babylon.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898
  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. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=babylon.pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /**
  1460. * Constant used to convert a value to gamma space
  1461. * @ignorenaming
  1462. */
  1463. BABYLON.ToGammaSpace = 1 / 2.2;
  1464. /**
  1465. * Constant used to convert a value to linear space
  1466. * @ignorenaming
  1467. */
  1468. BABYLON.ToLinearSpace = 2.2;
  1469. /**
  1470. * Constant used to define the minimal number value in Babylon.js
  1471. * @ignorenaming
  1472. */
  1473. BABYLON.Epsilon = 0.001;
  1474. /**
  1475. * Class used to hold a RBG color
  1476. */
  1477. var Color3 = /** @class */ (function () {
  1478. /**
  1479. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1480. * @param r defines the red component (between 0 and 1, default is 0)
  1481. * @param g defines the green component (between 0 and 1, default is 0)
  1482. * @param b defines the blue component (between 0 and 1, default is 0)
  1483. */
  1484. function Color3(
  1485. /**
  1486. * Defines the red component (between 0 and 1, default is 0)
  1487. */
  1488. r,
  1489. /**
  1490. * Defines the green component (between 0 and 1, default is 0)
  1491. */
  1492. g,
  1493. /**
  1494. * Defines the blue component (between 0 and 1, default is 0)
  1495. */
  1496. b) {
  1497. if (r === void 0) { r = 0; }
  1498. if (g === void 0) { g = 0; }
  1499. if (b === void 0) { b = 0; }
  1500. this.r = r;
  1501. this.g = g;
  1502. this.b = b;
  1503. }
  1504. /**
  1505. * Creates a string with the Color3 current values
  1506. * @returns the string representation of the Color3 object
  1507. */
  1508. Color3.prototype.toString = function () {
  1509. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1510. };
  1511. /**
  1512. * Returns the string "Color3"
  1513. * @returns "Color3"
  1514. */
  1515. Color3.prototype.getClassName = function () {
  1516. return "Color3";
  1517. };
  1518. /**
  1519. * Compute the Color3 hash code
  1520. * @returns an unique number that can be used to hash Color3 objects
  1521. */
  1522. Color3.prototype.getHashCode = function () {
  1523. var hash = this.r || 0;
  1524. hash = (hash * 397) ^ (this.g || 0);
  1525. hash = (hash * 397) ^ (this.b || 0);
  1526. return hash;
  1527. };
  1528. // Operators
  1529. /**
  1530. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1531. * @param array defines the array where to store the r,g,b components
  1532. * @param index defines an optional index in the target array to define where to start storing values
  1533. * @returns the current Color3 object
  1534. */
  1535. Color3.prototype.toArray = function (array, index) {
  1536. if (index === undefined) {
  1537. index = 0;
  1538. }
  1539. array[index] = this.r;
  1540. array[index + 1] = this.g;
  1541. array[index + 2] = this.b;
  1542. return this;
  1543. };
  1544. /**
  1545. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1546. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1547. * @returns a new {BABYLON.Color4} object
  1548. */
  1549. Color3.prototype.toColor4 = function (alpha) {
  1550. if (alpha === void 0) { alpha = 1; }
  1551. return new Color4(this.r, this.g, this.b, alpha);
  1552. };
  1553. /**
  1554. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1555. * @returns the new array
  1556. */
  1557. Color3.prototype.asArray = function () {
  1558. var result = new Array();
  1559. this.toArray(result, 0);
  1560. return result;
  1561. };
  1562. /**
  1563. * Returns the luminance value
  1564. * @returns a float value
  1565. */
  1566. Color3.prototype.toLuminance = function () {
  1567. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1568. };
  1569. /**
  1570. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3 object
  1573. */
  1574. Color3.prototype.multiply = function (otherColor) {
  1575. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1576. };
  1577. /**
  1578. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines the Color3 object where to store the result
  1581. * @returns the current Color3
  1582. */
  1583. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1584. result.r = this.r * otherColor.r;
  1585. result.g = this.g * otherColor.g;
  1586. result.b = this.b * otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Determines equality between Color3 objects
  1591. * @param otherColor defines the second operand
  1592. * @returns true if the rgb values are equal to the given ones
  1593. */
  1594. Color3.prototype.equals = function (otherColor) {
  1595. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1596. };
  1597. /**
  1598. * Determines equality between the current Color3 object and a set of r,b,g values
  1599. * @param r defines the red component to check
  1600. * @param g defines the green component to check
  1601. * @param b defines the blue component to check
  1602. * @returns true if the rgb values are equal to the given ones
  1603. */
  1604. Color3.prototype.equalsFloats = function (r, g, b) {
  1605. return this.r === r && this.g === g && this.b === b;
  1606. };
  1607. /**
  1608. * Multiplies in place each rgb value by scale
  1609. * @param scale defines the scaling factor
  1610. * @returns the updated Color3
  1611. */
  1612. Color3.prototype.scale = function (scale) {
  1613. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1614. };
  1615. /**
  1616. * Multiplies the rgb values by scale and stores the result into "result"
  1617. * @param scale defines the scaling factor
  1618. * @param result defines the Color3 object where to store the result
  1619. * @returns the unmodified current Color3
  1620. */
  1621. Color3.prototype.scaleToRef = function (scale, result) {
  1622. result.r = this.r * scale;
  1623. result.g = this.g * scale;
  1624. result.b = this.b * scale;
  1625. return this;
  1626. };
  1627. /**
  1628. * Scale the current Color3 values by a factor and add the result to a given Color3
  1629. * @param scale defines the scale factor
  1630. * @param result defines color to store the result into
  1631. * @returns the unmodified current Color3
  1632. */
  1633. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1634. result.r += this.r * scale;
  1635. result.g += this.g * scale;
  1636. result.b += this.b * scale;
  1637. return this;
  1638. };
  1639. /**
  1640. * Clamps the rgb values by the min and max values and stores the result into "result"
  1641. * @param min defines minimum clamping value (default is 0)
  1642. * @param max defines maximum clamping value (default is 1)
  1643. * @param result defines color to store the result into
  1644. * @returns the original Color3
  1645. */
  1646. Color3.prototype.clampToRef = function (min, max, result) {
  1647. if (min === void 0) { min = 0; }
  1648. if (max === void 0) { max = 1; }
  1649. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1650. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1651. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1652. return this;
  1653. };
  1654. /**
  1655. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1656. * @param otherColor defines the second operand
  1657. * @returns the new Color3
  1658. */
  1659. Color3.prototype.add = function (otherColor) {
  1660. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1661. };
  1662. /**
  1663. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1664. * @param otherColor defines the second operand
  1665. * @param result defines Color3 object to store the result into
  1666. * @returns the unmodified current Color3
  1667. */
  1668. Color3.prototype.addToRef = function (otherColor, result) {
  1669. result.r = this.r + otherColor.r;
  1670. result.g = this.g + otherColor.g;
  1671. result.b = this.b + otherColor.b;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1676. * @param otherColor defines the second operand
  1677. * @returns the new Color3
  1678. */
  1679. Color3.prototype.subtract = function (otherColor) {
  1680. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1681. };
  1682. /**
  1683. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1684. * @param otherColor defines the second operand
  1685. * @param result defines Color3 object to store the result into
  1686. * @returns the unmodified current Color3
  1687. */
  1688. Color3.prototype.subtractToRef = function (otherColor, result) {
  1689. result.r = this.r - otherColor.r;
  1690. result.g = this.g - otherColor.g;
  1691. result.b = this.b - otherColor.b;
  1692. return this;
  1693. };
  1694. /**
  1695. * Copy the current object
  1696. * @returns a new Color3 copied the current one
  1697. */
  1698. Color3.prototype.clone = function () {
  1699. return new Color3(this.r, this.g, this.b);
  1700. };
  1701. /**
  1702. * Copies the rgb values from the source in the current Color3
  1703. * @param source defines the source Color3 object
  1704. * @returns the updated Color3 object
  1705. */
  1706. Color3.prototype.copyFrom = function (source) {
  1707. this.r = source.r;
  1708. this.g = source.g;
  1709. this.b = source.b;
  1710. return this;
  1711. };
  1712. /**
  1713. * Updates the Color3 rgb values from the given floats
  1714. * @param r defines the red component to read from
  1715. * @param g defines the green component to read from
  1716. * @param b defines the blue component to read from
  1717. * @returns the current Color3 object
  1718. */
  1719. Color3.prototype.copyFromFloats = function (r, g, b) {
  1720. this.r = r;
  1721. this.g = g;
  1722. this.b = b;
  1723. return this;
  1724. };
  1725. /**
  1726. * Updates the Color3 rgb values from the given floats
  1727. * @param r defines the red component to read from
  1728. * @param g defines the green component to read from
  1729. * @param b defines the blue component to read from
  1730. * @returns the current Color3 object
  1731. */
  1732. Color3.prototype.set = function (r, g, b) {
  1733. return this.copyFromFloats(r, g, b);
  1734. };
  1735. /**
  1736. * Compute the Color3 hexadecimal code as a string
  1737. * @returns a string containing the hexadecimal representation of the Color3 object
  1738. */
  1739. Color3.prototype.toHexString = function () {
  1740. var intR = (this.r * 255) | 0;
  1741. var intG = (this.g * 255) | 0;
  1742. var intB = (this.b * 255) | 0;
  1743. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1744. };
  1745. /**
  1746. * Computes a new Color3 converted from the current one to linear space
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.prototype.toLinearSpace = function () {
  1750. var convertedColor = new Color3();
  1751. this.toLinearSpaceToRef(convertedColor);
  1752. return convertedColor;
  1753. };
  1754. /**
  1755. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1756. * @param convertedColor defines the Color3 object where to store the linear space version
  1757. * @returns the unmodified Color3
  1758. */
  1759. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1760. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1761. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1762. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1763. return this;
  1764. };
  1765. /**
  1766. * Computes a new Color3 converted from the current one to gamma space
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.prototype.toGammaSpace = function () {
  1770. var convertedColor = new Color3();
  1771. this.toGammaSpaceToRef(convertedColor);
  1772. return convertedColor;
  1773. };
  1774. /**
  1775. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1776. * @param convertedColor defines the Color3 object where to store the gamma space version
  1777. * @returns the unmodified Color3
  1778. */
  1779. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1780. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1781. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1782. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1783. return this;
  1784. };
  1785. // Statics
  1786. /**
  1787. * Creates a new Color3 from the string containing valid hexadecimal values
  1788. * @param hex defines a string containing valid hexadecimal values
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.FromHexString = function (hex) {
  1792. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1793. return new Color3(0, 0, 0);
  1794. }
  1795. var r = parseInt(hex.substring(1, 3), 16);
  1796. var g = parseInt(hex.substring(3, 5), 16);
  1797. var b = parseInt(hex.substring(5, 7), 16);
  1798. return Color3.FromInts(r, g, b);
  1799. };
  1800. /**
  1801. * Creates a new Vector3 from the starting index of the given array
  1802. * @param array defines the source array
  1803. * @param offset defines an offset in the source array
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.FromArray = function (array, offset) {
  1807. if (offset === void 0) { offset = 0; }
  1808. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1809. };
  1810. /**
  1811. * Creates a new Color3 from integer values (< 256)
  1812. * @param r defines the red component to read from (value between 0 and 255)
  1813. * @param g defines the green component to read from (value between 0 and 255)
  1814. * @param b defines the blue component to read from (value between 0 and 255)
  1815. * @returns a new Color3 object
  1816. */
  1817. Color3.FromInts = function (r, g, b) {
  1818. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1819. };
  1820. /**
  1821. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1822. * @param start defines the start Color3 value
  1823. * @param end defines the end Color3 value
  1824. * @param amount defines the gradient value between start and end
  1825. * @returns a new Color3 object
  1826. */
  1827. Color3.Lerp = function (start, end, amount) {
  1828. var result = new Color3(0.0, 0.0, 0.0);
  1829. Color3.LerpToRef(start, end, amount, result);
  1830. return result;
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param left defines the start value
  1835. * @param right defines the end value
  1836. * @param amount defines the gradient factor
  1837. * @param result defines the Color3 object where to store the result
  1838. */
  1839. Color3.LerpToRef = function (left, right, amount, result) {
  1840. result.r = left.r + ((right.r - left.r) * amount);
  1841. result.g = left.g + ((right.g - left.g) * amount);
  1842. result.b = left.b + ((right.b - left.b) * amount);
  1843. };
  1844. /**
  1845. * Returns a Color3 value containing a red color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Red = function () { return new Color3(1, 0, 0); };
  1849. /**
  1850. * Returns a Color3 value containing a green color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Green = function () { return new Color3(0, 1, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a blue color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a black color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Black = function () { return new Color3(0, 0, 0); };
  1864. /**
  1865. * Returns a Color3 value containing a white color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.White = function () { return new Color3(1, 1, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a purple color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1874. /**
  1875. * Returns a Color3 value containing a magenta color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1879. /**
  1880. * Returns a Color3 value containing a yellow color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1884. /**
  1885. * Returns a Color3 value containing a gray color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1889. /**
  1890. * Returns a Color3 value containing a teal color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1894. /**
  1895. * Returns a Color3 value containing a random color
  1896. * @returns a new Color3 object
  1897. */
  1898. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1899. return Color3;
  1900. }());
  1901. BABYLON.Color3 = Color3;
  1902. /**
  1903. * Class used to hold a RBGA color
  1904. */
  1905. var Color4 = /** @class */ (function () {
  1906. /**
  1907. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1908. * @param r defines the red component (between 0 and 1, default is 0)
  1909. * @param g defines the green component (between 0 and 1, default is 0)
  1910. * @param b defines the blue component (between 0 and 1, default is 0)
  1911. * @param a defines the alpha component (between 0 and 1, default is 1)
  1912. */
  1913. function Color4(
  1914. /**
  1915. * Defines the red component (between 0 and 1, default is 0)
  1916. */
  1917. r,
  1918. /**
  1919. * Defines the green component (between 0 and 1, default is 0)
  1920. */
  1921. g,
  1922. /**
  1923. * Defines the blue component (between 0 and 1, default is 0)
  1924. */
  1925. b,
  1926. /**
  1927. * Defines the alpha component (between 0 and 1, default is 1)
  1928. */
  1929. a) {
  1930. if (r === void 0) { r = 0; }
  1931. if (g === void 0) { g = 0; }
  1932. if (b === void 0) { b = 0; }
  1933. if (a === void 0) { a = 1; }
  1934. this.r = r;
  1935. this.g = g;
  1936. this.b = b;
  1937. this.a = a;
  1938. }
  1939. // Operators
  1940. /**
  1941. * Adds in place the given Color4 values to the current Color4 object
  1942. * @param right defines the second operand
  1943. * @returns the current updated Color4 object
  1944. */
  1945. Color4.prototype.addInPlace = function (right) {
  1946. this.r += right.r;
  1947. this.g += right.g;
  1948. this.b += right.b;
  1949. this.a += right.a;
  1950. return this;
  1951. };
  1952. /**
  1953. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1954. * @returns the new array
  1955. */
  1956. Color4.prototype.asArray = function () {
  1957. var result = new Array();
  1958. this.toArray(result, 0);
  1959. return result;
  1960. };
  1961. /**
  1962. * Stores from the starting index in the given array the Color4 successive values
  1963. * @param array defines the array where to store the r,g,b components
  1964. * @param index defines an optional index in the target array to define where to start storing values
  1965. * @returns the current Color4 object
  1966. */
  1967. Color4.prototype.toArray = function (array, index) {
  1968. if (index === undefined) {
  1969. index = 0;
  1970. }
  1971. array[index] = this.r;
  1972. array[index + 1] = this.g;
  1973. array[index + 2] = this.b;
  1974. array[index + 3] = this.a;
  1975. return this;
  1976. };
  1977. /**
  1978. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1979. * @param right defines the second operand
  1980. * @returns a new Color4 object
  1981. */
  1982. Color4.prototype.add = function (right) {
  1983. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1984. };
  1985. /**
  1986. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1987. * @param right defines the second operand
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.subtract = function (right) {
  1991. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1992. };
  1993. /**
  1994. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1995. * @param right defines the second operand
  1996. * @param result defines the Color4 object where to store the result
  1997. * @returns the current Color4 object
  1998. */
  1999. Color4.prototype.subtractToRef = function (right, result) {
  2000. result.r = this.r - right.r;
  2001. result.g = this.g - right.g;
  2002. result.b = this.b - right.b;
  2003. result.a = this.a - right.a;
  2004. return this;
  2005. };
  2006. /**
  2007. * Creates a new Color4 with the current Color4 values multiplied by scale
  2008. * @param scale defines the scaling factor to apply
  2009. * @returns a new Color4 object
  2010. */
  2011. Color4.prototype.scale = function (scale) {
  2012. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2013. };
  2014. /**
  2015. * Multiplies the current Color4 values by scale and stores the result in "result"
  2016. * @param scale defines the scaling factor to apply
  2017. * @param result defines the Color4 object where to store the result
  2018. * @returns the current unmodified Color4
  2019. */
  2020. Color4.prototype.scaleToRef = function (scale, result) {
  2021. result.r = this.r * scale;
  2022. result.g = this.g * scale;
  2023. result.b = this.b * scale;
  2024. result.a = this.a * scale;
  2025. return this;
  2026. };
  2027. /**
  2028. * Scale the current Color4 values by a factor and add the result to a given Color4
  2029. * @param scale defines the scale factor
  2030. * @param result defines the Color4 object where to store the result
  2031. * @returns the unmodified current Color4
  2032. */
  2033. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2034. result.r += this.r * scale;
  2035. result.g += this.g * scale;
  2036. result.b += this.b * scale;
  2037. result.a += this.a * scale;
  2038. return this;
  2039. };
  2040. /**
  2041. * Clamps the rgb values by the min and max values and stores the result into "result"
  2042. * @param min defines minimum clamping value (default is 0)
  2043. * @param max defines maximum clamping value (default is 1)
  2044. * @param result defines color to store the result into.
  2045. * @returns the cuurent Color4
  2046. */
  2047. Color4.prototype.clampToRef = function (min, max, result) {
  2048. if (min === void 0) { min = 0; }
  2049. if (max === void 0) { max = 1; }
  2050. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2051. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2052. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2053. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2054. return this;
  2055. };
  2056. /**
  2057. * Multipy an Color4 value by another and return a new Color4 object
  2058. * @param color defines the Color4 value to multiply by
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.prototype.multiply = function (color) {
  2062. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2063. };
  2064. /**
  2065. * Multipy a Color4 value by another and push the result in a reference value
  2066. * @param color defines the Color4 value to multiply by
  2067. * @param result defines the Color4 to fill the result in
  2068. * @returns the result Color4
  2069. */
  2070. Color4.prototype.multiplyToRef = function (color, result) {
  2071. result.r = this.r * color.r;
  2072. result.g = this.g * color.g;
  2073. result.b = this.b * color.b;
  2074. result.a = this.a * color.a;
  2075. return result;
  2076. };
  2077. /**
  2078. * Creates a string with the Color4 current values
  2079. * @returns the string representation of the Color4 object
  2080. */
  2081. Color4.prototype.toString = function () {
  2082. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2083. };
  2084. /**
  2085. * Returns the string "Color4"
  2086. * @returns "Color4"
  2087. */
  2088. Color4.prototype.getClassName = function () {
  2089. return "Color4";
  2090. };
  2091. /**
  2092. * Compute the Color4 hash code
  2093. * @returns an unique number that can be used to hash Color4 objects
  2094. */
  2095. Color4.prototype.getHashCode = function () {
  2096. var hash = this.r || 0;
  2097. hash = (hash * 397) ^ (this.g || 0);
  2098. hash = (hash * 397) ^ (this.b || 0);
  2099. hash = (hash * 397) ^ (this.a || 0);
  2100. return hash;
  2101. };
  2102. /**
  2103. * Creates a new Color4 copied from the current one
  2104. * @returns a new Color4 object
  2105. */
  2106. Color4.prototype.clone = function () {
  2107. return new Color4(this.r, this.g, this.b, this.a);
  2108. };
  2109. /**
  2110. * Copies the given Color4 values into the current one
  2111. * @param source defines the source Color4 object
  2112. * @returns the current updated Color4 object
  2113. */
  2114. Color4.prototype.copyFrom = function (source) {
  2115. this.r = source.r;
  2116. this.g = source.g;
  2117. this.b = source.b;
  2118. this.a = source.a;
  2119. return this;
  2120. };
  2121. /**
  2122. * Copies the given float values into the current one
  2123. * @param r defines the red component to read from
  2124. * @param g defines the green component to read from
  2125. * @param b defines the blue component to read from
  2126. * @param a defines the alpha component to read from
  2127. * @returns the current updated Color4 object
  2128. */
  2129. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2130. this.r = r;
  2131. this.g = g;
  2132. this.b = b;
  2133. this.a = a;
  2134. return this;
  2135. };
  2136. /**
  2137. * Copies the given float values into the current one
  2138. * @param r defines the red component to read from
  2139. * @param g defines the green component to read from
  2140. * @param b defines the blue component to read from
  2141. * @param a defines the alpha component to read from
  2142. * @returns the current updated Color4 object
  2143. */
  2144. Color4.prototype.set = function (r, g, b, a) {
  2145. return this.copyFromFloats(r, g, b, a);
  2146. };
  2147. /**
  2148. * Compute the Color4 hexadecimal code as a string
  2149. * @returns a string containing the hexadecimal representation of the Color4 object
  2150. */
  2151. Color4.prototype.toHexString = function () {
  2152. var intR = (this.r * 255) | 0;
  2153. var intG = (this.g * 255) | 0;
  2154. var intB = (this.b * 255) | 0;
  2155. var intA = (this.a * 255) | 0;
  2156. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2157. };
  2158. /**
  2159. * Computes a new Color4 converted from the current one to linear space
  2160. * @returns a new Color4 object
  2161. */
  2162. Color4.prototype.toLinearSpace = function () {
  2163. var convertedColor = new Color4();
  2164. this.toLinearSpaceToRef(convertedColor);
  2165. return convertedColor;
  2166. };
  2167. /**
  2168. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2169. * @param convertedColor defines the Color4 object where to store the linear space version
  2170. * @returns the unmodified Color4
  2171. */
  2172. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2173. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2174. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2175. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2176. convertedColor.a = this.a;
  2177. return this;
  2178. };
  2179. /**
  2180. * Computes a new Color4 converted from the current one to gamma space
  2181. * @returns a new Color4 object
  2182. */
  2183. Color4.prototype.toGammaSpace = function () {
  2184. var convertedColor = new Color4();
  2185. this.toGammaSpaceToRef(convertedColor);
  2186. return convertedColor;
  2187. };
  2188. /**
  2189. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2190. * @param convertedColor defines the Color4 object where to store the gamma space version
  2191. * @returns the unmodified Color4
  2192. */
  2193. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2194. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2195. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2196. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2197. convertedColor.a = this.a;
  2198. return this;
  2199. };
  2200. // Statics
  2201. /**
  2202. * Creates a new Color4 from the string containing valid hexadecimal values
  2203. * @param hex defines a string containing valid hexadecimal values
  2204. * @returns a new Color4 object
  2205. */
  2206. Color4.FromHexString = function (hex) {
  2207. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2208. return new Color4(0.0, 0.0, 0.0, 0.0);
  2209. }
  2210. var r = parseInt(hex.substring(1, 3), 16);
  2211. var g = parseInt(hex.substring(3, 5), 16);
  2212. var b = parseInt(hex.substring(5, 7), 16);
  2213. var a = parseInt(hex.substring(7, 9), 16);
  2214. return Color4.FromInts(r, g, b, a);
  2215. };
  2216. /**
  2217. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @returns a new Color4 object
  2222. */
  2223. Color4.Lerp = function (left, right, amount) {
  2224. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2225. Color4.LerpToRef(left, right, amount, result);
  2226. return result;
  2227. };
  2228. /**
  2229. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2230. * @param left defines the start value
  2231. * @param right defines the end value
  2232. * @param amount defines the gradient factor
  2233. * @param result defines the Color4 object where to store data
  2234. */
  2235. Color4.LerpToRef = function (left, right, amount, result) {
  2236. result.r = left.r + (right.r - left.r) * amount;
  2237. result.g = left.g + (right.g - left.g) * amount;
  2238. result.b = left.b + (right.b - left.b) * amount;
  2239. result.a = left.a + (right.a - left.a) * amount;
  2240. };
  2241. /**
  2242. * Creates a new Color4 from a Color3 and an alpha value
  2243. * @param color3 defines the source Color3 to read from
  2244. * @param alpha defines the alpha component (1.0 by default)
  2245. * @returns a new Color4 object
  2246. */
  2247. Color4.FromColor3 = function (color3, alpha) {
  2248. if (alpha === void 0) { alpha = 1.0; }
  2249. return new Color4(color3.r, color3.g, color3.b, alpha);
  2250. };
  2251. /**
  2252. * Creates a new Color4 from the starting index element of the given array
  2253. * @param array defines the source array to read from
  2254. * @param offset defines the offset in the source array
  2255. * @returns a new Color4 object
  2256. */
  2257. Color4.FromArray = function (array, offset) {
  2258. if (offset === void 0) { offset = 0; }
  2259. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2260. };
  2261. /**
  2262. * Creates a new Color3 from integer values (< 256)
  2263. * @param r defines the red component to read from (value between 0 and 255)
  2264. * @param g defines the green component to read from (value between 0 and 255)
  2265. * @param b defines the blue component to read from (value between 0 and 255)
  2266. * @param a defines the alpha component to read from (value between 0 and 255)
  2267. * @returns a new Color3 object
  2268. */
  2269. Color4.FromInts = function (r, g, b, a) {
  2270. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2271. };
  2272. /**
  2273. * Check the content of a given array and convert it to an array containing RGBA data
  2274. * If the original array was already containing count * 4 values then it is returned directly
  2275. * @param colors defines the array to check
  2276. * @param count defines the number of RGBA data to expect
  2277. * @returns an array containing count * 4 values (RGBA)
  2278. */
  2279. Color4.CheckColors4 = function (colors, count) {
  2280. // Check if color3 was used
  2281. if (colors.length === count * 3) {
  2282. var colors4 = [];
  2283. for (var index = 0; index < colors.length; index += 3) {
  2284. var newIndex = (index / 3) * 4;
  2285. colors4[newIndex] = colors[index];
  2286. colors4[newIndex + 1] = colors[index + 1];
  2287. colors4[newIndex + 2] = colors[index + 2];
  2288. colors4[newIndex + 3] = 1.0;
  2289. }
  2290. return colors4;
  2291. }
  2292. return colors;
  2293. };
  2294. return Color4;
  2295. }());
  2296. BABYLON.Color4 = Color4;
  2297. /**
  2298. * Class representing a vector containing 2 coordinates
  2299. */
  2300. var Vector2 = /** @class */ (function () {
  2301. /**
  2302. * Creates a new Vector2 from the given x and y coordinates
  2303. * @param x defines the first coordinate
  2304. * @param y defines the second coordinate
  2305. */
  2306. function Vector2(
  2307. /** defines the first coordinate */
  2308. x,
  2309. /** defines the second coordinate */
  2310. y) {
  2311. if (x === void 0) { x = 0; }
  2312. if (y === void 0) { y = 0; }
  2313. this.x = x;
  2314. this.y = y;
  2315. }
  2316. /**
  2317. * Gets a string with the Vector2 coordinates
  2318. * @returns a string with the Vector2 coordinates
  2319. */
  2320. Vector2.prototype.toString = function () {
  2321. return "{X: " + this.x + " Y:" + this.y + "}";
  2322. };
  2323. /**
  2324. * Gets class name
  2325. * @returns the string "Vector2"
  2326. */
  2327. Vector2.prototype.getClassName = function () {
  2328. return "Vector2";
  2329. };
  2330. /**
  2331. * Gets current vector hash code
  2332. * @returns the Vector2 hash code as a number
  2333. */
  2334. Vector2.prototype.getHashCode = function () {
  2335. var hash = this.x || 0;
  2336. hash = (hash * 397) ^ (this.y || 0);
  2337. return hash;
  2338. };
  2339. // Operators
  2340. /**
  2341. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2342. * @param array defines the source array
  2343. * @param index defines the offset in source array
  2344. * @returns the current Vector2
  2345. */
  2346. Vector2.prototype.toArray = function (array, index) {
  2347. if (index === void 0) { index = 0; }
  2348. array[index] = this.x;
  2349. array[index + 1] = this.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Copy the current vector to an array
  2354. * @returns a new array with 2 elements: the Vector2 coordinates.
  2355. */
  2356. Vector2.prototype.asArray = function () {
  2357. var result = new Array();
  2358. this.toArray(result, 0);
  2359. return result;
  2360. };
  2361. /**
  2362. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2363. * @param source defines the source Vector2
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.copyFrom = function (source) {
  2367. this.x = source.x;
  2368. this.y = source.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Sets the Vector2 coordinates with the given floats
  2373. * @param x defines the first coordinate
  2374. * @param y defines the second coordinate
  2375. * @returns the current updated Vector2
  2376. */
  2377. Vector2.prototype.copyFromFloats = function (x, y) {
  2378. this.x = x;
  2379. this.y = y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Sets the Vector2 coordinates with the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.set = function (x, y) {
  2389. return this.copyFromFloats(x, y);
  2390. };
  2391. /**
  2392. * Add another vector with the current one
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2395. */
  2396. Vector2.prototype.add = function (otherVector) {
  2397. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.addToRef = function (otherVector, result) {
  2406. result.x = this.x + otherVector.x;
  2407. result.y = this.y + otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.addInPlace = function (otherVector) {
  2416. this.x += otherVector.x;
  2417. this.y += otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.addVector3 = function (otherVector) {
  2426. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2427. };
  2428. /**
  2429. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2430. * @param otherVector defines the other vector
  2431. * @returns a new Vector2
  2432. */
  2433. Vector2.prototype.subtract = function (otherVector) {
  2434. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2435. };
  2436. /**
  2437. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2438. * @param otherVector defines the other vector
  2439. * @param result defines the target vector
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2443. result.x = this.x - otherVector.x;
  2444. result.y = this.y - otherVector.y;
  2445. return this;
  2446. };
  2447. /**
  2448. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns the current updated Vector2
  2451. */
  2452. Vector2.prototype.subtractInPlace = function (otherVector) {
  2453. this.x -= otherVector.x;
  2454. this.y -= otherVector.y;
  2455. return this;
  2456. };
  2457. /**
  2458. * Multiplies in place the current Vector2 coordinates by the given ones
  2459. * @param otherVector defines the other vector
  2460. * @returns the current updated Vector2
  2461. */
  2462. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2463. this.x *= otherVector.x;
  2464. this.y *= otherVector.y;
  2465. return this;
  2466. };
  2467. /**
  2468. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2469. * @param otherVector defines the other vector
  2470. * @returns a new Vector2
  2471. */
  2472. Vector2.prototype.multiply = function (otherVector) {
  2473. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2474. };
  2475. /**
  2476. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2477. * @param otherVector defines the other vector
  2478. * @param result defines the target vector
  2479. * @returns the unmodified current Vector2
  2480. */
  2481. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2482. result.x = this.x * otherVector.x;
  2483. result.y = this.y * otherVector.y;
  2484. return this;
  2485. };
  2486. /**
  2487. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2488. * @param x defines the first coordinate
  2489. * @param y defines the second coordinate
  2490. * @returns a new Vector2
  2491. */
  2492. Vector2.prototype.multiplyByFloats = function (x, y) {
  2493. return new Vector2(this.x * x, this.y * y);
  2494. };
  2495. /**
  2496. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2497. * @param otherVector defines the other vector
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.divide = function (otherVector) {
  2501. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2502. };
  2503. /**
  2504. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2505. * @param otherVector defines the other vector
  2506. * @param result defines the target vector
  2507. * @returns the unmodified current Vector2
  2508. */
  2509. Vector2.prototype.divideToRef = function (otherVector, result) {
  2510. result.x = this.x / otherVector.x;
  2511. result.y = this.y / otherVector.y;
  2512. return this;
  2513. };
  2514. /**
  2515. * Divides the current Vector2 coordinates by the given ones
  2516. * @param otherVector defines the other vector
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.divideInPlace = function (otherVector) {
  2520. return this.divideToRef(otherVector, this);
  2521. };
  2522. /**
  2523. * Gets a new Vector2 with current Vector2 negated coordinates
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.prototype.negate = function () {
  2527. return new Vector2(-this.x, -this.y);
  2528. };
  2529. /**
  2530. * Multiply the Vector2 coordinates by scale
  2531. * @param scale defines the scaling factor
  2532. * @returns the current updated Vector2
  2533. */
  2534. Vector2.prototype.scaleInPlace = function (scale) {
  2535. this.x *= scale;
  2536. this.y *= scale;
  2537. return this;
  2538. };
  2539. /**
  2540. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2541. * @param scale defines the scaling factor
  2542. * @returns a new Vector2
  2543. */
  2544. Vector2.prototype.scale = function (scale) {
  2545. var result = new Vector2(0, 0);
  2546. this.scaleToRef(scale, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Scale the current Vector2 values by a factor to a given Vector2
  2551. * @param scale defines the scale factor
  2552. * @param result defines the Vector2 object where to store the result
  2553. * @returns the unmodified current Vector2
  2554. */
  2555. Vector2.prototype.scaleToRef = function (scale, result) {
  2556. result.x = this.x * scale;
  2557. result.y = this.y * scale;
  2558. return this;
  2559. };
  2560. /**
  2561. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2562. * @param scale defines the scale factor
  2563. * @param result defines the Vector2 object where to store the result
  2564. * @returns the unmodified current Vector2
  2565. */
  2566. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2567. result.x += this.x * scale;
  2568. result.y += this.y * scale;
  2569. return this;
  2570. };
  2571. /**
  2572. * Gets a boolean if two vectors are equals
  2573. * @param otherVector defines the other vector
  2574. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2575. */
  2576. Vector2.prototype.equals = function (otherVector) {
  2577. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2578. };
  2579. /**
  2580. * Gets a boolean if two vectors are equals (using an epsilon value)
  2581. * @param otherVector defines the other vector
  2582. * @param epsilon defines the minimal distance to consider equality
  2583. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2584. */
  2585. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2586. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2587. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2588. };
  2589. /**
  2590. * Gets a new Vector2 from current Vector2 floored values
  2591. * @returns a new Vector2
  2592. */
  2593. Vector2.prototype.floor = function () {
  2594. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2595. };
  2596. /**
  2597. * Gets a new Vector2 from current Vector2 floored values
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.fract = function () {
  2601. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2602. };
  2603. // Properties
  2604. /**
  2605. * Gets the length of the vector
  2606. * @returns the vector length (float)
  2607. */
  2608. Vector2.prototype.length = function () {
  2609. return Math.sqrt(this.x * this.x + this.y * this.y);
  2610. };
  2611. /**
  2612. * Gets the vector squared length
  2613. * @returns the vector squared length (float)
  2614. */
  2615. Vector2.prototype.lengthSquared = function () {
  2616. return (this.x * this.x + this.y * this.y);
  2617. };
  2618. // Methods
  2619. /**
  2620. * Normalize the vector
  2621. * @returns the current updated Vector2
  2622. */
  2623. Vector2.prototype.normalize = function () {
  2624. var len = this.length();
  2625. if (len === 0)
  2626. return this;
  2627. var num = 1.0 / len;
  2628. this.x *= num;
  2629. this.y *= num;
  2630. return this;
  2631. };
  2632. /**
  2633. * Gets a new Vector2 copied from the Vector2
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.prototype.clone = function () {
  2637. return new Vector2(this.x, this.y);
  2638. };
  2639. // Statics
  2640. /**
  2641. * Gets a new Vector2(0, 0)
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Zero = function () {
  2645. return new Vector2(0, 0);
  2646. };
  2647. /**
  2648. * Gets a new Vector2(1, 1)
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.One = function () {
  2652. return new Vector2(1, 1);
  2653. };
  2654. /**
  2655. * Gets a new Vector2 set from the given index element of the given array
  2656. * @param array defines the data source
  2657. * @param offset defines the offset in the data source
  2658. * @returns a new Vector2
  2659. */
  2660. Vector2.FromArray = function (array, offset) {
  2661. if (offset === void 0) { offset = 0; }
  2662. return new Vector2(array[offset], array[offset + 1]);
  2663. };
  2664. /**
  2665. * Sets "result" from the given index element of the given array
  2666. * @param array defines the data source
  2667. * @param offset defines the offset in the data source
  2668. * @param result defines the target vector
  2669. */
  2670. Vector2.FromArrayToRef = function (array, offset, result) {
  2671. result.x = array[offset];
  2672. result.y = array[offset + 1];
  2673. };
  2674. /**
  2675. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2676. * @param value1 defines 1st point of control
  2677. * @param value2 defines 2nd point of control
  2678. * @param value3 defines 3rd point of control
  2679. * @param value4 defines 4th point of control
  2680. * @param amount defines the interpolation factor
  2681. * @returns a new Vector2
  2682. */
  2683. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2684. var squared = amount * amount;
  2685. var cubed = amount * squared;
  2686. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2687. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2688. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2689. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2690. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2691. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2692. return new Vector2(x, y);
  2693. };
  2694. /**
  2695. * 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".
  2696. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2697. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2698. * @param value defines the value to clamp
  2699. * @param min defines the lower limit
  2700. * @param max defines the upper limit
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Clamp = function (value, min, max) {
  2704. var x = value.x;
  2705. x = (x > max.x) ? max.x : x;
  2706. x = (x < min.x) ? min.x : x;
  2707. var y = value.y;
  2708. y = (y > max.y) ? max.y : y;
  2709. y = (y < min.y) ? min.y : y;
  2710. return new Vector2(x, y);
  2711. };
  2712. /**
  2713. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2714. * @param value1 defines the 1st control point
  2715. * @param tangent1 defines the outgoing tangent
  2716. * @param value2 defines the 2nd control point
  2717. * @param tangent2 defines the incoming tangent
  2718. * @param amount defines the interpolation factor
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2722. var squared = amount * amount;
  2723. var cubed = amount * squared;
  2724. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2725. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2726. var part3 = (cubed - (2.0 * squared)) + amount;
  2727. var part4 = cubed - squared;
  2728. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2729. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2730. return new Vector2(x, y);
  2731. };
  2732. /**
  2733. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2734. * @param start defines the start vector
  2735. * @param end defines the end vector
  2736. * @param amount defines the interpolation factor
  2737. * @returns a new Vector2
  2738. */
  2739. Vector2.Lerp = function (start, end, amount) {
  2740. var x = start.x + ((end.x - start.x) * amount);
  2741. var y = start.y + ((end.y - start.y) * amount);
  2742. return new Vector2(x, y);
  2743. };
  2744. /**
  2745. * Gets the dot product of the vector "left" and the vector "right"
  2746. * @param left defines first vector
  2747. * @param right defines second vector
  2748. * @returns the dot product (float)
  2749. */
  2750. Vector2.Dot = function (left, right) {
  2751. return left.x * right.x + left.y * right.y;
  2752. };
  2753. /**
  2754. * Returns a new Vector2 equal to the normalized given vector
  2755. * @param vector defines the vector to normalize
  2756. * @returns a new Vector2
  2757. */
  2758. Vector2.Normalize = function (vector) {
  2759. var newVector = vector.clone();
  2760. newVector.normalize();
  2761. return newVector;
  2762. };
  2763. /**
  2764. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2765. * @param left defines 1st vector
  2766. * @param right defines 2nd vector
  2767. * @returns a new Vector2
  2768. */
  2769. Vector2.Minimize = function (left, right) {
  2770. var x = (left.x < right.x) ? left.x : right.x;
  2771. var y = (left.y < right.y) ? left.y : right.y;
  2772. return new Vector2(x, y);
  2773. };
  2774. /**
  2775. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2776. * @param left defines 1st vector
  2777. * @param right defines 2nd vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Maximize = function (left, right) {
  2781. var x = (left.x > right.x) ? left.x : right.x;
  2782. var y = (left.y > right.y) ? left.y : right.y;
  2783. return new Vector2(x, y);
  2784. };
  2785. /**
  2786. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2787. * @param vector defines the vector to transform
  2788. * @param transformation defines the matrix to apply
  2789. * @returns a new Vector2
  2790. */
  2791. Vector2.Transform = function (vector, transformation) {
  2792. var r = Vector2.Zero();
  2793. Vector2.TransformToRef(vector, transformation, r);
  2794. return r;
  2795. };
  2796. /**
  2797. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2798. * @param vector defines the vector to transform
  2799. * @param transformation defines the matrix to apply
  2800. * @param result defines the target vector
  2801. */
  2802. Vector2.TransformToRef = function (vector, transformation, result) {
  2803. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2804. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2805. result.x = x;
  2806. result.y = y;
  2807. };
  2808. /**
  2809. * Determines if a given vector is included in a triangle
  2810. * @param p defines the vector to test
  2811. * @param p0 defines 1st triangle point
  2812. * @param p1 defines 2nd triangle point
  2813. * @param p2 defines 3rd triangle point
  2814. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2815. */
  2816. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2817. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2818. var sign = a < 0 ? -1 : 1;
  2819. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2820. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2821. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2822. };
  2823. /**
  2824. * Gets the distance between the vectors "value1" and "value2"
  2825. * @param value1 defines first vector
  2826. * @param value2 defines second vector
  2827. * @returns the distance between vectors
  2828. */
  2829. Vector2.Distance = function (value1, value2) {
  2830. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2831. };
  2832. /**
  2833. * Returns the squared distance between the vectors "value1" and "value2"
  2834. * @param value1 defines first vector
  2835. * @param value2 defines second vector
  2836. * @returns the squared distance between vectors
  2837. */
  2838. Vector2.DistanceSquared = function (value1, value2) {
  2839. var x = value1.x - value2.x;
  2840. var y = value1.y - value2.y;
  2841. return (x * x) + (y * y);
  2842. };
  2843. /**
  2844. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2845. * @param value1 defines first vector
  2846. * @param value2 defines second vector
  2847. * @returns a new Vector2
  2848. */
  2849. Vector2.Center = function (value1, value2) {
  2850. var center = value1.add(value2);
  2851. center.scaleInPlace(0.5);
  2852. return center;
  2853. };
  2854. /**
  2855. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2856. * @param p defines the middle point
  2857. * @param segA defines one point of the segment
  2858. * @param segB defines the other point of the segment
  2859. * @returns the shortest distance
  2860. */
  2861. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2862. var l2 = Vector2.DistanceSquared(segA, segB);
  2863. if (l2 === 0.0) {
  2864. return Vector2.Distance(p, segA);
  2865. }
  2866. var v = segB.subtract(segA);
  2867. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2868. var proj = segA.add(v.multiplyByFloats(t, t));
  2869. return Vector2.Distance(p, proj);
  2870. };
  2871. return Vector2;
  2872. }());
  2873. BABYLON.Vector2 = Vector2;
  2874. /**
  2875. * Classed used to store (x,y,z) vector representation
  2876. * A Vector3 is the main object used in 3D geometry
  2877. * It can represent etiher the coordinates of a point the space, either a direction
  2878. * Reminder: Babylon.js uses a left handed forward facing system
  2879. */
  2880. var Vector3 = /** @class */ (function () {
  2881. /**
  2882. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2883. * @param x defines the first coordinates (on X axis)
  2884. * @param y defines the second coordinates (on Y axis)
  2885. * @param z defines the third coordinates (on Z axis)
  2886. */
  2887. function Vector3(
  2888. /**
  2889. * Defines the first coordinates (on X axis)
  2890. */
  2891. x,
  2892. /**
  2893. * Defines the second coordinates (on Y axis)
  2894. */
  2895. y,
  2896. /**
  2897. * Defines the third coordinates (on Z axis)
  2898. */
  2899. z) {
  2900. if (x === void 0) { x = 0; }
  2901. if (y === void 0) { y = 0; }
  2902. if (z === void 0) { z = 0; }
  2903. this.x = x;
  2904. this.y = y;
  2905. this.z = z;
  2906. }
  2907. /**
  2908. * Creates a string representation of the Vector3
  2909. * @returns a string with the Vector3 coordinates.
  2910. */
  2911. Vector3.prototype.toString = function () {
  2912. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2913. };
  2914. /**
  2915. * Gets the class name
  2916. * @returns the string "Vector3"
  2917. */
  2918. Vector3.prototype.getClassName = function () {
  2919. return "Vector3";
  2920. };
  2921. /**
  2922. * Creates the Vector3 hash code
  2923. * @returns a number which tends to be unique between Vector3 instances
  2924. */
  2925. Vector3.prototype.getHashCode = function () {
  2926. var hash = this.x || 0;
  2927. hash = (hash * 397) ^ (this.y || 0);
  2928. hash = (hash * 397) ^ (this.z || 0);
  2929. return hash;
  2930. };
  2931. // Operators
  2932. /**
  2933. * Creates an array containing three elements : the coordinates of the Vector3
  2934. * @returns a new array of numbers
  2935. */
  2936. Vector3.prototype.asArray = function () {
  2937. var result = [];
  2938. this.toArray(result, 0);
  2939. return result;
  2940. };
  2941. /**
  2942. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2943. * @param array defines the destination array
  2944. * @param index defines the offset in the destination array
  2945. * @returns the current Vector3
  2946. */
  2947. Vector3.prototype.toArray = function (array, index) {
  2948. if (index === void 0) { index = 0; }
  2949. array[index] = this.x;
  2950. array[index + 1] = this.y;
  2951. array[index + 2] = this.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2956. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2957. */
  2958. Vector3.prototype.toQuaternion = function () {
  2959. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2960. };
  2961. /**
  2962. * Adds the given vector to the current Vector3
  2963. * @param otherVector defines the second operand
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.addInPlace = function (otherVector) {
  2967. this.x += otherVector.x;
  2968. this.y += otherVector.y;
  2969. this.z += otherVector.z;
  2970. return this;
  2971. };
  2972. /**
  2973. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2974. * @param otherVector defines the second operand
  2975. * @returns the resulting Vector3
  2976. */
  2977. Vector3.prototype.add = function (otherVector) {
  2978. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2979. };
  2980. /**
  2981. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2982. * @param otherVector defines the second operand
  2983. * @param result defines the Vector3 object where to store the result
  2984. * @returns the current Vector3
  2985. */
  2986. Vector3.prototype.addToRef = function (otherVector, result) {
  2987. result.x = this.x + otherVector.x;
  2988. result.y = this.y + otherVector.y;
  2989. result.z = this.z + otherVector.z;
  2990. return this;
  2991. };
  2992. /**
  2993. * Subtract the given vector from the current Vector3
  2994. * @param otherVector defines the second operand
  2995. * @returns the current updated Vector3
  2996. */
  2997. Vector3.prototype.subtractInPlace = function (otherVector) {
  2998. this.x -= otherVector.x;
  2999. this.y -= otherVector.y;
  3000. this.z -= otherVector.z;
  3001. return this;
  3002. };
  3003. /**
  3004. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  3005. * @param otherVector defines the second operand
  3006. * @returns the resulting Vector3
  3007. */
  3008. Vector3.prototype.subtract = function (otherVector) {
  3009. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  3010. };
  3011. /**
  3012. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  3013. * @param otherVector defines the second operand
  3014. * @param result defines the Vector3 object where to store the result
  3015. * @returns the current Vector3
  3016. */
  3017. Vector3.prototype.subtractToRef = function (otherVector, result) {
  3018. result.x = this.x - otherVector.x;
  3019. result.y = this.y - otherVector.y;
  3020. result.z = this.z - otherVector.z;
  3021. return this;
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  3025. * @param x defines the x coordinate of the operand
  3026. * @param y defines the y coordinate of the operand
  3027. * @param z defines the z coordinate of the operand
  3028. * @returns the resulting Vector3
  3029. */
  3030. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3031. return new Vector3(this.x - x, this.y - y, this.z - z);
  3032. };
  3033. /**
  3034. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3035. * @param x defines the x coordinate of the operand
  3036. * @param y defines the y coordinate of the operand
  3037. * @param z defines the z coordinate of the operand
  3038. * @param result defines the Vector3 object where to store the result
  3039. * @returns the current Vector3
  3040. */
  3041. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3042. result.x = this.x - x;
  3043. result.y = this.y - y;
  3044. result.z = this.z - z;
  3045. return this;
  3046. };
  3047. /**
  3048. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3049. * @returns a new Vector3
  3050. */
  3051. Vector3.prototype.negate = function () {
  3052. return new Vector3(-this.x, -this.y, -this.z);
  3053. };
  3054. /**
  3055. * Multiplies the Vector3 coordinates by the float "scale"
  3056. * @param scale defines the multiplier factor
  3057. * @returns the current updated Vector3
  3058. */
  3059. Vector3.prototype.scaleInPlace = function (scale) {
  3060. this.x *= scale;
  3061. this.y *= scale;
  3062. this.z *= scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3067. * @param scale defines the multiplier factor
  3068. * @returns a new Vector3
  3069. */
  3070. Vector3.prototype.scale = function (scale) {
  3071. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3072. };
  3073. /**
  3074. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3075. * @param scale defines the multiplier factor
  3076. * @param result defines the Vector3 object where to store the result
  3077. * @returns the current Vector3
  3078. */
  3079. Vector3.prototype.scaleToRef = function (scale, result) {
  3080. result.x = this.x * scale;
  3081. result.y = this.y * scale;
  3082. result.z = this.z * scale;
  3083. return this;
  3084. };
  3085. /**
  3086. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3087. * @param scale defines the scale factor
  3088. * @param result defines the Vector3 object where to store the result
  3089. * @returns the unmodified current Vector3
  3090. */
  3091. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3092. result.x += this.x * scale;
  3093. result.y += this.y * scale;
  3094. result.z += this.z * scale;
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3099. * @param otherVector defines the second operand
  3100. * @returns true if both vectors are equals
  3101. */
  3102. Vector3.prototype.equals = function (otherVector) {
  3103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3104. };
  3105. /**
  3106. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3107. * @param otherVector defines the second operand
  3108. * @param epsilon defines the minimal distance to define values as equals
  3109. * @returns true if both vectors are distant less than epsilon
  3110. */
  3111. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3112. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3113. 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);
  3114. };
  3115. /**
  3116. * Returns true if the current Vector3 coordinates equals the given floats
  3117. * @param x defines the x coordinate of the operand
  3118. * @param y defines the y coordinate of the operand
  3119. * @param z defines the z coordinate of the operand
  3120. * @returns true if both vectors are equals
  3121. */
  3122. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3123. return this.x === x && this.y === y && this.z === z;
  3124. };
  3125. /**
  3126. * Multiplies the current Vector3 coordinates by the given ones
  3127. * @param otherVector defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3131. this.x *= otherVector.x;
  3132. this.y *= otherVector.y;
  3133. this.z *= otherVector.z;
  3134. return this;
  3135. };
  3136. /**
  3137. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3138. * @param otherVector defines the second operand
  3139. * @returns the new Vector3
  3140. */
  3141. Vector3.prototype.multiply = function (otherVector) {
  3142. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3143. };
  3144. /**
  3145. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3146. * @param otherVector defines the second operand
  3147. * @param result defines the Vector3 object where to store the result
  3148. * @returns the current Vector3
  3149. */
  3150. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3151. result.x = this.x * otherVector.x;
  3152. result.y = this.y * otherVector.y;
  3153. result.z = this.z * otherVector.z;
  3154. return this;
  3155. };
  3156. /**
  3157. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3158. * @param x defines the x coordinate of the operand
  3159. * @param y defines the y coordinate of the operand
  3160. * @param z defines the z coordinate of the operand
  3161. * @returns the new Vector3
  3162. */
  3163. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3164. return new Vector3(this.x * x, this.y * y, this.z * z);
  3165. };
  3166. /**
  3167. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3168. * @param otherVector defines the second operand
  3169. * @returns the new Vector3
  3170. */
  3171. Vector3.prototype.divide = function (otherVector) {
  3172. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3173. };
  3174. /**
  3175. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3176. * @param otherVector defines the second operand
  3177. * @param result defines the Vector3 object where to store the result
  3178. * @returns the current Vector3
  3179. */
  3180. Vector3.prototype.divideToRef = function (otherVector, result) {
  3181. result.x = this.x / otherVector.x;
  3182. result.y = this.y / otherVector.y;
  3183. result.z = this.z / otherVector.z;
  3184. return this;
  3185. };
  3186. /**
  3187. * Divides the current Vector3 coordinates by the given ones.
  3188. * @param otherVector defines the second operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.divideInPlace = function (otherVector) {
  3192. return this.divideToRef(otherVector, this);
  3193. };
  3194. /**
  3195. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3196. * @param other defines the second operand
  3197. * @returns the current updated Vector3
  3198. */
  3199. Vector3.prototype.minimizeInPlace = function (other) {
  3200. if (other.x < this.x)
  3201. this.x = other.x;
  3202. if (other.y < this.y)
  3203. this.y = other.y;
  3204. if (other.z < this.z)
  3205. this.z = other.z;
  3206. return this;
  3207. };
  3208. /**
  3209. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3210. * @param other defines the second operand
  3211. * @returns the current updated Vector3
  3212. */
  3213. Vector3.prototype.maximizeInPlace = function (other) {
  3214. if (other.x > this.x)
  3215. this.x = other.x;
  3216. if (other.y > this.y)
  3217. this.y = other.y;
  3218. if (other.z > this.z)
  3219. this.z = other.z;
  3220. return this;
  3221. };
  3222. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3223. /**
  3224. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3225. */
  3226. get: function () {
  3227. var absX = Math.abs(this.x);
  3228. var absY = Math.abs(this.y);
  3229. if (absX !== absY) {
  3230. return true;
  3231. }
  3232. var absZ = Math.abs(this.z);
  3233. if (absX !== absZ) {
  3234. return true;
  3235. }
  3236. if (absY !== absZ) {
  3237. return true;
  3238. }
  3239. return false;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. /**
  3245. * Gets a new Vector3 from current Vector3 floored values
  3246. * @returns a new Vector3
  3247. */
  3248. Vector3.prototype.floor = function () {
  3249. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3250. };
  3251. /**
  3252. * Gets a new Vector3 from current Vector3 floored values
  3253. * @returns a new Vector3
  3254. */
  3255. Vector3.prototype.fract = function () {
  3256. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3257. };
  3258. // Properties
  3259. /**
  3260. * Gets the length of the Vector3
  3261. * @returns the length of the Vecto3
  3262. */
  3263. Vector3.prototype.length = function () {
  3264. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3265. };
  3266. /**
  3267. * Gets the squared length of the Vector3
  3268. * @returns squared length of the Vector3
  3269. */
  3270. Vector3.prototype.lengthSquared = function () {
  3271. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3272. };
  3273. /**
  3274. * Normalize the current Vector3.
  3275. * Please note that this is an in place operation.
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.normalize = function () {
  3279. var len = this.length();
  3280. if (len === 0 || len === 1.0)
  3281. return this;
  3282. var num = 1.0 / len;
  3283. this.x *= num;
  3284. this.y *= num;
  3285. this.z *= num;
  3286. return this;
  3287. };
  3288. /**
  3289. * Normalize the current Vector3 to a new vector
  3290. * @returns the new Vector3
  3291. */
  3292. Vector3.prototype.normalizeToNew = function () {
  3293. var normalized = new Vector3(0, 0, 0);
  3294. this.normalizeToRef(normalized);
  3295. return normalized;
  3296. };
  3297. /**
  3298. * Normalize the current Vector3 to the reference
  3299. * @param reference define the Vector3 to update
  3300. * @returns the updated Vector3
  3301. */
  3302. Vector3.prototype.normalizeToRef = function (reference) {
  3303. var len = this.length();
  3304. if (len === 0 || len === 1.0) {
  3305. reference.set(this.x, this.y, this.z);
  3306. return reference;
  3307. }
  3308. var scale = 1.0 / len;
  3309. this.scaleToRef(scale, reference);
  3310. return reference;
  3311. };
  3312. /**
  3313. * Creates a new Vector3 copied from the current Vector3
  3314. * @returns the new Vector3
  3315. */
  3316. Vector3.prototype.clone = function () {
  3317. return new Vector3(this.x, this.y, this.z);
  3318. };
  3319. /**
  3320. * Copies the given vector coordinates to the current Vector3 ones
  3321. * @param source defines the source Vector3
  3322. * @returns the current updated Vector3
  3323. */
  3324. Vector3.prototype.copyFrom = function (source) {
  3325. this.x = source.x;
  3326. this.y = source.y;
  3327. this.z = source.z;
  3328. return this;
  3329. };
  3330. /**
  3331. * Copies the given floats to the current Vector3 coordinates
  3332. * @param x defines the x coordinate of the operand
  3333. * @param y defines the y coordinate of the operand
  3334. * @param z defines the z coordinate of the operand
  3335. * @returns the current updated Vector3
  3336. */
  3337. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3338. this.x = x;
  3339. this.y = y;
  3340. this.z = z;
  3341. return this;
  3342. };
  3343. /**
  3344. * Copies the given floats to the current Vector3 coordinates
  3345. * @param x defines the x coordinate of the operand
  3346. * @param y defines the y coordinate of the operand
  3347. * @param z defines the z coordinate of the operand
  3348. * @returns the current updated Vector3
  3349. */
  3350. Vector3.prototype.set = function (x, y, z) {
  3351. return this.copyFromFloats(x, y, z);
  3352. };
  3353. // Statics
  3354. /**
  3355. * Get the clip factor between two vectors
  3356. * @param vector0 defines the first operand
  3357. * @param vector1 defines the second operand
  3358. * @param axis defines the axis to use
  3359. * @param size defines the size along the axis
  3360. * @returns the clip factor
  3361. */
  3362. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3363. var d0 = Vector3.Dot(vector0, axis) - size;
  3364. var d1 = Vector3.Dot(vector1, axis) - size;
  3365. var s = d0 / (d0 - d1);
  3366. return s;
  3367. };
  3368. /**
  3369. * Get angle between two vectors
  3370. * @param vector0 angle between vector0 and vector1
  3371. * @param vector1 angle between vector0 and vector1
  3372. * @param normal direction of the normal
  3373. * @return the angle between vector0 and vector1
  3374. */
  3375. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3376. var v0 = vector0.clone().normalize();
  3377. var v1 = vector1.clone().normalize();
  3378. var dot = Vector3.Dot(v0, v1);
  3379. var n = Vector3.Cross(v0, v1);
  3380. if (Vector3.Dot(n, normal) > 0) {
  3381. return Math.acos(dot);
  3382. }
  3383. return -Math.acos(dot);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set from the index "offset" of the given array
  3387. * @param array defines the source array
  3388. * @param offset defines the offset in the source array
  3389. * @returns the new Vector3
  3390. */
  3391. Vector3.FromArray = function (array, offset) {
  3392. if (!offset) {
  3393. offset = 0;
  3394. }
  3395. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3396. };
  3397. /**
  3398. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3399. * This function is deprecated. Use FromArray instead
  3400. * @param array defines the source array
  3401. * @param offset defines the offset in the source array
  3402. * @returns the new Vector3
  3403. */
  3404. Vector3.FromFloatArray = function (array, offset) {
  3405. return Vector3.FromArray(array, offset);
  3406. };
  3407. /**
  3408. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3409. * @param array defines the source array
  3410. * @param offset defines the offset in the source array
  3411. * @param result defines the Vector3 where to store the result
  3412. */
  3413. Vector3.FromArrayToRef = function (array, offset, result) {
  3414. result.x = array[offset];
  3415. result.y = array[offset + 1];
  3416. result.z = array[offset + 2];
  3417. };
  3418. /**
  3419. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3420. * This function is deprecated. Use FromArrayToRef instead.
  3421. * @param array defines the source array
  3422. * @param offset defines the offset in the source array
  3423. * @param result defines the Vector3 where to store the result
  3424. */
  3425. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3426. return Vector3.FromArrayToRef(array, offset, result);
  3427. };
  3428. /**
  3429. * Sets the given vector "result" with the given floats.
  3430. * @param x defines the x coordinate of the source
  3431. * @param y defines the y coordinate of the source
  3432. * @param z defines the z coordinate of the source
  3433. * @param result defines the Vector3 where to store the result
  3434. */
  3435. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3436. result.x = x;
  3437. result.y = y;
  3438. result.z = z;
  3439. };
  3440. /**
  3441. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3442. * @returns a new empty Vector3
  3443. */
  3444. Vector3.Zero = function () {
  3445. return new Vector3(0.0, 0.0, 0.0);
  3446. };
  3447. /**
  3448. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3449. * @returns a new unit Vector3
  3450. */
  3451. Vector3.One = function () {
  3452. return new Vector3(1.0, 1.0, 1.0);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3456. * @returns a new up Vector3
  3457. */
  3458. Vector3.Up = function () {
  3459. return new Vector3(0.0, 1.0, 0.0);
  3460. };
  3461. /**
  3462. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3463. * @returns a new down Vector3
  3464. */
  3465. Vector3.Down = function () {
  3466. return new Vector3(0.0, -1.0, 0.0);
  3467. };
  3468. /**
  3469. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3470. * @returns a new forward Vector3
  3471. */
  3472. Vector3.Forward = function () {
  3473. return new Vector3(0.0, 0.0, 1.0);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3477. * @returns a new forward Vector3
  3478. */
  3479. Vector3.Backward = function () {
  3480. return new Vector3(0.0, 0.0, -1.0);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3484. * @returns a new right Vector3
  3485. */
  3486. Vector3.Right = function () {
  3487. return new Vector3(1.0, 0.0, 0.0);
  3488. };
  3489. /**
  3490. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3491. * @returns a new left Vector3
  3492. */
  3493. Vector3.Left = function () {
  3494. return new Vector3(-1.0, 0.0, 0.0);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3498. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3499. * @param vector defines the Vector3 to transform
  3500. * @param transformation defines the transformation matrix
  3501. * @returns the transformed Vector3
  3502. */
  3503. Vector3.TransformCoordinates = function (vector, transformation) {
  3504. var result = Vector3.Zero();
  3505. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3506. return result;
  3507. };
  3508. /**
  3509. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3510. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3511. * @param vector defines the Vector3 to transform
  3512. * @param transformation defines the transformation matrix
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3518. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3519. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3520. result.x = x / w;
  3521. result.y = y / w;
  3522. result.z = z / w;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3526. * This method computes tranformed coordinates only, not transformed direction vectors
  3527. * @param x define the x coordinate of the source vector
  3528. * @param y define the y coordinate of the source vector
  3529. * @param z define the z coordinate of the source vector
  3530. * @param transformation defines the transformation matrix
  3531. * @param result defines the Vector3 where to store the result
  3532. */
  3533. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3534. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3535. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3536. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3537. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3538. result.x = rx / rw;
  3539. result.y = ry / rw;
  3540. result.z = rz / rw;
  3541. };
  3542. /**
  3543. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3544. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3545. * @param vector defines the Vector3 to transform
  3546. * @param transformation defines the transformation matrix
  3547. * @returns the new Vector3
  3548. */
  3549. Vector3.TransformNormal = function (vector, transformation) {
  3550. var result = Vector3.Zero();
  3551. Vector3.TransformNormalToRef(vector, transformation, result);
  3552. return result;
  3553. };
  3554. /**
  3555. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3556. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3557. * @param vector defines the Vector3 to transform
  3558. * @param transformation defines the transformation matrix
  3559. * @param result defines the Vector3 where to store the result
  3560. */
  3561. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3562. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3563. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3564. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3565. result.x = x;
  3566. result.y = y;
  3567. result.z = z;
  3568. };
  3569. /**
  3570. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3571. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3572. * @param x define the x coordinate of the source vector
  3573. * @param y define the y coordinate of the source vector
  3574. * @param z define the z coordinate of the source vector
  3575. * @param transformation defines the transformation matrix
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3579. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3580. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3581. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3582. };
  3583. /**
  3584. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3585. * @param value1 defines the first control point
  3586. * @param value2 defines the second control point
  3587. * @param value3 defines the third control point
  3588. * @param value4 defines the fourth control point
  3589. * @param amount defines the amount on the spline to use
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3593. var squared = amount * amount;
  3594. var cubed = amount * squared;
  3595. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3596. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3597. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3598. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3599. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3600. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3601. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3602. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3603. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3604. return new Vector3(x, y, z);
  3605. };
  3606. /**
  3607. * 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"
  3608. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3609. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3610. * @param value defines the current value
  3611. * @param min defines the lower range value
  3612. * @param max defines the upper range value
  3613. * @returns the new Vector3
  3614. */
  3615. Vector3.Clamp = function (value, min, max) {
  3616. var x = value.x;
  3617. x = (x > max.x) ? max.x : x;
  3618. x = (x < min.x) ? min.x : x;
  3619. var y = value.y;
  3620. y = (y > max.y) ? max.y : y;
  3621. y = (y < min.y) ? min.y : y;
  3622. var z = value.z;
  3623. z = (z > max.z) ? max.z : z;
  3624. z = (z < min.z) ? min.z : z;
  3625. return new Vector3(x, y, z);
  3626. };
  3627. /**
  3628. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3629. * @param value1 defines the first control point
  3630. * @param tangent1 defines the first tangent vector
  3631. * @param value2 defines the second control point
  3632. * @param tangent2 defines the second tangent vector
  3633. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3634. * @returns the new Vector3
  3635. */
  3636. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3637. var squared = amount * amount;
  3638. var cubed = amount * squared;
  3639. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3640. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3641. var part3 = (cubed - (2.0 * squared)) + amount;
  3642. var part4 = cubed - squared;
  3643. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3644. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3645. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3646. return new Vector3(x, y, z);
  3647. };
  3648. /**
  3649. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3650. * @param start defines the start value
  3651. * @param end defines the end value
  3652. * @param amount max defines amount between both (between 0 and 1)
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Lerp = function (start, end, amount) {
  3656. var result = new Vector3(0, 0, 0);
  3657. Vector3.LerpToRef(start, end, amount, result);
  3658. return result;
  3659. };
  3660. /**
  3661. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3662. * @param start defines the start value
  3663. * @param end defines the end value
  3664. * @param amount max defines amount between both (between 0 and 1)
  3665. * @param result defines the Vector3 where to store the result
  3666. */
  3667. Vector3.LerpToRef = function (start, end, amount, result) {
  3668. result.x = start.x + ((end.x - start.x) * amount);
  3669. result.y = start.y + ((end.y - start.y) * amount);
  3670. result.z = start.z + ((end.z - start.z) * amount);
  3671. };
  3672. /**
  3673. * Returns the dot product (float) between the vectors "left" and "right"
  3674. * @param left defines the left operand
  3675. * @param right defines the right operand
  3676. * @returns the dot product
  3677. */
  3678. Vector3.Dot = function (left, right) {
  3679. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3680. };
  3681. /**
  3682. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3683. * The cross product is then orthogonal to both "left" and "right"
  3684. * @param left defines the left operand
  3685. * @param right defines the right operand
  3686. * @returns the cross product
  3687. */
  3688. Vector3.Cross = function (left, right) {
  3689. var result = Vector3.Zero();
  3690. Vector3.CrossToRef(left, right, result);
  3691. return result;
  3692. };
  3693. /**
  3694. * Sets the given vector "result" with the cross product of "left" and "right"
  3695. * The cross product is then orthogonal to both "left" and "right"
  3696. * @param left defines the left operand
  3697. * @param right defines the right operand
  3698. * @param result defines the Vector3 where to store the result
  3699. */
  3700. Vector3.CrossToRef = function (left, right, result) {
  3701. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3702. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3703. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3704. result.copyFrom(MathTmp.Vector3[0]);
  3705. };
  3706. /**
  3707. * Returns a new Vector3 as the normalization of the given vector
  3708. * @param vector defines the Vector3 to normalize
  3709. * @returns the new Vector3
  3710. */
  3711. Vector3.Normalize = function (vector) {
  3712. var result = Vector3.Zero();
  3713. Vector3.NormalizeToRef(vector, result);
  3714. return result;
  3715. };
  3716. /**
  3717. * Sets the given vector "result" with the normalization of the given first vector
  3718. * @param vector defines the Vector3 to normalize
  3719. * @param result defines the Vector3 where to store the result
  3720. */
  3721. Vector3.NormalizeToRef = function (vector, result) {
  3722. result.copyFrom(vector);
  3723. result.normalize();
  3724. };
  3725. /**
  3726. * Project a Vector3 onto screen space
  3727. * @param vector defines the Vector3 to project
  3728. * @param world defines the world matrix to use
  3729. * @param transform defines the transform (view x projection) matrix to use
  3730. * @param viewport defines the screen viewport to use
  3731. * @returns the new Vector3
  3732. */
  3733. Vector3.Project = function (vector, world, transform, viewport) {
  3734. var cw = viewport.width;
  3735. var ch = viewport.height;
  3736. var cx = viewport.x;
  3737. var cy = viewport.y;
  3738. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3739. 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);
  3740. var matrix = MathTmp.Matrix[0];
  3741. world.multiplyToRef(transform, matrix);
  3742. matrix.multiplyToRef(viewportMatrix, matrix);
  3743. return Vector3.TransformCoordinates(vector, matrix);
  3744. };
  3745. /**
  3746. * Unproject from screen space to object space
  3747. * @param source defines the screen space Vector3 to use
  3748. * @param viewportWidth defines the current width of the viewport
  3749. * @param viewportHeight defines the current height of the viewport
  3750. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3751. * @param transform defines the transform (view x projection) matrix to use
  3752. * @returns the new Vector3
  3753. */
  3754. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3755. var matrix = MathTmp.Matrix[0];
  3756. world.multiplyToRef(transform, matrix);
  3757. matrix.invert();
  3758. source.x = source.x / viewportWidth * 2 - 1;
  3759. source.y = -(source.y / viewportHeight * 2 - 1);
  3760. var vector = Vector3.TransformCoordinates(source, matrix);
  3761. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3762. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3763. vector = vector.scale(1.0 / num);
  3764. }
  3765. return vector;
  3766. };
  3767. /**
  3768. * Unproject from screen space to object space
  3769. * @param source defines the screen space Vector3 to use
  3770. * @param viewportWidth defines the current width of the viewport
  3771. * @param viewportHeight defines the current height of the viewport
  3772. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3773. * @param view defines the view matrix to use
  3774. * @param projection defines the projection matrix to use
  3775. * @returns the new Vector3
  3776. */
  3777. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3778. var result = Vector3.Zero();
  3779. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3780. return result;
  3781. };
  3782. /**
  3783. * Unproject from screen space to object space
  3784. * @param source defines the screen space Vector3 to use
  3785. * @param viewportWidth defines the current width of the viewport
  3786. * @param viewportHeight defines the current height of the viewport
  3787. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3788. * @param view defines the view matrix to use
  3789. * @param projection defines the projection matrix to use
  3790. * @param result defines the Vector3 where to store the result
  3791. */
  3792. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3793. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3794. };
  3795. /**
  3796. * Unproject from screen space to object space
  3797. * @param sourceX defines the screen space x coordinate to use
  3798. * @param sourceY defines the screen space y coordinate to use
  3799. * @param sourceZ defines the screen space z coordinate to use
  3800. * @param viewportWidth defines the current width of the viewport
  3801. * @param viewportHeight defines the current height of the viewport
  3802. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3803. * @param view defines the view matrix to use
  3804. * @param projection defines the projection matrix to use
  3805. * @param result defines the Vector3 where to store the result
  3806. */
  3807. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3808. var matrix = MathTmp.Matrix[0];
  3809. world.multiplyToRef(view, matrix);
  3810. matrix.multiplyToRef(projection, matrix);
  3811. matrix.invert();
  3812. var screenSource = MathTmp.Vector3[0];
  3813. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3814. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3815. screenSource.z = 2 * sourceZ - 1.0;
  3816. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3817. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3818. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3819. result.scaleInPlace(1.0 / num);
  3820. }
  3821. };
  3822. /**
  3823. * Gets the minimal coordinate values between two Vector3
  3824. * @param left defines the first operand
  3825. * @param right defines the second operand
  3826. * @returns the new Vector3
  3827. */
  3828. Vector3.Minimize = function (left, right) {
  3829. var min = left.clone();
  3830. min.minimizeInPlace(right);
  3831. return min;
  3832. };
  3833. /**
  3834. * Gets the maximal coordinate values between two Vector3
  3835. * @param left defines the first operand
  3836. * @param right defines the second operand
  3837. * @returns the new Vector3
  3838. */
  3839. Vector3.Maximize = function (left, right) {
  3840. var max = left.clone();
  3841. max.maximizeInPlace(right);
  3842. return max;
  3843. };
  3844. /**
  3845. * Returns the distance between the vectors "value1" and "value2"
  3846. * @param value1 defines the first operand
  3847. * @param value2 defines the second operand
  3848. * @returns the distance
  3849. */
  3850. Vector3.Distance = function (value1, value2) {
  3851. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3852. };
  3853. /**
  3854. * Returns the squared distance between the vectors "value1" and "value2"
  3855. * @param value1 defines the first operand
  3856. * @param value2 defines the second operand
  3857. * @returns the squared distance
  3858. */
  3859. Vector3.DistanceSquared = function (value1, value2) {
  3860. var x = value1.x - value2.x;
  3861. var y = value1.y - value2.y;
  3862. var z = value1.z - value2.z;
  3863. return (x * x) + (y * y) + (z * z);
  3864. };
  3865. /**
  3866. * Returns a new Vector3 located at the center between "value1" and "value2"
  3867. * @param value1 defines the first operand
  3868. * @param value2 defines the second operand
  3869. * @returns the new Vector3
  3870. */
  3871. Vector3.Center = function (value1, value2) {
  3872. var center = value1.add(value2);
  3873. center.scaleInPlace(0.5);
  3874. return center;
  3875. };
  3876. /**
  3877. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3878. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3879. * to something in order to rotate it from its local system to the given target system
  3880. * Note: axis1, axis2 and axis3 are normalized during this operation
  3881. * @param axis1 defines the first axis
  3882. * @param axis2 defines the second axis
  3883. * @param axis3 defines the third axis
  3884. * @returns a new Vector3
  3885. */
  3886. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3887. var rotation = Vector3.Zero();
  3888. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3889. return rotation;
  3890. };
  3891. /**
  3892. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3893. * @param axis1 defines the first axis
  3894. * @param axis2 defines the second axis
  3895. * @param axis3 defines the third axis
  3896. * @param ref defines the Vector3 where to store the result
  3897. */
  3898. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3899. var quat = MathTmp.Quaternion[0];
  3900. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3901. quat.toEulerAnglesToRef(ref);
  3902. };
  3903. return Vector3;
  3904. }());
  3905. BABYLON.Vector3 = Vector3;
  3906. //Vector4 class created for EulerAngle class conversion to Quaternion
  3907. var Vector4 = /** @class */ (function () {
  3908. /**
  3909. * Creates a Vector4 object from the given floats.
  3910. */
  3911. function Vector4(x, y, z, w) {
  3912. this.x = x;
  3913. this.y = y;
  3914. this.z = z;
  3915. this.w = w;
  3916. }
  3917. /**
  3918. * Returns the string with the Vector4 coordinates.
  3919. */
  3920. Vector4.prototype.toString = function () {
  3921. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3922. };
  3923. /**
  3924. * Returns the string "Vector4".
  3925. */
  3926. Vector4.prototype.getClassName = function () {
  3927. return "Vector4";
  3928. };
  3929. /**
  3930. * Returns the Vector4 hash code.
  3931. */
  3932. Vector4.prototype.getHashCode = function () {
  3933. var hash = this.x || 0;
  3934. hash = (hash * 397) ^ (this.y || 0);
  3935. hash = (hash * 397) ^ (this.z || 0);
  3936. hash = (hash * 397) ^ (this.w || 0);
  3937. return hash;
  3938. };
  3939. // Operators
  3940. /**
  3941. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3942. */
  3943. Vector4.prototype.asArray = function () {
  3944. var result = new Array();
  3945. this.toArray(result, 0);
  3946. return result;
  3947. };
  3948. /**
  3949. * Populates the given array from the given index with the Vector4 coordinates.
  3950. * Returns the Vector4.
  3951. */
  3952. Vector4.prototype.toArray = function (array, index) {
  3953. if (index === undefined) {
  3954. index = 0;
  3955. }
  3956. array[index] = this.x;
  3957. array[index + 1] = this.y;
  3958. array[index + 2] = this.z;
  3959. array[index + 3] = this.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Adds the given vector to the current Vector4.
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.addInPlace = function (otherVector) {
  3967. this.x += otherVector.x;
  3968. this.y += otherVector.y;
  3969. this.z += otherVector.z;
  3970. this.w += otherVector.w;
  3971. return this;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3975. */
  3976. Vector4.prototype.add = function (otherVector) {
  3977. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3978. };
  3979. /**
  3980. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3981. * Returns the current Vector4.
  3982. */
  3983. Vector4.prototype.addToRef = function (otherVector, result) {
  3984. result.x = this.x + otherVector.x;
  3985. result.y = this.y + otherVector.y;
  3986. result.z = this.z + otherVector.z;
  3987. result.w = this.w + otherVector.w;
  3988. return this;
  3989. };
  3990. /**
  3991. * Subtract in place the given vector from the current Vector4.
  3992. * Returns the updated Vector4.
  3993. */
  3994. Vector4.prototype.subtractInPlace = function (otherVector) {
  3995. this.x -= otherVector.x;
  3996. this.y -= otherVector.y;
  3997. this.z -= otherVector.z;
  3998. this.w -= otherVector.w;
  3999. return this;
  4000. };
  4001. /**
  4002. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4003. */
  4004. Vector4.prototype.subtract = function (otherVector) {
  4005. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4006. };
  4007. /**
  4008. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4009. * Returns the current Vector4.
  4010. */
  4011. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4012. result.x = this.x - otherVector.x;
  4013. result.y = this.y - otherVector.y;
  4014. result.z = this.z - otherVector.z;
  4015. result.w = this.w - otherVector.w;
  4016. return this;
  4017. };
  4018. /**
  4019. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4020. */
  4021. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4022. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4023. };
  4024. /**
  4025. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4026. * Returns the current Vector4.
  4027. */
  4028. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4029. result.x = this.x - x;
  4030. result.y = this.y - y;
  4031. result.z = this.z - z;
  4032. result.w = this.w - w;
  4033. return this;
  4034. };
  4035. /**
  4036. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4037. */
  4038. Vector4.prototype.negate = function () {
  4039. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4040. };
  4041. /**
  4042. * Multiplies the current Vector4 coordinates by scale (float).
  4043. * Returns the updated Vector4.
  4044. */
  4045. Vector4.prototype.scaleInPlace = function (scale) {
  4046. this.x *= scale;
  4047. this.y *= scale;
  4048. this.z *= scale;
  4049. this.w *= scale;
  4050. return this;
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4054. */
  4055. Vector4.prototype.scale = function (scale) {
  4056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4057. };
  4058. /**
  4059. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4060. * Returns the current Vector4.
  4061. */
  4062. Vector4.prototype.scaleToRef = function (scale, result) {
  4063. result.x = this.x * scale;
  4064. result.y = this.y * scale;
  4065. result.z = this.z * scale;
  4066. result.w = this.w * scale;
  4067. return this;
  4068. };
  4069. /**
  4070. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4071. * @param scale defines the scale factor
  4072. * @param result defines the Vector4 object where to store the result
  4073. * @returns the unmodified current Vector4
  4074. */
  4075. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4076. result.x += this.x * scale;
  4077. result.y += this.y * scale;
  4078. result.z += this.z * scale;
  4079. result.w += this.w * scale;
  4080. return this;
  4081. };
  4082. /**
  4083. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4084. */
  4085. Vector4.prototype.equals = function (otherVector) {
  4086. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4087. };
  4088. /**
  4089. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4090. */
  4091. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4092. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4093. return otherVector
  4094. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4095. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4096. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4097. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4098. };
  4099. /**
  4100. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4101. */
  4102. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4103. return this.x === x && this.y === y && this.z === z && this.w === w;
  4104. };
  4105. /**
  4106. * Multiplies in place the current Vector4 by the given one.
  4107. * Returns the updated Vector4.
  4108. */
  4109. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4110. this.x *= otherVector.x;
  4111. this.y *= otherVector.y;
  4112. this.z *= otherVector.z;
  4113. this.w *= otherVector.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4118. */
  4119. Vector4.prototype.multiply = function (otherVector) {
  4120. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4121. };
  4122. /**
  4123. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4124. * Returns the current Vector4.
  4125. */
  4126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4127. result.x = this.x * otherVector.x;
  4128. result.y = this.y * otherVector.y;
  4129. result.z = this.z * otherVector.z;
  4130. result.w = this.w * otherVector.w;
  4131. return this;
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4135. */
  4136. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4137. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4138. };
  4139. /**
  4140. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4141. */
  4142. Vector4.prototype.divide = function (otherVector) {
  4143. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4144. };
  4145. /**
  4146. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4147. * Returns the current Vector4.
  4148. */
  4149. Vector4.prototype.divideToRef = function (otherVector, result) {
  4150. result.x = this.x / otherVector.x;
  4151. result.y = this.y / otherVector.y;
  4152. result.z = this.z / otherVector.z;
  4153. result.w = this.w / otherVector.w;
  4154. return this;
  4155. };
  4156. /**
  4157. * Divides the current Vector3 coordinates by the given ones.
  4158. * @returns the updated Vector3.
  4159. */
  4160. Vector4.prototype.divideInPlace = function (otherVector) {
  4161. return this.divideToRef(otherVector, this);
  4162. };
  4163. /**
  4164. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4165. * @param other defines the second operand
  4166. * @returns the current updated Vector4
  4167. */
  4168. Vector4.prototype.minimizeInPlace = function (other) {
  4169. if (other.x < this.x)
  4170. this.x = other.x;
  4171. if (other.y < this.y)
  4172. this.y = other.y;
  4173. if (other.z < this.z)
  4174. this.z = other.z;
  4175. if (other.w < this.w)
  4176. this.w = other.w;
  4177. return this;
  4178. };
  4179. /**
  4180. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4181. * @param other defines the second operand
  4182. * @returns the current updated Vector4
  4183. */
  4184. Vector4.prototype.maximizeInPlace = function (other) {
  4185. if (other.x > this.x)
  4186. this.x = other.x;
  4187. if (other.y > this.y)
  4188. this.y = other.y;
  4189. if (other.z > this.z)
  4190. this.z = other.z;
  4191. if (other.w > this.w)
  4192. this.w = other.w;
  4193. return this;
  4194. };
  4195. /**
  4196. * Gets a new Vector4 from current Vector4 floored values
  4197. * @returns a new Vector4
  4198. */
  4199. Vector4.prototype.floor = function () {
  4200. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4201. };
  4202. /**
  4203. * Gets a new Vector4 from current Vector3 floored values
  4204. * @returns a new Vector4
  4205. */
  4206. Vector4.prototype.fract = function () {
  4207. 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));
  4208. };
  4209. // Properties
  4210. /**
  4211. * Returns the Vector4 length (float).
  4212. */
  4213. Vector4.prototype.length = function () {
  4214. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4215. };
  4216. /**
  4217. * Returns the Vector4 squared length (float).
  4218. */
  4219. Vector4.prototype.lengthSquared = function () {
  4220. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4221. };
  4222. // Methods
  4223. /**
  4224. * Normalizes in place the Vector4.
  4225. * Returns the updated Vector4.
  4226. */
  4227. Vector4.prototype.normalize = function () {
  4228. var len = this.length();
  4229. if (len === 0)
  4230. return this;
  4231. var num = 1.0 / len;
  4232. this.x *= num;
  4233. this.y *= num;
  4234. this.z *= num;
  4235. this.w *= num;
  4236. return this;
  4237. };
  4238. /**
  4239. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4240. */
  4241. Vector4.prototype.toVector3 = function () {
  4242. return new Vector3(this.x, this.y, this.z);
  4243. };
  4244. /**
  4245. * Returns a new Vector4 copied from the current one.
  4246. */
  4247. Vector4.prototype.clone = function () {
  4248. return new Vector4(this.x, this.y, this.z, this.w);
  4249. };
  4250. /**
  4251. * Updates the current Vector4 with the given one coordinates.
  4252. * Returns the updated Vector4.
  4253. */
  4254. Vector4.prototype.copyFrom = function (source) {
  4255. this.x = source.x;
  4256. this.y = source.y;
  4257. this.z = source.z;
  4258. this.w = source.w;
  4259. return this;
  4260. };
  4261. /**
  4262. * Updates the current Vector4 coordinates with the given floats.
  4263. * Returns the updated Vector4.
  4264. */
  4265. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4266. this.x = x;
  4267. this.y = y;
  4268. this.z = z;
  4269. this.w = w;
  4270. return this;
  4271. };
  4272. /**
  4273. * Updates the current Vector4 coordinates with the given floats.
  4274. * Returns the updated Vector4.
  4275. */
  4276. Vector4.prototype.set = function (x, y, z, w) {
  4277. return this.copyFromFloats(x, y, z, w);
  4278. };
  4279. // Statics
  4280. /**
  4281. * Returns a new Vector4 set from the starting index of the given array.
  4282. */
  4283. Vector4.FromArray = function (array, offset) {
  4284. if (!offset) {
  4285. offset = 0;
  4286. }
  4287. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4288. };
  4289. /**
  4290. * Updates the given vector "result" from the starting index of the given array.
  4291. */
  4292. Vector4.FromArrayToRef = function (array, offset, result) {
  4293. result.x = array[offset];
  4294. result.y = array[offset + 1];
  4295. result.z = array[offset + 2];
  4296. result.w = array[offset + 3];
  4297. };
  4298. /**
  4299. * Updates the given vector "result" from the starting index of the given Float32Array.
  4300. */
  4301. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4302. Vector4.FromArrayToRef(array, offset, result);
  4303. };
  4304. /**
  4305. * Updates the given vector "result" coordinates from the given floats.
  4306. */
  4307. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4308. result.x = x;
  4309. result.y = y;
  4310. result.z = z;
  4311. result.w = w;
  4312. };
  4313. /**
  4314. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4315. */
  4316. Vector4.Zero = function () {
  4317. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4318. };
  4319. /**
  4320. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4321. */
  4322. Vector4.One = function () {
  4323. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4324. };
  4325. /**
  4326. * Returns a new normalized Vector4 from the given one.
  4327. */
  4328. Vector4.Normalize = function (vector) {
  4329. var result = Vector4.Zero();
  4330. Vector4.NormalizeToRef(vector, result);
  4331. return result;
  4332. };
  4333. /**
  4334. * Updates the given vector "result" from the normalization of the given one.
  4335. */
  4336. Vector4.NormalizeToRef = function (vector, result) {
  4337. result.copyFrom(vector);
  4338. result.normalize();
  4339. };
  4340. Vector4.Minimize = function (left, right) {
  4341. var min = left.clone();
  4342. min.minimizeInPlace(right);
  4343. return min;
  4344. };
  4345. Vector4.Maximize = function (left, right) {
  4346. var max = left.clone();
  4347. max.maximizeInPlace(right);
  4348. return max;
  4349. };
  4350. /**
  4351. * Returns the distance (float) between the vectors "value1" and "value2".
  4352. */
  4353. Vector4.Distance = function (value1, value2) {
  4354. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4355. };
  4356. /**
  4357. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4358. */
  4359. Vector4.DistanceSquared = function (value1, value2) {
  4360. var x = value1.x - value2.x;
  4361. var y = value1.y - value2.y;
  4362. var z = value1.z - value2.z;
  4363. var w = value1.w - value2.w;
  4364. return (x * x) + (y * y) + (z * z) + (w * w);
  4365. };
  4366. /**
  4367. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4368. */
  4369. Vector4.Center = function (value1, value2) {
  4370. var center = value1.add(value2);
  4371. center.scaleInPlace(0.5);
  4372. return center;
  4373. };
  4374. /**
  4375. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4376. * This methods computes transformed normalized direction vectors only.
  4377. */
  4378. Vector4.TransformNormal = function (vector, transformation) {
  4379. var result = Vector4.Zero();
  4380. Vector4.TransformNormalToRef(vector, transformation, result);
  4381. return result;
  4382. };
  4383. /**
  4384. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4385. * This methods computes transformed normalized direction vectors only.
  4386. */
  4387. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4388. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4389. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4390. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4391. result.x = x;
  4392. result.y = y;
  4393. result.z = z;
  4394. result.w = vector.w;
  4395. };
  4396. /**
  4397. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4398. * This methods computes transformed normalized direction vectors only.
  4399. */
  4400. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4401. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4402. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4403. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4404. result.w = w;
  4405. };
  4406. return Vector4;
  4407. }());
  4408. BABYLON.Vector4 = Vector4;
  4409. var Size = /** @class */ (function () {
  4410. /**
  4411. * Creates a Size object from the given width and height (floats).
  4412. */
  4413. function Size(width, height) {
  4414. this.width = width;
  4415. this.height = height;
  4416. }
  4417. // Returns a string with the Size width and height.
  4418. Size.prototype.toString = function () {
  4419. return "{W: " + this.width + ", H: " + this.height + "}";
  4420. };
  4421. /**
  4422. * Returns the string "Size"
  4423. */
  4424. Size.prototype.getClassName = function () {
  4425. return "Size";
  4426. };
  4427. /**
  4428. * Returns the Size hash code.
  4429. */
  4430. Size.prototype.getHashCode = function () {
  4431. var hash = this.width || 0;
  4432. hash = (hash * 397) ^ (this.height || 0);
  4433. return hash;
  4434. };
  4435. /**
  4436. * Updates the current size from the given one.
  4437. * Returns the updated Size.
  4438. */
  4439. Size.prototype.copyFrom = function (src) {
  4440. this.width = src.width;
  4441. this.height = src.height;
  4442. };
  4443. /**
  4444. * Updates in place the current Size from the given floats.
  4445. * Returns the updated Size.
  4446. */
  4447. Size.prototype.copyFromFloats = function (width, height) {
  4448. this.width = width;
  4449. this.height = height;
  4450. return this;
  4451. };
  4452. /**
  4453. * Updates in place the current Size from the given floats.
  4454. * Returns the updated Size.
  4455. */
  4456. Size.prototype.set = function (width, height) {
  4457. return this.copyFromFloats(width, height);
  4458. };
  4459. /**
  4460. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4461. */
  4462. Size.prototype.multiplyByFloats = function (w, h) {
  4463. return new Size(this.width * w, this.height * h);
  4464. };
  4465. /**
  4466. * Returns a new Size copied from the given one.
  4467. */
  4468. Size.prototype.clone = function () {
  4469. return new Size(this.width, this.height);
  4470. };
  4471. /**
  4472. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4473. */
  4474. Size.prototype.equals = function (other) {
  4475. if (!other) {
  4476. return false;
  4477. }
  4478. return (this.width === other.width) && (this.height === other.height);
  4479. };
  4480. Object.defineProperty(Size.prototype, "surface", {
  4481. /**
  4482. * Returns the surface of the Size : width * height (float).
  4483. */
  4484. get: function () {
  4485. return this.width * this.height;
  4486. },
  4487. enumerable: true,
  4488. configurable: true
  4489. });
  4490. /**
  4491. * Returns a new Size set to (0.0, 0.0)
  4492. */
  4493. Size.Zero = function () {
  4494. return new Size(0.0, 0.0);
  4495. };
  4496. /**
  4497. * Returns a new Size set as the addition result of the current Size and the given one.
  4498. */
  4499. Size.prototype.add = function (otherSize) {
  4500. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4501. return r;
  4502. };
  4503. /**
  4504. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4505. */
  4506. Size.prototype.subtract = function (otherSize) {
  4507. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4508. return r;
  4509. };
  4510. /**
  4511. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4512. */
  4513. Size.Lerp = function (start, end, amount) {
  4514. var w = start.width + ((end.width - start.width) * amount);
  4515. var h = start.height + ((end.height - start.height) * amount);
  4516. return new Size(w, h);
  4517. };
  4518. return Size;
  4519. }());
  4520. BABYLON.Size = Size;
  4521. /**
  4522. * Class used to store quaternion data
  4523. * @see https://en.wikipedia.org/wiki/Quaternion
  4524. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4525. */
  4526. var Quaternion = /** @class */ (function () {
  4527. /**
  4528. * Creates a new Quaternion from the given floats
  4529. * @param x defines the first component (0 by default)
  4530. * @param y defines the second component (0 by default)
  4531. * @param z defines the third component (0 by default)
  4532. * @param w defines the fourth component (1.0 by default)
  4533. */
  4534. function Quaternion(
  4535. /** defines the first component (0 by default) */
  4536. x,
  4537. /** defines the second component (0 by default) */
  4538. y,
  4539. /** defines the third component (0 by default) */
  4540. z,
  4541. /** defines the fourth component (1.0 by default) */
  4542. w) {
  4543. if (x === void 0) { x = 0.0; }
  4544. if (y === void 0) { y = 0.0; }
  4545. if (z === void 0) { z = 0.0; }
  4546. if (w === void 0) { w = 1.0; }
  4547. this.x = x;
  4548. this.y = y;
  4549. this.z = z;
  4550. this.w = w;
  4551. }
  4552. /**
  4553. * Gets a string representation for the current quaternion
  4554. * @returns a string with the Quaternion coordinates
  4555. */
  4556. Quaternion.prototype.toString = function () {
  4557. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4558. };
  4559. /**
  4560. * Gets the class name of the quaternion
  4561. * @returns the string "Quaternion"
  4562. */
  4563. Quaternion.prototype.getClassName = function () {
  4564. return "Quaternion";
  4565. };
  4566. /**
  4567. * Gets a hash code for this quaternion
  4568. * @returns the quaternion hash code
  4569. */
  4570. Quaternion.prototype.getHashCode = function () {
  4571. var hash = this.x || 0;
  4572. hash = (hash * 397) ^ (this.y || 0);
  4573. hash = (hash * 397) ^ (this.z || 0);
  4574. hash = (hash * 397) ^ (this.w || 0);
  4575. return hash;
  4576. };
  4577. /**
  4578. * Copy the quaternion to an array
  4579. * @returns a new array populated with 4 elements from the quaternion coordinates
  4580. */
  4581. Quaternion.prototype.asArray = function () {
  4582. return [this.x, this.y, this.z, this.w];
  4583. };
  4584. /**
  4585. * Check if two quaternions are equals
  4586. * @param otherQuaternion defines the second operand
  4587. * @return true if the current quaternion and the given one coordinates are strictly equals
  4588. */
  4589. Quaternion.prototype.equals = function (otherQuaternion) {
  4590. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4591. };
  4592. /**
  4593. * Clone the current quaternion
  4594. * @returns a new quaternion copied from the current one
  4595. */
  4596. Quaternion.prototype.clone = function () {
  4597. return new Quaternion(this.x, this.y, this.z, this.w);
  4598. };
  4599. /**
  4600. * Copy a quaternion to the current one
  4601. * @param other defines the other quaternion
  4602. * @returns the updated current quaternion
  4603. */
  4604. Quaternion.prototype.copyFrom = function (other) {
  4605. this.x = other.x;
  4606. this.y = other.y;
  4607. this.z = other.z;
  4608. this.w = other.w;
  4609. return this;
  4610. };
  4611. /**
  4612. * Updates the current quaternion with the given float coordinates
  4613. * @param x defines the x coordinate
  4614. * @param y defines the y coordinate
  4615. * @param z defines the z coordinate
  4616. * @param w defines the w coordinate
  4617. * @returns the updated current quaternion
  4618. */
  4619. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4620. this.x = x;
  4621. this.y = y;
  4622. this.z = z;
  4623. this.w = w;
  4624. return this;
  4625. };
  4626. /**
  4627. * Updates the current quaternion from the given float coordinates
  4628. * @param x defines the x coordinate
  4629. * @param y defines the y coordinate
  4630. * @param z defines the z coordinate
  4631. * @param w defines the w coordinate
  4632. * @returns the updated current quaternion
  4633. */
  4634. Quaternion.prototype.set = function (x, y, z, w) {
  4635. return this.copyFromFloats(x, y, z, w);
  4636. };
  4637. /**
  4638. * Adds two quaternions
  4639. * @param other defines the second operand
  4640. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4641. */
  4642. Quaternion.prototype.add = function (other) {
  4643. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4644. };
  4645. /**
  4646. * Add a quaternion to the current one
  4647. * @param other defines the quaternion to add
  4648. * @returns the current quaternion
  4649. */
  4650. Quaternion.prototype.addInPlace = function (other) {
  4651. this.x += other.x;
  4652. this.y += other.y;
  4653. this.z += other.z;
  4654. this.w += other.w;
  4655. return this;
  4656. };
  4657. /**
  4658. * Subtract two quaternions
  4659. * @param other defines the second operand
  4660. * @returns a new quaternion as the subtraction result of the given one from the current one
  4661. */
  4662. Quaternion.prototype.subtract = function (other) {
  4663. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4664. };
  4665. /**
  4666. * Multiplies the current quaternion by a scale factor
  4667. * @param value defines the scale factor
  4668. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4669. */
  4670. Quaternion.prototype.scale = function (value) {
  4671. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4672. };
  4673. /**
  4674. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4675. * @param scale defines the scale factor
  4676. * @param result defines the Quaternion object where to store the result
  4677. * @returns the unmodified current quaternion
  4678. */
  4679. Quaternion.prototype.scaleToRef = function (scale, result) {
  4680. result.x = this.x * scale;
  4681. result.y = this.y * scale;
  4682. result.z = this.z * scale;
  4683. result.w = this.w * scale;
  4684. return this;
  4685. };
  4686. /**
  4687. * Multiplies in place the current quaternion by a scale factor
  4688. * @param value defines the scale factor
  4689. * @returns the current modified quaternion
  4690. */
  4691. Quaternion.prototype.scaleInPlace = function (value) {
  4692. this.x *= value;
  4693. this.y *= value;
  4694. this.z *= value;
  4695. this.w *= value;
  4696. return this;
  4697. };
  4698. /**
  4699. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4700. * @param scale defines the scale factor
  4701. * @param result defines the Quaternion object where to store the result
  4702. * @returns the unmodified current quaternion
  4703. */
  4704. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4705. result.x += this.x * scale;
  4706. result.y += this.y * scale;
  4707. result.z += this.z * scale;
  4708. result.w += this.w * scale;
  4709. return this;
  4710. };
  4711. /**
  4712. * Multiplies two quaternions
  4713. * @param q1 defines the second operand
  4714. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4715. */
  4716. Quaternion.prototype.multiply = function (q1) {
  4717. var result = new Quaternion(0, 0, 0, 1.0);
  4718. this.multiplyToRef(q1, result);
  4719. return result;
  4720. };
  4721. /**
  4722. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4723. * @param q1 defines the second operand
  4724. * @param result defines the target quaternion
  4725. * @returns the current quaternion
  4726. */
  4727. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4728. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4729. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4730. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4731. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4732. result.copyFromFloats(x, y, z, w);
  4733. return this;
  4734. };
  4735. /**
  4736. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4737. * @param q1 defines the second operand
  4738. * @returns the currentupdated quaternion
  4739. */
  4740. Quaternion.prototype.multiplyInPlace = function (q1) {
  4741. this.multiplyToRef(q1, this);
  4742. return this;
  4743. };
  4744. /**
  4745. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4746. * @param ref defines the target quaternion
  4747. * @returns the current quaternion
  4748. */
  4749. Quaternion.prototype.conjugateToRef = function (ref) {
  4750. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4751. return this;
  4752. };
  4753. /**
  4754. * Conjugates in place (1-q) the current quaternion
  4755. * @returns the current updated quaternion
  4756. */
  4757. Quaternion.prototype.conjugateInPlace = function () {
  4758. this.x *= -1;
  4759. this.y *= -1;
  4760. this.z *= -1;
  4761. return this;
  4762. };
  4763. /**
  4764. * Conjugates in place (1-q) the current quaternion
  4765. * @returns a new quaternion
  4766. */
  4767. Quaternion.prototype.conjugate = function () {
  4768. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4769. return result;
  4770. };
  4771. /**
  4772. * Gets length of current quaternion
  4773. * @returns the quaternion length (float)
  4774. */
  4775. Quaternion.prototype.length = function () {
  4776. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4777. };
  4778. /**
  4779. * Normalize in place the current quaternion
  4780. * @returns the current updated quaternion
  4781. */
  4782. Quaternion.prototype.normalize = function () {
  4783. var length = 1.0 / this.length();
  4784. this.x *= length;
  4785. this.y *= length;
  4786. this.z *= length;
  4787. this.w *= length;
  4788. return this;
  4789. };
  4790. /**
  4791. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4792. * @param order is a reserved parameter and is ignore for now
  4793. * @returns a new Vector3 containing the Euler angles
  4794. */
  4795. Quaternion.prototype.toEulerAngles = function (order) {
  4796. if (order === void 0) { order = "YZX"; }
  4797. var result = Vector3.Zero();
  4798. this.toEulerAnglesToRef(result, order);
  4799. return result;
  4800. };
  4801. /**
  4802. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4803. * @param result defines the vector which will be filled with the Euler angles
  4804. * @param order is a reserved parameter and is ignore for now
  4805. * @returns the current unchanged quaternion
  4806. */
  4807. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4808. if (order === void 0) { order = "YZX"; }
  4809. var qz = this.z;
  4810. var qx = this.x;
  4811. var qy = this.y;
  4812. var qw = this.w;
  4813. var sqw = qw * qw;
  4814. var sqz = qz * qz;
  4815. var sqx = qx * qx;
  4816. var sqy = qy * qy;
  4817. var zAxisY = qy * qz - qx * qw;
  4818. var limit = .4999999;
  4819. if (zAxisY < -limit) {
  4820. result.y = 2 * Math.atan2(qy, qw);
  4821. result.x = Math.PI / 2;
  4822. result.z = 0;
  4823. }
  4824. else if (zAxisY > limit) {
  4825. result.y = 2 * Math.atan2(qy, qw);
  4826. result.x = -Math.PI / 2;
  4827. result.z = 0;
  4828. }
  4829. else {
  4830. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4831. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4832. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4833. }
  4834. return this;
  4835. };
  4836. /**
  4837. * Updates the given rotation matrix with the current quaternion values
  4838. * @param result defines the target matrix
  4839. * @returns the current unchanged quaternion
  4840. */
  4841. Quaternion.prototype.toRotationMatrix = function (result) {
  4842. var xx = this.x * this.x;
  4843. var yy = this.y * this.y;
  4844. var zz = this.z * this.z;
  4845. var xy = this.x * this.y;
  4846. var zw = this.z * this.w;
  4847. var zx = this.z * this.x;
  4848. var yw = this.y * this.w;
  4849. var yz = this.y * this.z;
  4850. var xw = this.x * this.w;
  4851. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4852. result.m[1] = 2.0 * (xy + zw);
  4853. result.m[2] = 2.0 * (zx - yw);
  4854. result.m[3] = 0;
  4855. result.m[4] = 2.0 * (xy - zw);
  4856. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4857. result.m[6] = 2.0 * (yz + xw);
  4858. result.m[7] = 0;
  4859. result.m[8] = 2.0 * (zx + yw);
  4860. result.m[9] = 2.0 * (yz - xw);
  4861. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4862. result.m[11] = 0;
  4863. result.m[12] = 0;
  4864. result.m[13] = 0;
  4865. result.m[14] = 0;
  4866. result.m[15] = 1.0;
  4867. result._markAsUpdated();
  4868. return this;
  4869. };
  4870. /**
  4871. * Updates the current quaternion from the given rotation matrix values
  4872. * @param matrix defines the source matrix
  4873. * @returns the current updated quaternion
  4874. */
  4875. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4876. Quaternion.FromRotationMatrixToRef(matrix, this);
  4877. return this;
  4878. };
  4879. // Statics
  4880. /**
  4881. * Creates a new quaternion from a rotation matrix
  4882. * @param matrix defines the source matrix
  4883. * @returns a new quaternion created from the given rotation matrix values
  4884. */
  4885. Quaternion.FromRotationMatrix = function (matrix) {
  4886. var result = new Quaternion();
  4887. Quaternion.FromRotationMatrixToRef(matrix, result);
  4888. return result;
  4889. };
  4890. /**
  4891. * Updates the given quaternion with the given rotation matrix values
  4892. * @param matrix defines the source matrix
  4893. * @param result defines the target quaternion
  4894. */
  4895. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4896. var data = matrix.m;
  4897. var m11 = data[0], m12 = data[4], m13 = data[8];
  4898. var m21 = data[1], m22 = data[5], m23 = data[9];
  4899. var m31 = data[2], m32 = data[6], m33 = data[10];
  4900. var trace = m11 + m22 + m33;
  4901. var s;
  4902. if (trace > 0) {
  4903. s = 0.5 / Math.sqrt(trace + 1.0);
  4904. result.w = 0.25 / s;
  4905. result.x = (m32 - m23) * s;
  4906. result.y = (m13 - m31) * s;
  4907. result.z = (m21 - m12) * s;
  4908. }
  4909. else if (m11 > m22 && m11 > m33) {
  4910. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4911. result.w = (m32 - m23) / s;
  4912. result.x = 0.25 * s;
  4913. result.y = (m12 + m21) / s;
  4914. result.z = (m13 + m31) / s;
  4915. }
  4916. else if (m22 > m33) {
  4917. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4918. result.w = (m13 - m31) / s;
  4919. result.x = (m12 + m21) / s;
  4920. result.y = 0.25 * s;
  4921. result.z = (m23 + m32) / s;
  4922. }
  4923. else {
  4924. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4925. result.w = (m21 - m12) / s;
  4926. result.x = (m13 + m31) / s;
  4927. result.y = (m23 + m32) / s;
  4928. result.z = 0.25 * s;
  4929. }
  4930. };
  4931. /**
  4932. * Returns the dot product (float) between the quaternions "left" and "right"
  4933. * @param left defines the left operand
  4934. * @param right defines the right operand
  4935. * @returns the dot product
  4936. */
  4937. Quaternion.Dot = function (left, right) {
  4938. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4939. };
  4940. /**
  4941. * Checks if the two quaternions are close to each other
  4942. * @param quat0 defines the first quaternion to check
  4943. * @param quat1 defines the second quaternion to check
  4944. * @returns true if the two quaternions are close to each other
  4945. */
  4946. Quaternion.AreClose = function (quat0, quat1) {
  4947. var dot = Quaternion.Dot(quat0, quat1);
  4948. return dot >= 0;
  4949. };
  4950. /**
  4951. * Creates an empty quaternion
  4952. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4953. */
  4954. Quaternion.Zero = function () {
  4955. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4956. };
  4957. /**
  4958. * Inverse a given quaternion
  4959. * @param q defines the source quaternion
  4960. * @returns a new quaternion as the inverted current quaternion
  4961. */
  4962. Quaternion.Inverse = function (q) {
  4963. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4964. };
  4965. /**
  4966. * Creates an identity quaternion
  4967. * @returns the identity quaternion
  4968. */
  4969. Quaternion.Identity = function () {
  4970. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4971. };
  4972. /**
  4973. * Gets a boolean indicating if the given quaternion is identity
  4974. * @param quaternion defines the quaternion to check
  4975. * @returns true if the quaternion is identity
  4976. */
  4977. Quaternion.IsIdentity = function (quaternion) {
  4978. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4979. };
  4980. /**
  4981. * Creates a quaternion from a rotation around an axis
  4982. * @param axis defines the axis to use
  4983. * @param angle defines the angle to use
  4984. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4985. */
  4986. Quaternion.RotationAxis = function (axis, angle) {
  4987. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4988. };
  4989. /**
  4990. * Creates a rotation around an axis and stores it into the given quaternion
  4991. * @param axis defines the axis to use
  4992. * @param angle defines the angle to use
  4993. * @param result defines the target quaternion
  4994. * @returns the target quaternion
  4995. */
  4996. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4997. var sin = Math.sin(angle / 2);
  4998. axis.normalize();
  4999. result.w = Math.cos(angle / 2);
  5000. result.x = axis.x * sin;
  5001. result.y = axis.y * sin;
  5002. result.z = axis.z * sin;
  5003. return result;
  5004. };
  5005. /**
  5006. * Creates a new quaternion from data stored into an array
  5007. * @param array defines the data source
  5008. * @param offset defines the offset in the source array where the data starts
  5009. * @returns a new quaternion
  5010. */
  5011. Quaternion.FromArray = function (array, offset) {
  5012. if (!offset) {
  5013. offset = 0;
  5014. }
  5015. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5016. };
  5017. /**
  5018. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5019. * @param yaw defines the rotation around Y axis
  5020. * @param pitch defines the rotation around X axis
  5021. * @param roll defines the rotation around Z axis
  5022. * @returns the new quaternion
  5023. */
  5024. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5025. var q = new Quaternion();
  5026. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5027. return q;
  5028. };
  5029. /**
  5030. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5031. * @param yaw defines the rotation around Y axis
  5032. * @param pitch defines the rotation around X axis
  5033. * @param roll defines the rotation around Z axis
  5034. * @param result defines the target quaternion
  5035. */
  5036. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5037. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5038. var halfRoll = roll * 0.5;
  5039. var halfPitch = pitch * 0.5;
  5040. var halfYaw = yaw * 0.5;
  5041. var sinRoll = Math.sin(halfRoll);
  5042. var cosRoll = Math.cos(halfRoll);
  5043. var sinPitch = Math.sin(halfPitch);
  5044. var cosPitch = Math.cos(halfPitch);
  5045. var sinYaw = Math.sin(halfYaw);
  5046. var cosYaw = Math.cos(halfYaw);
  5047. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5048. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5049. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5050. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5051. };
  5052. /**
  5053. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5054. * @param alpha defines the rotation around first axis
  5055. * @param beta defines the rotation around second axis
  5056. * @param gamma defines the rotation around third axis
  5057. * @returns the new quaternion
  5058. */
  5059. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5060. var result = new Quaternion();
  5061. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5062. return result;
  5063. };
  5064. /**
  5065. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5066. * @param alpha defines the rotation around first axis
  5067. * @param beta defines the rotation around second axis
  5068. * @param gamma defines the rotation around third axis
  5069. * @param result defines the target quaternion
  5070. */
  5071. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5072. // Produces a quaternion from Euler angles in the z-x-z orientation
  5073. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5074. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5075. var halfBeta = beta * 0.5;
  5076. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5077. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5078. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5079. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5080. };
  5081. /**
  5082. * 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)
  5083. * @param axis1 defines the first axis
  5084. * @param axis2 defines the second axis
  5085. * @param axis3 defines the third axis
  5086. * @returns the new quaternion
  5087. */
  5088. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5089. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5090. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5091. return quat;
  5092. };
  5093. /**
  5094. * 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
  5095. * @param axis1 defines the first axis
  5096. * @param axis2 defines the second axis
  5097. * @param axis3 defines the third axis
  5098. * @param ref defines the target quaternion
  5099. */
  5100. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5101. var rotMat = MathTmp.Matrix[0];
  5102. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5103. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5104. };
  5105. /**
  5106. * Interpolates between two quaternions
  5107. * @param left defines first quaternion
  5108. * @param right defines second quaternion
  5109. * @param amount defines the gradient to use
  5110. * @returns the new interpolated quaternion
  5111. */
  5112. Quaternion.Slerp = function (left, right, amount) {
  5113. var result = Quaternion.Identity();
  5114. Quaternion.SlerpToRef(left, right, amount, result);
  5115. return result;
  5116. };
  5117. /**
  5118. * Interpolates between two quaternions and stores it into a target quaternion
  5119. * @param left defines first quaternion
  5120. * @param right defines second quaternion
  5121. * @param amount defines the gradient to use
  5122. * @param result defines the target quaternion
  5123. */
  5124. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5125. var num2;
  5126. var num3;
  5127. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5128. var flag = false;
  5129. if (num4 < 0) {
  5130. flag = true;
  5131. num4 = -num4;
  5132. }
  5133. if (num4 > 0.999999) {
  5134. num3 = 1 - amount;
  5135. num2 = flag ? -amount : amount;
  5136. }
  5137. else {
  5138. var num5 = Math.acos(num4);
  5139. var num6 = (1.0 / Math.sin(num5));
  5140. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5141. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5142. }
  5143. result.x = (num3 * left.x) + (num2 * right.x);
  5144. result.y = (num3 * left.y) + (num2 * right.y);
  5145. result.z = (num3 * left.z) + (num2 * right.z);
  5146. result.w = (num3 * left.w) + (num2 * right.w);
  5147. };
  5148. /**
  5149. * Interpolate between two quaternions using Hermite interpolation
  5150. * @param value1 defines first quaternion
  5151. * @param tangent1 defines the incoming tangent
  5152. * @param value2 defines second quaternion
  5153. * @param tangent2 defines the outgoing tangent
  5154. * @param amount defines the target quaternion
  5155. * @returns the new interpolated quaternion
  5156. */
  5157. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5158. var squared = amount * amount;
  5159. var cubed = amount * squared;
  5160. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5161. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5162. var part3 = (cubed - (2.0 * squared)) + amount;
  5163. var part4 = cubed - squared;
  5164. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5165. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5166. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5167. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5168. return new Quaternion(x, y, z, w);
  5169. };
  5170. return Quaternion;
  5171. }());
  5172. BABYLON.Quaternion = Quaternion;
  5173. /**
  5174. * Class used to store matrix data (4x4)
  5175. */
  5176. var Matrix = /** @class */ (function () {
  5177. /**
  5178. * Creates an empty matrix (filled with zeros)
  5179. */
  5180. function Matrix() {
  5181. this._isIdentity = false;
  5182. this._isIdentityDirty = true;
  5183. /**
  5184. * Gets or sets the internal data of the matrix
  5185. */
  5186. this.m = new Float32Array(16);
  5187. this._markAsUpdated();
  5188. }
  5189. /** @hidden */
  5190. Matrix.prototype._markAsUpdated = function () {
  5191. this.updateFlag = Matrix._updateFlagSeed++;
  5192. this._isIdentityDirty = true;
  5193. };
  5194. // Properties
  5195. /**
  5196. * Check if the current matrix is indentity
  5197. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5198. * @returns true is the matrix is the identity matrix
  5199. */
  5200. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5201. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5202. if (this._isIdentityDirty) {
  5203. this._isIdentityDirty = false;
  5204. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5205. this._isIdentity = false;
  5206. }
  5207. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5208. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5209. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5210. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5211. this._isIdentity = false;
  5212. }
  5213. else {
  5214. this._isIdentity = true;
  5215. }
  5216. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5217. this._isIdentity = false;
  5218. }
  5219. }
  5220. return this._isIdentity;
  5221. };
  5222. /**
  5223. * Gets the determinant of the matrix
  5224. * @returns the matrix determinant
  5225. */
  5226. Matrix.prototype.determinant = function () {
  5227. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5228. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5229. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5230. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5231. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5232. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5233. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5234. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5235. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5236. };
  5237. // Methods
  5238. /**
  5239. * Returns the matrix as a Float32Array
  5240. * @returns the matrix underlying array
  5241. */
  5242. Matrix.prototype.toArray = function () {
  5243. return this.m;
  5244. };
  5245. /**
  5246. * Returns the matrix as a Float32Array
  5247. * @returns the matrix underlying array.
  5248. */
  5249. Matrix.prototype.asArray = function () {
  5250. return this.toArray();
  5251. };
  5252. /**
  5253. * Inverts the current matrix in place
  5254. * @returns the current inverted matrix
  5255. */
  5256. Matrix.prototype.invert = function () {
  5257. this.invertToRef(this);
  5258. return this;
  5259. };
  5260. /**
  5261. * Sets all the matrix elements to zero
  5262. * @returns the current matrix
  5263. */
  5264. Matrix.prototype.reset = function () {
  5265. for (var index = 0; index < 16; index++) {
  5266. this.m[index] = 0.0;
  5267. }
  5268. this._markAsUpdated();
  5269. return this;
  5270. };
  5271. /**
  5272. * Adds the current matrix with a second one
  5273. * @param other defines the matrix to add
  5274. * @returns a new matrix as the addition of the current matrix and the given one
  5275. */
  5276. Matrix.prototype.add = function (other) {
  5277. var result = new Matrix();
  5278. this.addToRef(other, result);
  5279. return result;
  5280. };
  5281. /**
  5282. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5283. * @param other defines the matrix to add
  5284. * @param result defines the target matrix
  5285. * @returns the current matrix
  5286. */
  5287. Matrix.prototype.addToRef = function (other, result) {
  5288. for (var index = 0; index < 16; index++) {
  5289. result.m[index] = this.m[index] + other.m[index];
  5290. }
  5291. result._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Adds in place the given matrix to the current matrix
  5296. * @param other defines the second operand
  5297. * @returns the current updated matrix
  5298. */
  5299. Matrix.prototype.addToSelf = function (other) {
  5300. for (var index = 0; index < 16; index++) {
  5301. this.m[index] += other.m[index];
  5302. }
  5303. this._markAsUpdated();
  5304. return this;
  5305. };
  5306. /**
  5307. * Sets the given matrix to the current inverted Matrix
  5308. * @param other defines the target matrix
  5309. * @returns the unmodified current matrix
  5310. */
  5311. Matrix.prototype.invertToRef = function (other) {
  5312. var l1 = this.m[0];
  5313. var l2 = this.m[1];
  5314. var l3 = this.m[2];
  5315. var l4 = this.m[3];
  5316. var l5 = this.m[4];
  5317. var l6 = this.m[5];
  5318. var l7 = this.m[6];
  5319. var l8 = this.m[7];
  5320. var l9 = this.m[8];
  5321. var l10 = this.m[9];
  5322. var l11 = this.m[10];
  5323. var l12 = this.m[11];
  5324. var l13 = this.m[12];
  5325. var l14 = this.m[13];
  5326. var l15 = this.m[14];
  5327. var l16 = this.m[15];
  5328. var l17 = (l11 * l16) - (l12 * l15);
  5329. var l18 = (l10 * l16) - (l12 * l14);
  5330. var l19 = (l10 * l15) - (l11 * l14);
  5331. var l20 = (l9 * l16) - (l12 * l13);
  5332. var l21 = (l9 * l15) - (l11 * l13);
  5333. var l22 = (l9 * l14) - (l10 * l13);
  5334. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5335. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5336. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5337. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5338. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5339. var l28 = (l7 * l16) - (l8 * l15);
  5340. var l29 = (l6 * l16) - (l8 * l14);
  5341. var l30 = (l6 * l15) - (l7 * l14);
  5342. var l31 = (l5 * l16) - (l8 * l13);
  5343. var l32 = (l5 * l15) - (l7 * l13);
  5344. var l33 = (l5 * l14) - (l6 * l13);
  5345. var l34 = (l7 * l12) - (l8 * l11);
  5346. var l35 = (l6 * l12) - (l8 * l10);
  5347. var l36 = (l6 * l11) - (l7 * l10);
  5348. var l37 = (l5 * l12) - (l8 * l9);
  5349. var l38 = (l5 * l11) - (l7 * l9);
  5350. var l39 = (l5 * l10) - (l6 * l9);
  5351. other.m[0] = l23 * l27;
  5352. other.m[4] = l24 * l27;
  5353. other.m[8] = l25 * l27;
  5354. other.m[12] = l26 * l27;
  5355. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5356. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5357. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5358. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5359. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5360. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5361. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5362. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5363. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5364. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5365. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5366. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5367. other._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Inserts the translation vector (using 3 floats) in the current matrix
  5372. * @param x defines the 1st component of the translation
  5373. * @param y defines the 2nd component of the translation
  5374. * @param z defines the 3rd component of the translation
  5375. * @returns the current updated matrix
  5376. */
  5377. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5378. this.m[12] = x;
  5379. this.m[13] = y;
  5380. this.m[14] = z;
  5381. this._markAsUpdated();
  5382. return this;
  5383. };
  5384. /**
  5385. * Inserts the translation vector in the current matrix
  5386. * @param vector3 defines the translation to insert
  5387. * @returns the current updated matrix
  5388. */
  5389. Matrix.prototype.setTranslation = function (vector3) {
  5390. this.m[12] = vector3.x;
  5391. this.m[13] = vector3.y;
  5392. this.m[14] = vector3.z;
  5393. this._markAsUpdated();
  5394. return this;
  5395. };
  5396. /**
  5397. * Gets the translation value of the current matrix
  5398. * @returns a new Vector3 as the extracted translation from the matrix
  5399. */
  5400. Matrix.prototype.getTranslation = function () {
  5401. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5402. };
  5403. /**
  5404. * Fill a Vector3 with the extracted translation from the matrix
  5405. * @param result defines the Vector3 where to store the translation
  5406. * @returns the current matrix
  5407. */
  5408. Matrix.prototype.getTranslationToRef = function (result) {
  5409. result.x = this.m[12];
  5410. result.y = this.m[13];
  5411. result.z = this.m[14];
  5412. return this;
  5413. };
  5414. /**
  5415. * Remove rotation and scaling part from the matrix
  5416. * @returns the updated matrix
  5417. */
  5418. Matrix.prototype.removeRotationAndScaling = function () {
  5419. this.setRowFromFloats(0, 1, 0, 0, 0);
  5420. this.setRowFromFloats(1, 0, 1, 0, 0);
  5421. this.setRowFromFloats(2, 0, 0, 1, 0);
  5422. return this;
  5423. };
  5424. /**
  5425. * Multiply two matrices
  5426. * @param other defines the second operand
  5427. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5428. */
  5429. Matrix.prototype.multiply = function (other) {
  5430. var result = new Matrix();
  5431. this.multiplyToRef(other, result);
  5432. return result;
  5433. };
  5434. /**
  5435. * Copy the current matrix from the given one
  5436. * @param other defines the source matrix
  5437. * @returns the current updated matrix
  5438. */
  5439. Matrix.prototype.copyFrom = function (other) {
  5440. for (var index = 0; index < 16; index++) {
  5441. this.m[index] = other.m[index];
  5442. }
  5443. this._markAsUpdated();
  5444. return this;
  5445. };
  5446. /**
  5447. * Populates the given array from the starting index with the current matrix values
  5448. * @param array defines the target array
  5449. * @param offset defines the offset in the target array where to start storing values
  5450. * @returns the current matrix
  5451. */
  5452. Matrix.prototype.copyToArray = function (array, offset) {
  5453. if (offset === void 0) { offset = 0; }
  5454. for (var index = 0; index < 16; index++) {
  5455. array[offset + index] = this.m[index];
  5456. }
  5457. return this;
  5458. };
  5459. /**
  5460. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5461. * @param other defines the second operand
  5462. * @param result defines the matrix where to store the multiplication
  5463. * @returns the current matrix
  5464. */
  5465. Matrix.prototype.multiplyToRef = function (other, result) {
  5466. this.multiplyToArray(other, result.m, 0);
  5467. result._markAsUpdated();
  5468. return this;
  5469. };
  5470. /**
  5471. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5472. * @param other defines the second operand
  5473. * @param result defines the array where to store the multiplication
  5474. * @param offset defines the offset in the target array where to start storing values
  5475. * @returns the current matrix
  5476. */
  5477. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5478. var tm0 = this.m[0];
  5479. var tm1 = this.m[1];
  5480. var tm2 = this.m[2];
  5481. var tm3 = this.m[3];
  5482. var tm4 = this.m[4];
  5483. var tm5 = this.m[5];
  5484. var tm6 = this.m[6];
  5485. var tm7 = this.m[7];
  5486. var tm8 = this.m[8];
  5487. var tm9 = this.m[9];
  5488. var tm10 = this.m[10];
  5489. var tm11 = this.m[11];
  5490. var tm12 = this.m[12];
  5491. var tm13 = this.m[13];
  5492. var tm14 = this.m[14];
  5493. var tm15 = this.m[15];
  5494. var om0 = other.m[0];
  5495. var om1 = other.m[1];
  5496. var om2 = other.m[2];
  5497. var om3 = other.m[3];
  5498. var om4 = other.m[4];
  5499. var om5 = other.m[5];
  5500. var om6 = other.m[6];
  5501. var om7 = other.m[7];
  5502. var om8 = other.m[8];
  5503. var om9 = other.m[9];
  5504. var om10 = other.m[10];
  5505. var om11 = other.m[11];
  5506. var om12 = other.m[12];
  5507. var om13 = other.m[13];
  5508. var om14 = other.m[14];
  5509. var om15 = other.m[15];
  5510. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5511. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5512. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5513. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5514. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5515. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5516. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5517. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5518. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5519. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5520. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5521. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5522. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5523. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5524. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5525. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5526. return this;
  5527. };
  5528. /**
  5529. * Check equality between this matrix and a second one
  5530. * @param value defines the second matrix to compare
  5531. * @returns true is the current matrix and the given one values are strictly equal
  5532. */
  5533. Matrix.prototype.equals = function (value) {
  5534. return value &&
  5535. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5536. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5537. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5538. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5539. };
  5540. /**
  5541. * Clone the current matrix
  5542. * @returns a new matrix from the current matrix
  5543. */
  5544. Matrix.prototype.clone = function () {
  5545. 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]);
  5546. };
  5547. /**
  5548. * Returns the name of the current matrix class
  5549. * @returns the string "Matrix"
  5550. */
  5551. Matrix.prototype.getClassName = function () {
  5552. return "Matrix";
  5553. };
  5554. /**
  5555. * Gets the hash code of the current matrix
  5556. * @returns the hash code
  5557. */
  5558. Matrix.prototype.getHashCode = function () {
  5559. var hash = this.m[0] || 0;
  5560. for (var i = 1; i < 16; i++) {
  5561. hash = (hash * 397) ^ (this.m[i] || 0);
  5562. }
  5563. return hash;
  5564. };
  5565. /**
  5566. * Decomposes the current Matrix into a translation, rotation and scaling components
  5567. * @param scale defines the scale vector3 given as a reference to update
  5568. * @param rotation defines the rotation quaternion given as a reference to update
  5569. * @param translation defines the translation vector3 given as a reference to update
  5570. * @returns true if operation was successful
  5571. */
  5572. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5573. if (translation) {
  5574. translation.x = this.m[12];
  5575. translation.y = this.m[13];
  5576. translation.z = this.m[14];
  5577. }
  5578. scale = scale || MathTmp.Vector3[0];
  5579. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5580. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5581. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5582. if (this.determinant() <= 0) {
  5583. scale.y *= -1;
  5584. }
  5585. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5586. if (rotation) {
  5587. rotation.x = 0;
  5588. rotation.y = 0;
  5589. rotation.z = 0;
  5590. rotation.w = 1;
  5591. }
  5592. return false;
  5593. }
  5594. if (rotation) {
  5595. 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]);
  5596. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5597. }
  5598. return true;
  5599. };
  5600. /**
  5601. * Gets specific row of the matrix
  5602. * @param index defines the number of the row to get
  5603. * @returns the index-th row of the current matrix as a new Vector4
  5604. */
  5605. Matrix.prototype.getRow = function (index) {
  5606. if (index < 0 || index > 3) {
  5607. return null;
  5608. }
  5609. var i = index * 4;
  5610. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5611. };
  5612. /**
  5613. * Sets the index-th row of the current matrix to the vector4 values
  5614. * @param index defines the number of the row to set
  5615. * @param row defines the target vector4
  5616. * @returns the updated current matrix
  5617. */
  5618. Matrix.prototype.setRow = function (index, row) {
  5619. if (index < 0 || index > 3) {
  5620. return this;
  5621. }
  5622. var i = index * 4;
  5623. this.m[i + 0] = row.x;
  5624. this.m[i + 1] = row.y;
  5625. this.m[i + 2] = row.z;
  5626. this.m[i + 3] = row.w;
  5627. this._markAsUpdated();
  5628. return this;
  5629. };
  5630. /**
  5631. * Compute the transpose of the matrix
  5632. * @returns the new transposed matrix
  5633. */
  5634. Matrix.prototype.transpose = function () {
  5635. return Matrix.Transpose(this);
  5636. };
  5637. /**
  5638. * Compute the transpose of the matrix and store it in a given matrix
  5639. * @param result defines the target matrix
  5640. * @returns the current matrix
  5641. */
  5642. Matrix.prototype.transposeToRef = function (result) {
  5643. Matrix.TransposeToRef(this, result);
  5644. return this;
  5645. };
  5646. /**
  5647. * Sets the index-th row of the current matrix with the given 4 x float values
  5648. * @param index defines the row index
  5649. * @param x defines the x component to set
  5650. * @param y defines the y component to set
  5651. * @param z defines the z component to set
  5652. * @param w defines the w component to set
  5653. * @returns the updated current matrix
  5654. */
  5655. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5656. if (index < 0 || index > 3) {
  5657. return this;
  5658. }
  5659. var i = index * 4;
  5660. this.m[i + 0] = x;
  5661. this.m[i + 1] = y;
  5662. this.m[i + 2] = z;
  5663. this.m[i + 3] = w;
  5664. this._markAsUpdated();
  5665. return this;
  5666. };
  5667. /**
  5668. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5669. * @param scale defines the scale factor
  5670. * @returns a new matrix
  5671. */
  5672. Matrix.prototype.scale = function (scale) {
  5673. var result = new Matrix();
  5674. this.scaleToRef(scale, result);
  5675. return result;
  5676. };
  5677. /**
  5678. * Scale the current matrix values by a factor to a given result matrix
  5679. * @param scale defines the scale factor
  5680. * @param result defines the matrix to store the result
  5681. * @returns the current matrix
  5682. */
  5683. Matrix.prototype.scaleToRef = function (scale, result) {
  5684. for (var index = 0; index < 16; index++) {
  5685. result.m[index] = this.m[index] * scale;
  5686. }
  5687. result._markAsUpdated();
  5688. return this;
  5689. };
  5690. /**
  5691. * Scale the current matrix values by a factor and add the result to a given matrix
  5692. * @param scale defines the scale factor
  5693. * @param result defines the Matrix to store the result
  5694. * @returns the current matrix
  5695. */
  5696. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5697. for (var index = 0; index < 16; index++) {
  5698. result.m[index] += this.m[index] * scale;
  5699. }
  5700. result._markAsUpdated();
  5701. return this;
  5702. };
  5703. /**
  5704. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5705. * @param ref matrix to store the result
  5706. */
  5707. Matrix.prototype.toNormalMatrix = function (ref) {
  5708. this.invertToRef(ref);
  5709. ref.transpose();
  5710. var m = ref.m;
  5711. 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);
  5712. };
  5713. /**
  5714. * Gets only rotation part of the current matrix
  5715. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5716. */
  5717. Matrix.prototype.getRotationMatrix = function () {
  5718. var result = Matrix.Identity();
  5719. this.getRotationMatrixToRef(result);
  5720. return result;
  5721. };
  5722. /**
  5723. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5724. * @param result defines the target matrix to store data to
  5725. * @returns the current matrix
  5726. */
  5727. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5728. var m = this.m;
  5729. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5730. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5731. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5732. if (this.determinant() <= 0) {
  5733. sy *= -1;
  5734. }
  5735. if (sx === 0 || sy === 0 || sz === 0) {
  5736. Matrix.IdentityToRef(result);
  5737. }
  5738. else {
  5739. 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);
  5740. }
  5741. return this;
  5742. };
  5743. // Statics
  5744. /**
  5745. * Creates a matrix from an array
  5746. * @param array defines the source array
  5747. * @param offset defines an offset in the source array
  5748. * @returns a new Matrix set from the starting index of the given array
  5749. */
  5750. Matrix.FromArray = function (array, offset) {
  5751. var result = new Matrix();
  5752. if (!offset) {
  5753. offset = 0;
  5754. }
  5755. Matrix.FromArrayToRef(array, offset, result);
  5756. return result;
  5757. };
  5758. /**
  5759. * Copy the content of an array into a given matrix
  5760. * @param array defines the source array
  5761. * @param offset defines an offset in the source array
  5762. * @param result defines the target matrix
  5763. */
  5764. Matrix.FromArrayToRef = function (array, offset, result) {
  5765. for (var index = 0; index < 16; index++) {
  5766. result.m[index] = array[index + offset];
  5767. }
  5768. result._markAsUpdated();
  5769. };
  5770. /**
  5771. * Stores an array into a matrix after having multiplied each component by a given factor
  5772. * @param array defines the source array
  5773. * @param offset defines the offset in the source array
  5774. * @param scale defines the scaling factor
  5775. * @param result defines the target matrix
  5776. */
  5777. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5778. for (var index = 0; index < 16; index++) {
  5779. result.m[index] = array[index + offset] * scale;
  5780. }
  5781. result._markAsUpdated();
  5782. };
  5783. /**
  5784. * Stores a list of values (16) inside a given matrix
  5785. * @param initialM11 defines 1st value of 1st row
  5786. * @param initialM12 defines 2nd value of 1st row
  5787. * @param initialM13 defines 3rd value of 1st row
  5788. * @param initialM14 defines 4th value of 1st row
  5789. * @param initialM21 defines 1st value of 2nd row
  5790. * @param initialM22 defines 2nd value of 2nd row
  5791. * @param initialM23 defines 3rd value of 2nd row
  5792. * @param initialM24 defines 4th value of 2nd row
  5793. * @param initialM31 defines 1st value of 3rd row
  5794. * @param initialM32 defines 2nd value of 3rd row
  5795. * @param initialM33 defines 3rd value of 3rd row
  5796. * @param initialM34 defines 4th value of 3rd row
  5797. * @param initialM41 defines 1st value of 4th row
  5798. * @param initialM42 defines 2nd value of 4th row
  5799. * @param initialM43 defines 3rd value of 4th row
  5800. * @param initialM44 defines 4th value of 4th row
  5801. * @param result defines the target matrix
  5802. */
  5803. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5804. result.m[0] = initialM11;
  5805. result.m[1] = initialM12;
  5806. result.m[2] = initialM13;
  5807. result.m[3] = initialM14;
  5808. result.m[4] = initialM21;
  5809. result.m[5] = initialM22;
  5810. result.m[6] = initialM23;
  5811. result.m[7] = initialM24;
  5812. result.m[8] = initialM31;
  5813. result.m[9] = initialM32;
  5814. result.m[10] = initialM33;
  5815. result.m[11] = initialM34;
  5816. result.m[12] = initialM41;
  5817. result.m[13] = initialM42;
  5818. result.m[14] = initialM43;
  5819. result.m[15] = initialM44;
  5820. result._markAsUpdated();
  5821. };
  5822. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5823. /**
  5824. * Gets an identity matrix that must not be updated
  5825. */
  5826. get: function () {
  5827. return Matrix._identityReadOnly;
  5828. },
  5829. enumerable: true,
  5830. configurable: true
  5831. });
  5832. /**
  5833. * Creates new matrix from a list of values (16)
  5834. * @param initialM11 defines 1st value of 1st row
  5835. * @param initialM12 defines 2nd value of 1st row
  5836. * @param initialM13 defines 3rd value of 1st row
  5837. * @param initialM14 defines 4th value of 1st row
  5838. * @param initialM21 defines 1st value of 2nd row
  5839. * @param initialM22 defines 2nd value of 2nd row
  5840. * @param initialM23 defines 3rd value of 2nd row
  5841. * @param initialM24 defines 4th value of 2nd row
  5842. * @param initialM31 defines 1st value of 3rd row
  5843. * @param initialM32 defines 2nd value of 3rd row
  5844. * @param initialM33 defines 3rd value of 3rd row
  5845. * @param initialM34 defines 4th value of 3rd row
  5846. * @param initialM41 defines 1st value of 4th row
  5847. * @param initialM42 defines 2nd value of 4th row
  5848. * @param initialM43 defines 3rd value of 4th row
  5849. * @param initialM44 defines 4th value of 4th row
  5850. * @returns the new matrix
  5851. */
  5852. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5853. var result = new Matrix();
  5854. result.m[0] = initialM11;
  5855. result.m[1] = initialM12;
  5856. result.m[2] = initialM13;
  5857. result.m[3] = initialM14;
  5858. result.m[4] = initialM21;
  5859. result.m[5] = initialM22;
  5860. result.m[6] = initialM23;
  5861. result.m[7] = initialM24;
  5862. result.m[8] = initialM31;
  5863. result.m[9] = initialM32;
  5864. result.m[10] = initialM33;
  5865. result.m[11] = initialM34;
  5866. result.m[12] = initialM41;
  5867. result.m[13] = initialM42;
  5868. result.m[14] = initialM43;
  5869. result.m[15] = initialM44;
  5870. return result;
  5871. };
  5872. /**
  5873. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5874. * @param scale defines the scale vector3
  5875. * @param rotation defines the rotation quaternion
  5876. * @param translation defines the translation vector3
  5877. * @returns a new matrix
  5878. */
  5879. Matrix.Compose = function (scale, rotation, translation) {
  5880. var result = Matrix.Identity();
  5881. Matrix.ComposeToRef(scale, rotation, translation, result);
  5882. return result;
  5883. };
  5884. /**
  5885. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5886. * @param scale defines the scale vector3
  5887. * @param rotation defines the rotation quaternion
  5888. * @param translation defines the translation vector3
  5889. * @param result defines the target matrix
  5890. */
  5891. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5892. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5893. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5894. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5895. result.setTranslation(translation);
  5896. };
  5897. /**
  5898. * Creates a new identity matrix
  5899. * @returns a new identity matrix
  5900. */
  5901. Matrix.Identity = function () {
  5902. 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);
  5903. };
  5904. /**
  5905. * Creates a new identity matrix and stores the result in a given matrix
  5906. * @param result defines the target matrix
  5907. */
  5908. Matrix.IdentityToRef = function (result) {
  5909. 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);
  5910. };
  5911. /**
  5912. * Creates a new zero matrix
  5913. * @returns a new zero matrix
  5914. */
  5915. Matrix.Zero = function () {
  5916. 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);
  5917. };
  5918. /**
  5919. * Creates a new rotation matrix for "angle" radians around the X axis
  5920. * @param angle defines the angle (in radians) to use
  5921. * @return the new matrix
  5922. */
  5923. Matrix.RotationX = function (angle) {
  5924. var result = new Matrix();
  5925. Matrix.RotationXToRef(angle, result);
  5926. return result;
  5927. };
  5928. /**
  5929. * Creates a new matrix as the invert of a given matrix
  5930. * @param source defines the source matrix
  5931. * @returns the new matrix
  5932. */
  5933. Matrix.Invert = function (source) {
  5934. var result = new Matrix();
  5935. source.invertToRef(result);
  5936. return result;
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5940. * @param angle defines the angle (in radians) to use
  5941. * @param result defines the target matrix
  5942. */
  5943. Matrix.RotationXToRef = function (angle, result) {
  5944. var s = Math.sin(angle);
  5945. var c = Math.cos(angle);
  5946. result.m[0] = 1.0;
  5947. result.m[15] = 1.0;
  5948. result.m[5] = c;
  5949. result.m[10] = c;
  5950. result.m[9] = -s;
  5951. result.m[6] = s;
  5952. result.m[1] = 0.0;
  5953. result.m[2] = 0.0;
  5954. result.m[3] = 0.0;
  5955. result.m[4] = 0.0;
  5956. result.m[7] = 0.0;
  5957. result.m[8] = 0.0;
  5958. result.m[11] = 0.0;
  5959. result.m[12] = 0.0;
  5960. result.m[13] = 0.0;
  5961. result.m[14] = 0.0;
  5962. result._markAsUpdated();
  5963. };
  5964. /**
  5965. * Creates a new rotation matrix for "angle" radians around the Y axis
  5966. * @param angle defines the angle (in radians) to use
  5967. * @return the new matrix
  5968. */
  5969. Matrix.RotationY = function (angle) {
  5970. var result = new Matrix();
  5971. Matrix.RotationYToRef(angle, result);
  5972. return result;
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationYToRef = function (angle, result) {
  5980. var s = Math.sin(angle);
  5981. var c = Math.cos(angle);
  5982. result.m[5] = 1.0;
  5983. result.m[15] = 1.0;
  5984. result.m[0] = c;
  5985. result.m[2] = -s;
  5986. result.m[8] = s;
  5987. result.m[10] = c;
  5988. result.m[1] = 0.0;
  5989. result.m[3] = 0.0;
  5990. result.m[4] = 0.0;
  5991. result.m[6] = 0.0;
  5992. result.m[7] = 0.0;
  5993. result.m[9] = 0.0;
  5994. result.m[11] = 0.0;
  5995. result.m[12] = 0.0;
  5996. result.m[13] = 0.0;
  5997. result.m[14] = 0.0;
  5998. result._markAsUpdated();
  5999. };
  6000. /**
  6001. * Creates a new rotation matrix for "angle" radians around the Z axis
  6002. * @param angle defines the angle (in radians) to use
  6003. * @return the new matrix
  6004. */
  6005. Matrix.RotationZ = function (angle) {
  6006. var result = new Matrix();
  6007. Matrix.RotationZToRef(angle, result);
  6008. return result;
  6009. };
  6010. /**
  6011. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6012. * @param angle defines the angle (in radians) to use
  6013. * @param result defines the target matrix
  6014. */
  6015. Matrix.RotationZToRef = function (angle, result) {
  6016. var s = Math.sin(angle);
  6017. var c = Math.cos(angle);
  6018. result.m[10] = 1.0;
  6019. result.m[15] = 1.0;
  6020. result.m[0] = c;
  6021. result.m[1] = s;
  6022. result.m[4] = -s;
  6023. result.m[5] = c;
  6024. result.m[2] = 0.0;
  6025. result.m[3] = 0.0;
  6026. result.m[6] = 0.0;
  6027. result.m[7] = 0.0;
  6028. result.m[8] = 0.0;
  6029. result.m[9] = 0.0;
  6030. result.m[11] = 0.0;
  6031. result.m[12] = 0.0;
  6032. result.m[13] = 0.0;
  6033. result.m[14] = 0.0;
  6034. result._markAsUpdated();
  6035. };
  6036. /**
  6037. * Creates a new rotation matrix for "angle" radians around the given axis
  6038. * @param axis defines the axis to use
  6039. * @param angle defines the angle (in radians) to use
  6040. * @return the new matrix
  6041. */
  6042. Matrix.RotationAxis = function (axis, angle) {
  6043. var result = Matrix.Zero();
  6044. Matrix.RotationAxisToRef(axis, angle, result);
  6045. return result;
  6046. };
  6047. /**
  6048. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6049. * @param axis defines the axis to use
  6050. * @param angle defines the angle (in radians) to use
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6054. var s = Math.sin(-angle);
  6055. var c = Math.cos(-angle);
  6056. var c1 = 1 - c;
  6057. axis.normalize();
  6058. result.m[0] = (axis.x * axis.x) * c1 + c;
  6059. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6060. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6061. result.m[3] = 0.0;
  6062. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6063. result.m[5] = (axis.y * axis.y) * c1 + c;
  6064. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6065. result.m[7] = 0.0;
  6066. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6067. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6068. result.m[10] = (axis.z * axis.z) * c1 + c;
  6069. result.m[11] = 0.0;
  6070. result.m[15] = 1.0;
  6071. result._markAsUpdated();
  6072. };
  6073. /**
  6074. * Creates a rotation matrix
  6075. * @param yaw defines the yaw angle in radians (Y axis)
  6076. * @param pitch defines the pitch angle in radians (X axis)
  6077. * @param roll defines the roll angle in radians (X axis)
  6078. * @returns the new rotation matrix
  6079. */
  6080. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6081. var result = new Matrix();
  6082. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6083. return result;
  6084. };
  6085. /**
  6086. * Creates a rotation matrix and stores it in a given matrix
  6087. * @param yaw defines the yaw angle in radians (Y axis)
  6088. * @param pitch defines the pitch angle in radians (X axis)
  6089. * @param roll defines the roll angle in radians (X axis)
  6090. * @param result defines the target matrix
  6091. */
  6092. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6093. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6094. this._tempQuaternion.toRotationMatrix(result);
  6095. };
  6096. /**
  6097. * Creates a scaling matrix
  6098. * @param x defines the scale factor on X axis
  6099. * @param y defines the scale factor on Y axis
  6100. * @param z defines the scale factor on Z axis
  6101. * @returns the new matrix
  6102. */
  6103. Matrix.Scaling = function (x, y, z) {
  6104. var result = Matrix.Zero();
  6105. Matrix.ScalingToRef(x, y, z, result);
  6106. return result;
  6107. };
  6108. /**
  6109. * Creates a scaling matrix and stores it in a given matrix
  6110. * @param x defines the scale factor on X axis
  6111. * @param y defines the scale factor on Y axis
  6112. * @param z defines the scale factor on Z axis
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.ScalingToRef = function (x, y, z, result) {
  6116. result.m[0] = x;
  6117. result.m[1] = 0.0;
  6118. result.m[2] = 0.0;
  6119. result.m[3] = 0.0;
  6120. result.m[4] = 0.0;
  6121. result.m[5] = y;
  6122. result.m[6] = 0.0;
  6123. result.m[7] = 0.0;
  6124. result.m[8] = 0.0;
  6125. result.m[9] = 0.0;
  6126. result.m[10] = z;
  6127. result.m[11] = 0.0;
  6128. result.m[12] = 0.0;
  6129. result.m[13] = 0.0;
  6130. result.m[14] = 0.0;
  6131. result.m[15] = 1.0;
  6132. result._markAsUpdated();
  6133. };
  6134. /**
  6135. * Creates a translation matrix
  6136. * @param x defines the translation on X axis
  6137. * @param y defines the translation on Y axis
  6138. * @param z defines the translationon Z axis
  6139. * @returns the new matrix
  6140. */
  6141. Matrix.Translation = function (x, y, z) {
  6142. var result = Matrix.Identity();
  6143. Matrix.TranslationToRef(x, y, z, result);
  6144. return result;
  6145. };
  6146. /**
  6147. * Creates a translation matrix and stores it in a given matrix
  6148. * @param x defines the translation on X axis
  6149. * @param y defines the translation on Y axis
  6150. * @param z defines the translationon Z axis
  6151. * @param result defines the target matrix
  6152. */
  6153. Matrix.TranslationToRef = function (x, y, z, result) {
  6154. 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);
  6155. };
  6156. /**
  6157. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6158. * @param startValue defines the start value
  6159. * @param endValue defines the end value
  6160. * @param gradient defines the gradient factor
  6161. * @returns the new matrix
  6162. */
  6163. Matrix.Lerp = function (startValue, endValue, gradient) {
  6164. var result = Matrix.Zero();
  6165. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6166. return result;
  6167. };
  6168. /**
  6169. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6170. * @param startValue defines the start value
  6171. * @param endValue defines the end value
  6172. * @param gradient defines the gradient factor
  6173. * @param result defines the Matrix object where to store data
  6174. */
  6175. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6176. for (var index = 0; index < 16; index++) {
  6177. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6178. }
  6179. result._markAsUpdated();
  6180. };
  6181. /**
  6182. * Builds a new matrix whose values are computed by:
  6183. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6184. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6185. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6186. * @param startValue defines the first matrix
  6187. * @param endValue defines the second matrix
  6188. * @param gradient defines the gradient between the two matrices
  6189. * @returns the new matrix
  6190. */
  6191. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6192. var result = Matrix.Zero();
  6193. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6194. return result;
  6195. };
  6196. /**
  6197. * Update a matrix to values which are computed by:
  6198. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6199. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6200. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6201. * @param startValue defines the first matrix
  6202. * @param endValue defines the second matrix
  6203. * @param gradient defines the gradient between the two matrices
  6204. * @param result defines the target matrix
  6205. */
  6206. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6207. var startScale = MathTmp.Vector3[0];
  6208. var startRotation = MathTmp.Quaternion[0];
  6209. var startTranslation = MathTmp.Vector3[1];
  6210. startValue.decompose(startScale, startRotation, startTranslation);
  6211. var endScale = MathTmp.Vector3[2];
  6212. var endRotation = MathTmp.Quaternion[1];
  6213. var endTranslation = MathTmp.Vector3[3];
  6214. endValue.decompose(endScale, endRotation, endTranslation);
  6215. var resultScale = MathTmp.Vector3[4];
  6216. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6217. var resultRotation = MathTmp.Quaternion[2];
  6218. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6219. var resultTranslation = MathTmp.Vector3[5];
  6220. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6221. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6222. };
  6223. /**
  6224. * 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"
  6225. * This function works in left handed mode
  6226. * @param eye defines the final position of the entity
  6227. * @param target defines where the entity should look at
  6228. * @param up defines the up vector for the entity
  6229. * @returns the new matrix
  6230. */
  6231. Matrix.LookAtLH = function (eye, target, up) {
  6232. var result = Matrix.Zero();
  6233. Matrix.LookAtLHToRef(eye, target, up, result);
  6234. return result;
  6235. };
  6236. /**
  6237. * 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".
  6238. * This function works in left handed mode
  6239. * @param eye defines the final position of the entity
  6240. * @param target defines where the entity should look at
  6241. * @param up defines the up vector for the entity
  6242. * @param result defines the target matrix
  6243. */
  6244. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6245. // Z axis
  6246. target.subtractToRef(eye, this._zAxis);
  6247. this._zAxis.normalize();
  6248. // X axis
  6249. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6250. if (this._xAxis.lengthSquared() === 0) {
  6251. this._xAxis.x = 1.0;
  6252. }
  6253. else {
  6254. this._xAxis.normalize();
  6255. }
  6256. // Y axis
  6257. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6258. this._yAxis.normalize();
  6259. // Eye angles
  6260. var ex = -Vector3.Dot(this._xAxis, eye);
  6261. var ey = -Vector3.Dot(this._yAxis, eye);
  6262. var ez = -Vector3.Dot(this._zAxis, eye);
  6263. 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);
  6264. };
  6265. /**
  6266. * 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"
  6267. * This function works in right handed mode
  6268. * @param eye defines the final position of the entity
  6269. * @param target defines where the entity should look at
  6270. * @param up defines the up vector for the entity
  6271. * @returns the new matrix
  6272. */
  6273. Matrix.LookAtRH = function (eye, target, up) {
  6274. var result = Matrix.Zero();
  6275. Matrix.LookAtRHToRef(eye, target, up, result);
  6276. return result;
  6277. };
  6278. /**
  6279. * 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".
  6280. * This function works in right handed mode
  6281. * @param eye defines the final position of the entity
  6282. * @param target defines where the entity should look at
  6283. * @param up defines the up vector for the entity
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6287. // Z axis
  6288. eye.subtractToRef(target, this._zAxis);
  6289. this._zAxis.normalize();
  6290. // X axis
  6291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6292. if (this._xAxis.lengthSquared() === 0) {
  6293. this._xAxis.x = 1.0;
  6294. }
  6295. else {
  6296. this._xAxis.normalize();
  6297. }
  6298. // Y axis
  6299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6300. this._yAxis.normalize();
  6301. // Eye angles
  6302. var ex = -Vector3.Dot(this._xAxis, eye);
  6303. var ey = -Vector3.Dot(this._yAxis, eye);
  6304. var ez = -Vector3.Dot(this._zAxis, eye);
  6305. 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);
  6306. };
  6307. /**
  6308. * Create a left-handed orthographic projection matrix
  6309. * @param width defines the viewport width
  6310. * @param height defines the viewport height
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @returns a new matrix as a left-handed orthographic projection matrix
  6314. */
  6315. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6316. var matrix = Matrix.Zero();
  6317. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6318. return matrix;
  6319. };
  6320. /**
  6321. * Store a left-handed orthographic projection to a given matrix
  6322. * @param width defines the viewport width
  6323. * @param height defines the viewport height
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @param result defines the target matrix
  6327. */
  6328. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6329. var n = znear;
  6330. var f = zfar;
  6331. var a = 2.0 / width;
  6332. var b = 2.0 / height;
  6333. var c = 2.0 / (f - n);
  6334. var d = -(f + n) / (f - n);
  6335. 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);
  6336. };
  6337. /**
  6338. * Create a left-handed orthographic projection matrix
  6339. * @param left defines the viewport left coordinate
  6340. * @param right defines the viewport right coordinate
  6341. * @param bottom defines the viewport bottom coordinate
  6342. * @param top defines the viewport top coordinate
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed orthographic projection matrix
  6346. */
  6347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6350. return matrix;
  6351. };
  6352. /**
  6353. * Stores a left-handed orthographic projection into a given matrix
  6354. * @param left defines the viewport left coordinate
  6355. * @param right defines the viewport right coordinate
  6356. * @param bottom defines the viewport bottom coordinate
  6357. * @param top defines the viewport top coordinate
  6358. * @param znear defines the near clip plane
  6359. * @param zfar defines the far clip plane
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6363. var n = znear;
  6364. var f = zfar;
  6365. var a = 2.0 / (right - left);
  6366. var b = 2.0 / (top - bottom);
  6367. var c = 2.0 / (f - n);
  6368. var d = -(f + n) / (f - n);
  6369. var i0 = (left + right) / (left - right);
  6370. var i1 = (top + bottom) / (bottom - top);
  6371. 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);
  6372. };
  6373. /**
  6374. * Creates a right-handed orthographic projection matrix
  6375. * @param left defines the viewport left coordinate
  6376. * @param right defines the viewport right coordinate
  6377. * @param bottom defines the viewport bottom coordinate
  6378. * @param top defines the viewport top coordinate
  6379. * @param znear defines the near clip plane
  6380. * @param zfar defines the far clip plane
  6381. * @returns a new matrix as a right-handed orthographic projection matrix
  6382. */
  6383. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6384. var matrix = Matrix.Zero();
  6385. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6386. return matrix;
  6387. };
  6388. /**
  6389. * Stores a right-handed orthographic projection into a given matrix
  6390. * @param left defines the viewport left coordinate
  6391. * @param right defines the viewport right coordinate
  6392. * @param bottom defines the viewport bottom coordinate
  6393. * @param top defines the viewport top coordinate
  6394. * @param znear defines the near clip plane
  6395. * @param zfar defines the far clip plane
  6396. * @param result defines the target matrix
  6397. */
  6398. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6399. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6400. result.m[10] *= -1.0;
  6401. };
  6402. /**
  6403. * Creates a left-handed perspective projection matrix
  6404. * @param width defines the viewport width
  6405. * @param height defines the viewport height
  6406. * @param znear defines the near clip plane
  6407. * @param zfar defines the far clip plane
  6408. * @returns a new matrix as a left-handed perspective projection matrix
  6409. */
  6410. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6411. var matrix = Matrix.Zero();
  6412. var n = znear;
  6413. var f = zfar;
  6414. var a = 2.0 * n / width;
  6415. var b = 2.0 * n / height;
  6416. var c = (f + n) / (f - n);
  6417. var d = -2.0 * f * n / (f - n);
  6418. 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);
  6419. return matrix;
  6420. };
  6421. /**
  6422. * Creates a left-handed perspective projection matrix
  6423. * @param fov defines the horizontal field of view
  6424. * @param aspect defines the aspect ratio
  6425. * @param znear defines the near clip plane
  6426. * @param zfar defines the far clip plane
  6427. * @returns a new matrix as a left-handed perspective projection matrix
  6428. */
  6429. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6430. var matrix = Matrix.Zero();
  6431. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6432. return matrix;
  6433. };
  6434. /**
  6435. * Stores a left-handed perspective projection into a given matrix
  6436. * @param fov defines the horizontal field of view
  6437. * @param aspect defines the aspect ratio
  6438. * @param znear defines the near clip plane
  6439. * @param zfar defines the far clip plane
  6440. * @param result defines the target matrix
  6441. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6442. */
  6443. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6444. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6445. var n = znear;
  6446. var f = zfar;
  6447. var t = 1.0 / (Math.tan(fov * 0.5));
  6448. var a = isVerticalFovFixed ? (t / aspect) : t;
  6449. var b = isVerticalFovFixed ? t : (t * aspect);
  6450. var c = (f + n) / (f - n);
  6451. var d = -2.0 * f * n / (f - n);
  6452. 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);
  6453. };
  6454. /**
  6455. * Creates a right-handed perspective projection matrix
  6456. * @param fov defines the horizontal field of view
  6457. * @param aspect defines the aspect ratio
  6458. * @param znear defines the near clip plane
  6459. * @param zfar defines the far clip plane
  6460. * @returns a new matrix as a right-handed perspective projection matrix
  6461. */
  6462. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6463. var matrix = Matrix.Zero();
  6464. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6465. return matrix;
  6466. };
  6467. /**
  6468. * Stores a right-handed perspective projection into a given matrix
  6469. * @param fov defines the horizontal field of view
  6470. * @param aspect defines the aspect ratio
  6471. * @param znear defines the near clip plane
  6472. * @param zfar defines the far clip plane
  6473. * @param result defines the target matrix
  6474. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6475. */
  6476. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6477. //alternatively this could be expressed as:
  6478. // m = PerspectiveFovLHToRef
  6479. // m[10] *= -1.0;
  6480. // m[11] *= -1.0;
  6481. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6482. var n = znear;
  6483. var f = zfar;
  6484. var t = 1.0 / (Math.tan(fov * 0.5));
  6485. var a = isVerticalFovFixed ? (t / aspect) : t;
  6486. var b = isVerticalFovFixed ? t : (t * aspect);
  6487. var c = -(f + n) / (f - n);
  6488. var d = -2 * f * n / (f - n);
  6489. 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);
  6490. };
  6491. /**
  6492. * Stores a perspective projection for WebVR info a given matrix
  6493. * @param fov defines the field of view
  6494. * @param znear defines the near clip plane
  6495. * @param zfar defines the far clip plane
  6496. * @param result defines the target matrix
  6497. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6498. */
  6499. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6500. if (rightHanded === void 0) { rightHanded = false; }
  6501. var rightHandedFactor = rightHanded ? -1 : 1;
  6502. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6503. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6504. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6505. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6506. var xScale = 2.0 / (leftTan + rightTan);
  6507. var yScale = 2.0 / (upTan + downTan);
  6508. result.m[0] = xScale;
  6509. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6510. result.m[5] = yScale;
  6511. result.m[6] = result.m[7] = 0.0;
  6512. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6513. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6514. result.m[10] = -zfar / (znear - zfar);
  6515. result.m[11] = 1.0 * rightHandedFactor;
  6516. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6517. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6518. result._markAsUpdated();
  6519. };
  6520. /**
  6521. * Computes a complete transformation matrix
  6522. * @param viewport defines the viewport to use
  6523. * @param world defines the world matrix
  6524. * @param view defines the view matrix
  6525. * @param projection defines the projection matrix
  6526. * @param zmin defines the near clip plane
  6527. * @param zmax defines the far clip plane
  6528. * @returns the transformation matrix
  6529. */
  6530. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6531. var cw = viewport.width;
  6532. var ch = viewport.height;
  6533. var cx = viewport.x;
  6534. var cy = viewport.y;
  6535. 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);
  6536. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6537. };
  6538. /**
  6539. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6540. * @param matrix defines the matrix to use
  6541. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6542. */
  6543. Matrix.GetAsMatrix2x2 = function (matrix) {
  6544. return new Float32Array([
  6545. matrix.m[0], matrix.m[1],
  6546. matrix.m[4], matrix.m[5]
  6547. ]);
  6548. };
  6549. /**
  6550. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6551. * @param matrix defines the matrix to use
  6552. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6553. */
  6554. Matrix.GetAsMatrix3x3 = function (matrix) {
  6555. return new Float32Array([
  6556. matrix.m[0], matrix.m[1], matrix.m[2],
  6557. matrix.m[4], matrix.m[5], matrix.m[6],
  6558. matrix.m[8], matrix.m[9], matrix.m[10]
  6559. ]);
  6560. };
  6561. /**
  6562. * Compute the transpose of a given matrix
  6563. * @param matrix defines the matrix to transpose
  6564. * @returns the new matrix
  6565. */
  6566. Matrix.Transpose = function (matrix) {
  6567. var result = new Matrix();
  6568. Matrix.TransposeToRef(matrix, result);
  6569. return result;
  6570. };
  6571. /**
  6572. * Compute the transpose of a matrix and store it in a target matrix
  6573. * @param matrix defines the matrix to transpose
  6574. * @param result defines the target matrix
  6575. */
  6576. Matrix.TransposeToRef = function (matrix, result) {
  6577. result.m[0] = matrix.m[0];
  6578. result.m[1] = matrix.m[4];
  6579. result.m[2] = matrix.m[8];
  6580. result.m[3] = matrix.m[12];
  6581. result.m[4] = matrix.m[1];
  6582. result.m[5] = matrix.m[5];
  6583. result.m[6] = matrix.m[9];
  6584. result.m[7] = matrix.m[13];
  6585. result.m[8] = matrix.m[2];
  6586. result.m[9] = matrix.m[6];
  6587. result.m[10] = matrix.m[10];
  6588. result.m[11] = matrix.m[14];
  6589. result.m[12] = matrix.m[3];
  6590. result.m[13] = matrix.m[7];
  6591. result.m[14] = matrix.m[11];
  6592. result.m[15] = matrix.m[15];
  6593. };
  6594. /**
  6595. * Computes a reflection matrix from a plane
  6596. * @param plane defines the reflection plane
  6597. * @returns a new matrix
  6598. */
  6599. Matrix.Reflection = function (plane) {
  6600. var matrix = new Matrix();
  6601. Matrix.ReflectionToRef(plane, matrix);
  6602. return matrix;
  6603. };
  6604. /**
  6605. * Computes a reflection matrix from a plane
  6606. * @param plane defines the reflection plane
  6607. * @param result defines the target matrix
  6608. */
  6609. Matrix.ReflectionToRef = function (plane, result) {
  6610. plane.normalize();
  6611. var x = plane.normal.x;
  6612. var y = plane.normal.y;
  6613. var z = plane.normal.z;
  6614. var temp = -2 * x;
  6615. var temp2 = -2 * y;
  6616. var temp3 = -2 * z;
  6617. result.m[0] = (temp * x) + 1;
  6618. result.m[1] = temp2 * x;
  6619. result.m[2] = temp3 * x;
  6620. result.m[3] = 0.0;
  6621. result.m[4] = temp * y;
  6622. result.m[5] = (temp2 * y) + 1;
  6623. result.m[6] = temp3 * y;
  6624. result.m[7] = 0.0;
  6625. result.m[8] = temp * z;
  6626. result.m[9] = temp2 * z;
  6627. result.m[10] = (temp3 * z) + 1;
  6628. result.m[11] = 0.0;
  6629. result.m[12] = temp * plane.d;
  6630. result.m[13] = temp2 * plane.d;
  6631. result.m[14] = temp3 * plane.d;
  6632. result.m[15] = 1.0;
  6633. result._markAsUpdated();
  6634. };
  6635. /**
  6636. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6637. * @param xaxis defines the value of the 1st axis
  6638. * @param yaxis defines the value of the 2nd axis
  6639. * @param zaxis defines the value of the 3rd axis
  6640. * @param result defines the target matrix
  6641. */
  6642. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6643. result.m[0] = xaxis.x;
  6644. result.m[1] = xaxis.y;
  6645. result.m[2] = xaxis.z;
  6646. result.m[3] = 0.0;
  6647. result.m[4] = yaxis.x;
  6648. result.m[5] = yaxis.y;
  6649. result.m[6] = yaxis.z;
  6650. result.m[7] = 0.0;
  6651. result.m[8] = zaxis.x;
  6652. result.m[9] = zaxis.y;
  6653. result.m[10] = zaxis.z;
  6654. result.m[11] = 0.0;
  6655. result.m[12] = 0.0;
  6656. result.m[13] = 0.0;
  6657. result.m[14] = 0.0;
  6658. result.m[15] = 1.0;
  6659. result._markAsUpdated();
  6660. };
  6661. /**
  6662. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6663. * @param quat defines the quaternion to use
  6664. * @param result defines the target matrix
  6665. */
  6666. Matrix.FromQuaternionToRef = function (quat, result) {
  6667. var xx = quat.x * quat.x;
  6668. var yy = quat.y * quat.y;
  6669. var zz = quat.z * quat.z;
  6670. var xy = quat.x * quat.y;
  6671. var zw = quat.z * quat.w;
  6672. var zx = quat.z * quat.x;
  6673. var yw = quat.y * quat.w;
  6674. var yz = quat.y * quat.z;
  6675. var xw = quat.x * quat.w;
  6676. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6677. result.m[1] = 2.0 * (xy + zw);
  6678. result.m[2] = 2.0 * (zx - yw);
  6679. result.m[3] = 0.0;
  6680. result.m[4] = 2.0 * (xy - zw);
  6681. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6682. result.m[6] = 2.0 * (yz + xw);
  6683. result.m[7] = 0.0;
  6684. result.m[8] = 2.0 * (zx + yw);
  6685. result.m[9] = 2.0 * (yz - xw);
  6686. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6687. result.m[11] = 0.0;
  6688. result.m[12] = 0.0;
  6689. result.m[13] = 0.0;
  6690. result.m[14] = 0.0;
  6691. result.m[15] = 1.0;
  6692. result._markAsUpdated();
  6693. };
  6694. Matrix._tempQuaternion = new Quaternion();
  6695. Matrix._xAxis = Vector3.Zero();
  6696. Matrix._yAxis = Vector3.Zero();
  6697. Matrix._zAxis = Vector3.Zero();
  6698. Matrix._updateFlagSeed = 0;
  6699. Matrix._identityReadOnly = Matrix.Identity();
  6700. return Matrix;
  6701. }());
  6702. BABYLON.Matrix = Matrix;
  6703. var Plane = /** @class */ (function () {
  6704. /**
  6705. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6706. */
  6707. function Plane(a, b, c, d) {
  6708. this.normal = new Vector3(a, b, c);
  6709. this.d = d;
  6710. }
  6711. /**
  6712. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6713. */
  6714. Plane.prototype.asArray = function () {
  6715. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6716. };
  6717. // Methods
  6718. /**
  6719. * Returns a new plane copied from the current Plane.
  6720. */
  6721. Plane.prototype.clone = function () {
  6722. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6723. };
  6724. /**
  6725. * Returns the string "Plane".
  6726. */
  6727. Plane.prototype.getClassName = function () {
  6728. return "Plane";
  6729. };
  6730. /**
  6731. * Returns the Plane hash code.
  6732. */
  6733. Plane.prototype.getHashCode = function () {
  6734. var hash = this.normal.getHashCode();
  6735. hash = (hash * 397) ^ (this.d || 0);
  6736. return hash;
  6737. };
  6738. /**
  6739. * Normalize the current Plane in place.
  6740. * Returns the updated Plane.
  6741. */
  6742. Plane.prototype.normalize = function () {
  6743. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6744. var magnitude = 0.0;
  6745. if (norm !== 0) {
  6746. magnitude = 1.0 / norm;
  6747. }
  6748. this.normal.x *= magnitude;
  6749. this.normal.y *= magnitude;
  6750. this.normal.z *= magnitude;
  6751. this.d *= magnitude;
  6752. return this;
  6753. };
  6754. /**
  6755. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6756. */
  6757. Plane.prototype.transform = function (transformation) {
  6758. var transposedMatrix = Matrix.Transpose(transformation);
  6759. var x = this.normal.x;
  6760. var y = this.normal.y;
  6761. var z = this.normal.z;
  6762. var d = this.d;
  6763. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6764. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6765. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6766. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6767. return new Plane(normalX, normalY, normalZ, finalD);
  6768. };
  6769. /**
  6770. * Returns the dot product (float) of the point coordinates and the plane normal.
  6771. */
  6772. Plane.prototype.dotCoordinate = function (point) {
  6773. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6774. };
  6775. /**
  6776. * Updates the current Plane from the plane defined by the three given points.
  6777. * Returns the updated Plane.
  6778. */
  6779. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6780. var x1 = point2.x - point1.x;
  6781. var y1 = point2.y - point1.y;
  6782. var z1 = point2.z - point1.z;
  6783. var x2 = point3.x - point1.x;
  6784. var y2 = point3.y - point1.y;
  6785. var z2 = point3.z - point1.z;
  6786. var yz = (y1 * z2) - (z1 * y2);
  6787. var xz = (z1 * x2) - (x1 * z2);
  6788. var xy = (x1 * y2) - (y1 * x2);
  6789. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6790. var invPyth;
  6791. if (pyth !== 0) {
  6792. invPyth = 1.0 / pyth;
  6793. }
  6794. else {
  6795. invPyth = 0.0;
  6796. }
  6797. this.normal.x = yz * invPyth;
  6798. this.normal.y = xz * invPyth;
  6799. this.normal.z = xy * invPyth;
  6800. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6801. return this;
  6802. };
  6803. /**
  6804. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6805. */
  6806. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6807. var dot = Vector3.Dot(this.normal, direction);
  6808. return (dot <= epsilon);
  6809. };
  6810. /**
  6811. * Returns the signed distance (float) from the given point to the Plane.
  6812. */
  6813. Plane.prototype.signedDistanceTo = function (point) {
  6814. return Vector3.Dot(point, this.normal) + this.d;
  6815. };
  6816. // Statics
  6817. /**
  6818. * Returns a new Plane from the given array.
  6819. */
  6820. Plane.FromArray = function (array) {
  6821. return new Plane(array[0], array[1], array[2], array[3]);
  6822. };
  6823. /**
  6824. * Returns a new Plane defined by the three given points.
  6825. */
  6826. Plane.FromPoints = function (point1, point2, point3) {
  6827. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6828. result.copyFromPoints(point1, point2, point3);
  6829. return result;
  6830. };
  6831. /**
  6832. * Returns a new Plane the normal vector to this plane at the given origin point.
  6833. * Note : the vector "normal" is updated because normalized.
  6834. */
  6835. Plane.FromPositionAndNormal = function (origin, normal) {
  6836. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6837. normal.normalize();
  6838. result.normal = normal;
  6839. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6840. return result;
  6841. };
  6842. /**
  6843. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6844. */
  6845. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6846. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6847. return Vector3.Dot(point, normal) + d;
  6848. };
  6849. return Plane;
  6850. }());
  6851. BABYLON.Plane = Plane;
  6852. /**
  6853. * Class used to represent a viewport on screen
  6854. */
  6855. var Viewport = /** @class */ (function () {
  6856. /**
  6857. * Creates a Viewport object located at (x, y) and sized (width, height)
  6858. * @param x defines viewport left coordinate
  6859. * @param y defines viewport top coordinate
  6860. * @param width defines the viewport width
  6861. * @param height defines the viewport height
  6862. */
  6863. function Viewport(
  6864. /** viewport left coordinate */
  6865. x,
  6866. /** viewport top coordinate */
  6867. y,
  6868. /**viewport width */
  6869. width,
  6870. /** viewport height */
  6871. height) {
  6872. this.x = x;
  6873. this.y = y;
  6874. this.width = width;
  6875. this.height = height;
  6876. }
  6877. /**
  6878. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  6879. * @param renderWidthOrEngine defines either an engine or the rendering width
  6880. * @param renderHeight defines the rendering height
  6881. * @returns a new Viewport
  6882. */
  6883. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6884. if (renderWidthOrEngine.getRenderWidth) {
  6885. var engine = renderWidthOrEngine;
  6886. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6887. }
  6888. var renderWidth = renderWidthOrEngine;
  6889. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6890. };
  6891. /**
  6892. * Returns a new Viewport copied from the current one
  6893. * @returns a new Viewport
  6894. */
  6895. Viewport.prototype.clone = function () {
  6896. return new Viewport(this.x, this.y, this.width, this.height);
  6897. };
  6898. return Viewport;
  6899. }());
  6900. BABYLON.Viewport = Viewport;
  6901. var Frustum = /** @class */ (function () {
  6902. function Frustum() {
  6903. }
  6904. /**
  6905. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6906. */
  6907. Frustum.GetPlanes = function (transform) {
  6908. var frustumPlanes = [];
  6909. for (var index = 0; index < 6; index++) {
  6910. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6911. }
  6912. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6913. return frustumPlanes;
  6914. };
  6915. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6916. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6917. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6918. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6919. frustumPlane.d = transform.m[15] + transform.m[14];
  6920. frustumPlane.normalize();
  6921. };
  6922. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6923. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6924. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6925. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6926. frustumPlane.d = transform.m[15] - transform.m[14];
  6927. frustumPlane.normalize();
  6928. };
  6929. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6930. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6931. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6932. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6933. frustumPlane.d = transform.m[15] + transform.m[12];
  6934. frustumPlane.normalize();
  6935. };
  6936. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6937. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6938. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6939. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6940. frustumPlane.d = transform.m[15] - transform.m[12];
  6941. frustumPlane.normalize();
  6942. };
  6943. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6944. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6945. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6946. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6947. frustumPlane.d = transform.m[15] - transform.m[13];
  6948. frustumPlane.normalize();
  6949. };
  6950. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6951. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6952. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6953. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6954. frustumPlane.d = transform.m[15] + transform.m[13];
  6955. frustumPlane.normalize();
  6956. };
  6957. /**
  6958. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6959. */
  6960. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6961. // Near
  6962. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6963. // Far
  6964. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6965. // Left
  6966. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6967. // Right
  6968. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6969. // Top
  6970. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6971. // Bottom
  6972. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6973. };
  6974. return Frustum;
  6975. }());
  6976. BABYLON.Frustum = Frustum;
  6977. /** Defines supported spaces */
  6978. var Space;
  6979. (function (Space) {
  6980. /** Local (object) space */
  6981. Space[Space["LOCAL"] = 0] = "LOCAL";
  6982. /** World space */
  6983. Space[Space["WORLD"] = 1] = "WORLD";
  6984. /** Bone space */
  6985. Space[Space["BONE"] = 2] = "BONE";
  6986. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6987. /** Defines the 3 main axes */
  6988. var Axis = /** @class */ (function () {
  6989. function Axis() {
  6990. }
  6991. /** X axis */
  6992. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6993. /** Y axis */
  6994. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6995. /** Z axis */
  6996. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6997. return Axis;
  6998. }());
  6999. BABYLON.Axis = Axis;
  7000. ;
  7001. /** Class used to represent a Bezier curve */
  7002. var BezierCurve = /** @class */ (function () {
  7003. function BezierCurve() {
  7004. }
  7005. /**
  7006. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7007. * @param t defines the time
  7008. * @param x1 defines the left coordinate on X axis
  7009. * @param y1 defines the left coordinate on Y axis
  7010. * @param x2 defines the right coordinate on X axis
  7011. * @param y2 defines the right coordinate on Y axis
  7012. * @returns the interpolated value
  7013. */
  7014. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7015. // Extract X (which is equal to time here)
  7016. var f0 = 1 - 3 * x2 + 3 * x1;
  7017. var f1 = 3 * x2 - 6 * x1;
  7018. var f2 = 3 * x1;
  7019. var refinedT = t;
  7020. for (var i = 0; i < 5; i++) {
  7021. var refinedT2 = refinedT * refinedT;
  7022. var refinedT3 = refinedT2 * refinedT;
  7023. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7024. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7025. refinedT -= (x - t) * slope;
  7026. refinedT = Math.min(1, Math.max(0, refinedT));
  7027. }
  7028. // Resolve cubic bezier for the given x
  7029. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7030. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7031. Math.pow(refinedT, 3);
  7032. };
  7033. return BezierCurve;
  7034. }());
  7035. BABYLON.BezierCurve = BezierCurve;
  7036. /**
  7037. * Defines potential orientation for back face culling
  7038. */
  7039. var Orientation;
  7040. (function (Orientation) {
  7041. /**
  7042. * Clockwise
  7043. */
  7044. Orientation[Orientation["CW"] = 0] = "CW";
  7045. /** Counter clockwise */
  7046. Orientation[Orientation["CCW"] = 1] = "CCW";
  7047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7048. /**
  7049. * Defines angle representation
  7050. */
  7051. var Angle = /** @class */ (function () {
  7052. /**
  7053. * Creates an Angle object of "radians" radians (float).
  7054. */
  7055. function Angle(radians) {
  7056. this._radians = radians;
  7057. if (this._radians < 0.0)
  7058. this._radians += (2.0 * Math.PI);
  7059. }
  7060. /**
  7061. * Get value in degrees
  7062. * @returns the Angle value in degrees (float)
  7063. */
  7064. Angle.prototype.degrees = function () {
  7065. return this._radians * 180.0 / Math.PI;
  7066. };
  7067. /**
  7068. * Get value in radians
  7069. * @returns the Angle value in radians (float)
  7070. */
  7071. Angle.prototype.radians = function () {
  7072. return this._radians;
  7073. };
  7074. /**
  7075. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7076. * @param a defines first vector
  7077. * @param b defines second vector
  7078. * @returns a new Angle
  7079. */
  7080. Angle.BetweenTwoPoints = function (a, b) {
  7081. var delta = b.subtract(a);
  7082. var theta = Math.atan2(delta.y, delta.x);
  7083. return new Angle(theta);
  7084. };
  7085. /**
  7086. * Gets a new Angle object from the given float in radians
  7087. * @param radians defines the angle value in radians
  7088. * @returns a new Angle
  7089. */
  7090. Angle.FromRadians = function (radians) {
  7091. return new Angle(radians);
  7092. };
  7093. /**
  7094. * Gets a new Angle object from the given float in degrees
  7095. * @param degrees defines the angle value in degrees
  7096. * @returns a new Angle
  7097. */
  7098. Angle.FromDegrees = function (degrees) {
  7099. return new Angle(degrees * Math.PI / 180.0);
  7100. };
  7101. return Angle;
  7102. }());
  7103. BABYLON.Angle = Angle;
  7104. /**
  7105. * This represents an arc in a 2d space.
  7106. */
  7107. var Arc2 = /** @class */ (function () {
  7108. /**
  7109. * Creates an Arc object from the three given points : start, middle and end.
  7110. * @param startPoint Defines the start point of the arc
  7111. * @param midPoint Defines the midlle point of the arc
  7112. * @param endPoint Defines the end point of the arc
  7113. */
  7114. function Arc2(
  7115. /** Defines the start point of the arc */
  7116. startPoint,
  7117. /** Defines the mid point of the arc */
  7118. midPoint,
  7119. /** Defines the end point of the arc */
  7120. endPoint) {
  7121. this.startPoint = startPoint;
  7122. this.midPoint = midPoint;
  7123. this.endPoint = endPoint;
  7124. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7125. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7126. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7127. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7128. 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);
  7129. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7130. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7131. var a1 = this.startAngle.degrees();
  7132. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7133. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7134. // angles correction
  7135. if (a2 - a1 > +180.0)
  7136. a2 -= 360.0;
  7137. if (a2 - a1 < -180.0)
  7138. a2 += 360.0;
  7139. if (a3 - a2 > +180.0)
  7140. a3 -= 360.0;
  7141. if (a3 - a2 < -180.0)
  7142. a3 += 360.0;
  7143. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7144. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7145. }
  7146. return Arc2;
  7147. }());
  7148. BABYLON.Arc2 = Arc2;
  7149. var Path2 = /** @class */ (function () {
  7150. /**
  7151. * Creates a Path2 object from the starting 2D coordinates x and y.
  7152. */
  7153. function Path2(x, y) {
  7154. this._points = new Array();
  7155. this._length = 0.0;
  7156. this.closed = false;
  7157. this._points.push(new Vector2(x, y));
  7158. }
  7159. /**
  7160. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7161. * Returns the updated Path2.
  7162. */
  7163. Path2.prototype.addLineTo = function (x, y) {
  7164. if (this.closed) {
  7165. return this;
  7166. }
  7167. var newPoint = new Vector2(x, y);
  7168. var previousPoint = this._points[this._points.length - 1];
  7169. this._points.push(newPoint);
  7170. this._length += newPoint.subtract(previousPoint).length();
  7171. return this;
  7172. };
  7173. /**
  7174. * 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.
  7175. * Returns the updated Path2.
  7176. */
  7177. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7178. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7179. if (this.closed) {
  7180. return this;
  7181. }
  7182. var startPoint = this._points[this._points.length - 1];
  7183. var midPoint = new Vector2(midX, midY);
  7184. var endPoint = new Vector2(endX, endY);
  7185. var arc = new Arc2(startPoint, midPoint, endPoint);
  7186. var increment = arc.angle.radians() / numberOfSegments;
  7187. if (arc.orientation === Orientation.CW)
  7188. increment *= -1;
  7189. var currentAngle = arc.startAngle.radians() + increment;
  7190. for (var i = 0; i < numberOfSegments; i++) {
  7191. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7192. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7193. this.addLineTo(x, y);
  7194. currentAngle += increment;
  7195. }
  7196. return this;
  7197. };
  7198. /**
  7199. * Closes the Path2.
  7200. * Returns the Path2.
  7201. */
  7202. Path2.prototype.close = function () {
  7203. this.closed = true;
  7204. return this;
  7205. };
  7206. /**
  7207. * Returns the Path2 total length (float).
  7208. */
  7209. Path2.prototype.length = function () {
  7210. var result = this._length;
  7211. if (!this.closed) {
  7212. var lastPoint = this._points[this._points.length - 1];
  7213. var firstPoint = this._points[0];
  7214. result += (firstPoint.subtract(lastPoint).length());
  7215. }
  7216. return result;
  7217. };
  7218. /**
  7219. * Returns the Path2 internal array of points.
  7220. */
  7221. Path2.prototype.getPoints = function () {
  7222. return this._points;
  7223. };
  7224. /**
  7225. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7226. */
  7227. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7228. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7229. return Vector2.Zero();
  7230. }
  7231. var lengthPosition = normalizedLengthPosition * this.length();
  7232. var previousOffset = 0;
  7233. for (var i = 0; i < this._points.length; i++) {
  7234. var j = (i + 1) % this._points.length;
  7235. var a = this._points[i];
  7236. var b = this._points[j];
  7237. var bToA = b.subtract(a);
  7238. var nextOffset = (bToA.length() + previousOffset);
  7239. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7240. var dir = bToA.normalize();
  7241. var localOffset = lengthPosition - previousOffset;
  7242. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7243. }
  7244. previousOffset = nextOffset;
  7245. }
  7246. return Vector2.Zero();
  7247. };
  7248. /**
  7249. * Returns a new Path2 starting at the coordinates (x, y).
  7250. */
  7251. Path2.StartingAt = function (x, y) {
  7252. return new Path2(x, y);
  7253. };
  7254. return Path2;
  7255. }());
  7256. BABYLON.Path2 = Path2;
  7257. var Path3D = /** @class */ (function () {
  7258. /**
  7259. * new Path3D(path, normal, raw)
  7260. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7261. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7262. * path : an array of Vector3, the curve axis of the Path3D
  7263. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7264. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7265. */
  7266. function Path3D(path, firstNormal, raw) {
  7267. if (firstNormal === void 0) { firstNormal = null; }
  7268. this.path = path;
  7269. this._curve = new Array();
  7270. this._distances = new Array();
  7271. this._tangents = new Array();
  7272. this._normals = new Array();
  7273. this._binormals = new Array();
  7274. for (var p = 0; p < path.length; p++) {
  7275. this._curve[p] = path[p].clone(); // hard copy
  7276. }
  7277. this._raw = raw || false;
  7278. this._compute(firstNormal);
  7279. }
  7280. /**
  7281. * Returns the Path3D array of successive Vector3 designing its curve.
  7282. */
  7283. Path3D.prototype.getCurve = function () {
  7284. return this._curve;
  7285. };
  7286. /**
  7287. * Returns an array populated with tangent vectors on each Path3D curve point.
  7288. */
  7289. Path3D.prototype.getTangents = function () {
  7290. return this._tangents;
  7291. };
  7292. /**
  7293. * Returns an array populated with normal vectors on each Path3D curve point.
  7294. */
  7295. Path3D.prototype.getNormals = function () {
  7296. return this._normals;
  7297. };
  7298. /**
  7299. * Returns an array populated with binormal vectors on each Path3D curve point.
  7300. */
  7301. Path3D.prototype.getBinormals = function () {
  7302. return this._binormals;
  7303. };
  7304. /**
  7305. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7306. */
  7307. Path3D.prototype.getDistances = function () {
  7308. return this._distances;
  7309. };
  7310. /**
  7311. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7312. * Returns the same object updated.
  7313. */
  7314. Path3D.prototype.update = function (path, firstNormal) {
  7315. if (firstNormal === void 0) { firstNormal = null; }
  7316. for (var p = 0; p < path.length; p++) {
  7317. this._curve[p].x = path[p].x;
  7318. this._curve[p].y = path[p].y;
  7319. this._curve[p].z = path[p].z;
  7320. }
  7321. this._compute(firstNormal);
  7322. return this;
  7323. };
  7324. // private function compute() : computes tangents, normals and binormals
  7325. Path3D.prototype._compute = function (firstNormal) {
  7326. var l = this._curve.length;
  7327. // first and last tangents
  7328. this._tangents[0] = this._getFirstNonNullVector(0);
  7329. if (!this._raw) {
  7330. this._tangents[0].normalize();
  7331. }
  7332. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7333. if (!this._raw) {
  7334. this._tangents[l - 1].normalize();
  7335. }
  7336. // normals and binormals at first point : arbitrary vector with _normalVector()
  7337. var tg0 = this._tangents[0];
  7338. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7339. this._normals[0] = pp0;
  7340. if (!this._raw) {
  7341. this._normals[0].normalize();
  7342. }
  7343. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7344. if (!this._raw) {
  7345. this._binormals[0].normalize();
  7346. }
  7347. this._distances[0] = 0.0;
  7348. // normals and binormals : next points
  7349. var prev; // previous vector (segment)
  7350. var cur; // current vector (segment)
  7351. var curTang; // current tangent
  7352. // previous normal
  7353. var prevBinor; // previous binormal
  7354. for (var i = 1; i < l; i++) {
  7355. // tangents
  7356. prev = this._getLastNonNullVector(i);
  7357. if (i < l - 1) {
  7358. cur = this._getFirstNonNullVector(i);
  7359. this._tangents[i] = prev.add(cur);
  7360. this._tangents[i].normalize();
  7361. }
  7362. this._distances[i] = this._distances[i - 1] + prev.length();
  7363. // normals and binormals
  7364. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7365. curTang = this._tangents[i];
  7366. prevBinor = this._binormals[i - 1];
  7367. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7368. if (!this._raw) {
  7369. this._normals[i].normalize();
  7370. }
  7371. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7372. if (!this._raw) {
  7373. this._binormals[i].normalize();
  7374. }
  7375. }
  7376. };
  7377. // private function getFirstNonNullVector(index)
  7378. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7379. Path3D.prototype._getFirstNonNullVector = function (index) {
  7380. var i = 1;
  7381. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7382. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7383. i++;
  7384. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7385. }
  7386. return nNVector;
  7387. };
  7388. // private function getLastNonNullVector(index)
  7389. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7390. Path3D.prototype._getLastNonNullVector = function (index) {
  7391. var i = 1;
  7392. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7393. while (nLVector.length() === 0 && index > i + 1) {
  7394. i++;
  7395. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7396. }
  7397. return nLVector;
  7398. };
  7399. // private function normalVector(v0, vt, va) :
  7400. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7401. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7402. Path3D.prototype._normalVector = function (v0, vt, va) {
  7403. var normal0;
  7404. var tgl = vt.length();
  7405. if (tgl === 0.0) {
  7406. tgl = 1.0;
  7407. }
  7408. if (va === undefined || va === null) {
  7409. var point;
  7410. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7411. point = new Vector3(0.0, -1.0, 0.0);
  7412. }
  7413. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7414. point = new Vector3(1.0, 0.0, 0.0);
  7415. }
  7416. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7417. point = new Vector3(0.0, 0.0, 1.0);
  7418. }
  7419. else {
  7420. point = Vector3.Zero();
  7421. }
  7422. normal0 = Vector3.Cross(vt, point);
  7423. }
  7424. else {
  7425. normal0 = Vector3.Cross(vt, va);
  7426. Vector3.CrossToRef(normal0, vt, normal0);
  7427. }
  7428. normal0.normalize();
  7429. return normal0;
  7430. };
  7431. return Path3D;
  7432. }());
  7433. BABYLON.Path3D = Path3D;
  7434. var Curve3 = /** @class */ (function () {
  7435. /**
  7436. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7437. * A Curve3 is designed from a series of successive Vector3.
  7438. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7439. */
  7440. function Curve3(points) {
  7441. this._length = 0.0;
  7442. this._points = points;
  7443. this._length = this._computeLength(points);
  7444. }
  7445. /**
  7446. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7447. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7448. * @param v1 (Vector3) the control point
  7449. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7450. * @param nbPoints (integer) the wanted number of points in the curve
  7451. */
  7452. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7453. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7454. var bez = new Array();
  7455. var equation = function (t, val0, val1, val2) {
  7456. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7457. return res;
  7458. };
  7459. for (var i = 0; i <= nbPoints; i++) {
  7460. 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)));
  7461. }
  7462. return new Curve3(bez);
  7463. };
  7464. /**
  7465. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7466. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7467. * @param v1 (Vector3) the first control point
  7468. * @param v2 (Vector3) the second control point
  7469. * @param v3 (Vector3) the end point of the Cubic Bezier
  7470. * @param nbPoints (integer) the wanted number of points in the curve
  7471. */
  7472. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7473. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7474. var bez = new Array();
  7475. var equation = function (t, val0, val1, val2, val3) {
  7476. 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;
  7477. return res;
  7478. };
  7479. for (var i = 0; i <= nbPoints; i++) {
  7480. 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)));
  7481. }
  7482. return new Curve3(bez);
  7483. };
  7484. /**
  7485. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7486. * @param p1 (Vector3) the origin point of the Hermite Spline
  7487. * @param t1 (Vector3) the tangent vector at the origin point
  7488. * @param p2 (Vector3) the end point of the Hermite Spline
  7489. * @param t2 (Vector3) the tangent vector at the end point
  7490. * @param nbPoints (integer) the wanted number of points in the curve
  7491. */
  7492. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7493. var hermite = new Array();
  7494. var step = 1.0 / nbPoints;
  7495. for (var i = 0; i <= nbPoints; i++) {
  7496. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7497. }
  7498. return new Curve3(hermite);
  7499. };
  7500. /**
  7501. * Returns a Curve3 object along a CatmullRom Spline curve :
  7502. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7503. * @param nbPoints (integer) the wanted number of points between each curve control points
  7504. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7505. */
  7506. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7507. var catmullRom = new Array();
  7508. var step = 1.0 / nbPoints;
  7509. var amount = 0.0;
  7510. if (closed) {
  7511. var pointsCount = points.length;
  7512. for (var i = 0; i < pointsCount; i++) {
  7513. amount = 0;
  7514. for (var c = 0; c < nbPoints; c++) {
  7515. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7516. amount += step;
  7517. }
  7518. }
  7519. catmullRom.push(catmullRom[0]);
  7520. }
  7521. else {
  7522. var totalPoints = new Array();
  7523. totalPoints.push(points[0].clone());
  7524. Array.prototype.push.apply(totalPoints, points);
  7525. totalPoints.push(points[points.length - 1].clone());
  7526. for (var i = 0; i < totalPoints.length - 3; i++) {
  7527. amount = 0;
  7528. for (var c = 0; c < nbPoints; c++) {
  7529. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7530. amount += step;
  7531. }
  7532. }
  7533. i--;
  7534. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7535. }
  7536. return new Curve3(catmullRom);
  7537. };
  7538. /**
  7539. * Returns the Curve3 stored array of successive Vector3
  7540. */
  7541. Curve3.prototype.getPoints = function () {
  7542. return this._points;
  7543. };
  7544. /**
  7545. * Returns the computed length (float) of the curve.
  7546. */
  7547. Curve3.prototype.length = function () {
  7548. return this._length;
  7549. };
  7550. /**
  7551. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7552. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7553. * curveA and curveB keep unchanged.
  7554. */
  7555. Curve3.prototype.continue = function (curve) {
  7556. var lastPoint = this._points[this._points.length - 1];
  7557. var continuedPoints = this._points.slice();
  7558. var curvePoints = curve.getPoints();
  7559. for (var i = 1; i < curvePoints.length; i++) {
  7560. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7561. }
  7562. var continuedCurve = new Curve3(continuedPoints);
  7563. return continuedCurve;
  7564. };
  7565. Curve3.prototype._computeLength = function (path) {
  7566. var l = 0;
  7567. for (var i = 1; i < path.length; i++) {
  7568. l += (path[i].subtract(path[i - 1])).length();
  7569. }
  7570. return l;
  7571. };
  7572. return Curve3;
  7573. }());
  7574. BABYLON.Curve3 = Curve3;
  7575. // Vertex formats
  7576. var PositionNormalVertex = /** @class */ (function () {
  7577. function PositionNormalVertex(position, normal) {
  7578. if (position === void 0) { position = Vector3.Zero(); }
  7579. if (normal === void 0) { normal = Vector3.Up(); }
  7580. this.position = position;
  7581. this.normal = normal;
  7582. }
  7583. PositionNormalVertex.prototype.clone = function () {
  7584. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7585. };
  7586. return PositionNormalVertex;
  7587. }());
  7588. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7589. var PositionNormalTextureVertex = /** @class */ (function () {
  7590. function PositionNormalTextureVertex(position, normal, uv) {
  7591. if (position === void 0) { position = Vector3.Zero(); }
  7592. if (normal === void 0) { normal = Vector3.Up(); }
  7593. if (uv === void 0) { uv = Vector2.Zero(); }
  7594. this.position = position;
  7595. this.normal = normal;
  7596. this.uv = uv;
  7597. }
  7598. PositionNormalTextureVertex.prototype.clone = function () {
  7599. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7600. };
  7601. return PositionNormalTextureVertex;
  7602. }());
  7603. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7604. // Temporary pre-allocated objects for engine internal use
  7605. // usage in any internal function :
  7606. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7607. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7608. var Tmp = /** @class */ (function () {
  7609. function Tmp() {
  7610. }
  7611. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7612. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7613. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7614. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7615. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7616. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7617. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7618. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7619. Matrix.Zero(), Matrix.Zero(),
  7620. Matrix.Zero(), Matrix.Zero(),
  7621. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7622. return Tmp;
  7623. }());
  7624. BABYLON.Tmp = Tmp;
  7625. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7626. var MathTmp = /** @class */ (function () {
  7627. function MathTmp() {
  7628. }
  7629. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7630. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7631. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7632. return MathTmp;
  7633. }());
  7634. })(BABYLON || (BABYLON = {}));
  7635. //# sourceMappingURL=babylon.math.js.map
  7636. var BABYLON;
  7637. (function (BABYLON) {
  7638. var Scalar = /** @class */ (function () {
  7639. function Scalar() {
  7640. }
  7641. /**
  7642. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7643. */
  7644. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7645. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7646. var num = a - b;
  7647. return -epsilon <= num && num <= epsilon;
  7648. };
  7649. /**
  7650. * Returns a string : the upper case translation of the number i to hexadecimal.
  7651. */
  7652. Scalar.ToHex = function (i) {
  7653. var str = i.toString(16);
  7654. if (i <= 15) {
  7655. return ("0" + str).toUpperCase();
  7656. }
  7657. return str.toUpperCase();
  7658. };
  7659. /**
  7660. * Returns -1 if value is negative and +1 is value is positive.
  7661. * Returns the value itself if it's equal to zero.
  7662. */
  7663. Scalar.Sign = function (value) {
  7664. value = +value; // convert to a number
  7665. if (value === 0 || isNaN(value))
  7666. return value;
  7667. return value > 0 ? 1 : -1;
  7668. };
  7669. /**
  7670. * Returns the value itself if it's between min and max.
  7671. * Returns min if the value is lower than min.
  7672. * Returns max if the value is greater than max.
  7673. */
  7674. Scalar.Clamp = function (value, min, max) {
  7675. if (min === void 0) { min = 0; }
  7676. if (max === void 0) { max = 1; }
  7677. return Math.min(max, Math.max(min, value));
  7678. };
  7679. /**
  7680. * Returns the log2 of value.
  7681. */
  7682. Scalar.Log2 = function (value) {
  7683. return Math.log(value) * Math.LOG2E;
  7684. };
  7685. /**
  7686. * Loops the value, so that it is never larger than length and never smaller than 0.
  7687. *
  7688. * This is similar to the modulo operator but it works with floating point numbers.
  7689. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7690. * With t = 5 and length = 2.5, the result would be 0.0.
  7691. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7692. */
  7693. Scalar.Repeat = function (value, length) {
  7694. return value - Math.floor(value / length) * length;
  7695. };
  7696. /**
  7697. * Normalize the value between 0.0 and 1.0 using min and max values
  7698. */
  7699. Scalar.Normalize = function (value, min, max) {
  7700. return (value - min) / (max - min);
  7701. };
  7702. /**
  7703. * Denormalize the value from 0.0 and 1.0 using min and max values
  7704. */
  7705. Scalar.Denormalize = function (normalized, min, max) {
  7706. return (normalized * (max - min) + min);
  7707. };
  7708. /**
  7709. * Calculates the shortest difference between two given angles given in degrees.
  7710. */
  7711. Scalar.DeltaAngle = function (current, target) {
  7712. var num = Scalar.Repeat(target - current, 360.0);
  7713. if (num > 180.0) {
  7714. num -= 360.0;
  7715. }
  7716. return num;
  7717. };
  7718. /**
  7719. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7720. *
  7721. * The returned value will move back and forth between 0 and length
  7722. */
  7723. Scalar.PingPong = function (tx, length) {
  7724. var t = Scalar.Repeat(tx, length * 2.0);
  7725. return length - Math.abs(t - length);
  7726. };
  7727. /**
  7728. * Interpolates between min and max with smoothing at the limits.
  7729. *
  7730. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7731. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7732. */
  7733. Scalar.SmoothStep = function (from, to, tx) {
  7734. var t = Scalar.Clamp(tx);
  7735. t = -2.0 * t * t * t + 3.0 * t * t;
  7736. return to * t + from * (1.0 - t);
  7737. };
  7738. /**
  7739. * Moves a value current towards target.
  7740. *
  7741. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7742. * Negative values of maxDelta pushes the value away from target.
  7743. */
  7744. Scalar.MoveTowards = function (current, target, maxDelta) {
  7745. var result = 0;
  7746. if (Math.abs(target - current) <= maxDelta) {
  7747. result = target;
  7748. }
  7749. else {
  7750. result = current + Scalar.Sign(target - current) * maxDelta;
  7751. }
  7752. return result;
  7753. };
  7754. /**
  7755. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7756. *
  7757. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7758. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7759. */
  7760. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7761. var num = Scalar.DeltaAngle(current, target);
  7762. var result = 0;
  7763. if (-maxDelta < num && num < maxDelta) {
  7764. result = target;
  7765. }
  7766. else {
  7767. target = current + num;
  7768. result = Scalar.MoveTowards(current, target, maxDelta);
  7769. }
  7770. return result;
  7771. };
  7772. /**
  7773. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7774. */
  7775. Scalar.Lerp = function (start, end, amount) {
  7776. return start + ((end - start) * amount);
  7777. };
  7778. /**
  7779. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7780. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7781. */
  7782. Scalar.LerpAngle = function (start, end, amount) {
  7783. var num = Scalar.Repeat(end - start, 360.0);
  7784. if (num > 180.0) {
  7785. num -= 360.0;
  7786. }
  7787. return start + num * Scalar.Clamp(amount);
  7788. };
  7789. /**
  7790. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7791. */
  7792. Scalar.InverseLerp = function (a, b, value) {
  7793. var result = 0;
  7794. if (a != b) {
  7795. result = Scalar.Clamp((value - a) / (b - a));
  7796. }
  7797. else {
  7798. result = 0.0;
  7799. }
  7800. return result;
  7801. };
  7802. /**
  7803. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7804. */
  7805. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7806. var squared = amount * amount;
  7807. var cubed = amount * squared;
  7808. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7809. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7810. var part3 = (cubed - (2.0 * squared)) + amount;
  7811. var part4 = cubed - squared;
  7812. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7813. };
  7814. /**
  7815. * Returns a random float number between and min and max values
  7816. */
  7817. Scalar.RandomRange = function (min, max) {
  7818. if (min === max)
  7819. return min;
  7820. return ((Math.random() * (max - min)) + min);
  7821. };
  7822. /**
  7823. * This function returns percentage of a number in a given range.
  7824. *
  7825. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7826. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7827. */
  7828. Scalar.RangeToPercent = function (number, min, max) {
  7829. return ((number - min) / (max - min));
  7830. };
  7831. /**
  7832. * This function returns number that corresponds to the percentage in a given range.
  7833. *
  7834. * PercentToRange(0.34,0,100) will return 34.
  7835. */
  7836. Scalar.PercentToRange = function (percent, min, max) {
  7837. return ((max - min) * percent + min);
  7838. };
  7839. /**
  7840. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7841. * @param angle The angle to normalize in radian.
  7842. * @return The converted angle.
  7843. */
  7844. Scalar.NormalizeRadians = function (angle) {
  7845. // More precise but slower version kept for reference.
  7846. // angle = angle % Tools.TwoPi;
  7847. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7848. //if (angle > Math.PI) {
  7849. // angle -= Tools.TwoPi;
  7850. //}
  7851. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7852. return angle;
  7853. };
  7854. /**
  7855. * Two pi constants convenient for computation.
  7856. */
  7857. Scalar.TwoPi = Math.PI * 2;
  7858. return Scalar;
  7859. }());
  7860. BABYLON.Scalar = Scalar;
  7861. })(BABYLON || (BABYLON = {}));
  7862. //# sourceMappingURL=babylon.math.scalar.js.map
  7863. //# sourceMappingURL=babylon.mixins.js.map
  7864. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7865. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7866. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7867. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7868. //# sourceMappingURL=babylon.webgl2.js.map
  7869. var BABYLON;
  7870. (function (BABYLON) {
  7871. var __decoratorInitialStore = {};
  7872. var __mergedStore = {};
  7873. var _copySource = function (creationFunction, source, instanciate) {
  7874. var destination = creationFunction();
  7875. // Tags
  7876. if (BABYLON.Tags) {
  7877. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7878. }
  7879. var classStore = getMergedStore(destination);
  7880. // Properties
  7881. for (var property in classStore) {
  7882. var propertyDescriptor = classStore[property];
  7883. var sourceProperty = source[property];
  7884. var propertyType = propertyDescriptor.type;
  7885. if (sourceProperty !== undefined && sourceProperty !== null) {
  7886. switch (propertyType) {
  7887. case 0: // Value
  7888. case 6: // Mesh reference
  7889. case 11: // Camera reference
  7890. destination[property] = sourceProperty;
  7891. break;
  7892. case 1: // Texture
  7893. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7894. break;
  7895. case 2: // Color3
  7896. case 3: // FresnelParameters
  7897. case 4: // Vector2
  7898. case 5: // Vector3
  7899. case 7: // Color Curves
  7900. case 10: // Quaternion
  7901. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7902. break;
  7903. }
  7904. }
  7905. }
  7906. return destination;
  7907. };
  7908. function getDirectStore(target) {
  7909. var classKey = target.getClassName();
  7910. if (!__decoratorInitialStore[classKey]) {
  7911. __decoratorInitialStore[classKey] = {};
  7912. }
  7913. return __decoratorInitialStore[classKey];
  7914. }
  7915. /**
  7916. * Return the list of properties flagged as serializable
  7917. * @param target: host object
  7918. */
  7919. function getMergedStore(target) {
  7920. var classKey = target.getClassName();
  7921. if (__mergedStore[classKey]) {
  7922. return __mergedStore[classKey];
  7923. }
  7924. __mergedStore[classKey] = {};
  7925. var store = __mergedStore[classKey];
  7926. var currentTarget = target;
  7927. var currentKey = classKey;
  7928. while (currentKey) {
  7929. var initialStore = __decoratorInitialStore[currentKey];
  7930. for (var property in initialStore) {
  7931. store[property] = initialStore[property];
  7932. }
  7933. var parent_1 = void 0;
  7934. var done = false;
  7935. do {
  7936. parent_1 = Object.getPrototypeOf(currentTarget);
  7937. if (!parent_1.getClassName) {
  7938. done = true;
  7939. break;
  7940. }
  7941. if (parent_1.getClassName() !== currentKey) {
  7942. break;
  7943. }
  7944. currentTarget = parent_1;
  7945. } while (parent_1);
  7946. if (done) {
  7947. break;
  7948. }
  7949. currentKey = parent_1.getClassName();
  7950. currentTarget = parent_1;
  7951. }
  7952. return store;
  7953. }
  7954. function generateSerializableMember(type, sourceName) {
  7955. return function (target, propertyKey) {
  7956. var classStore = getDirectStore(target);
  7957. if (!classStore[propertyKey]) {
  7958. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7959. }
  7960. };
  7961. }
  7962. function generateExpandMember(setCallback, targetKey) {
  7963. if (targetKey === void 0) { targetKey = null; }
  7964. return function (target, propertyKey) {
  7965. var key = targetKey || ("_" + propertyKey);
  7966. Object.defineProperty(target, propertyKey, {
  7967. get: function () {
  7968. return this[key];
  7969. },
  7970. set: function (value) {
  7971. if (this[key] === value) {
  7972. return;
  7973. }
  7974. this[key] = value;
  7975. target[setCallback].apply(this);
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. };
  7981. }
  7982. function expandToProperty(callback, targetKey) {
  7983. if (targetKey === void 0) { targetKey = null; }
  7984. return generateExpandMember(callback, targetKey);
  7985. }
  7986. BABYLON.expandToProperty = expandToProperty;
  7987. function serialize(sourceName) {
  7988. return generateSerializableMember(0, sourceName); // value member
  7989. }
  7990. BABYLON.serialize = serialize;
  7991. function serializeAsTexture(sourceName) {
  7992. return generateSerializableMember(1, sourceName); // texture member
  7993. }
  7994. BABYLON.serializeAsTexture = serializeAsTexture;
  7995. function serializeAsColor3(sourceName) {
  7996. return generateSerializableMember(2, sourceName); // color3 member
  7997. }
  7998. BABYLON.serializeAsColor3 = serializeAsColor3;
  7999. function serializeAsFresnelParameters(sourceName) {
  8000. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8001. }
  8002. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8003. function serializeAsVector2(sourceName) {
  8004. return generateSerializableMember(4, sourceName); // vector2 member
  8005. }
  8006. BABYLON.serializeAsVector2 = serializeAsVector2;
  8007. function serializeAsVector3(sourceName) {
  8008. return generateSerializableMember(5, sourceName); // vector3 member
  8009. }
  8010. BABYLON.serializeAsVector3 = serializeAsVector3;
  8011. function serializeAsMeshReference(sourceName) {
  8012. return generateSerializableMember(6, sourceName); // mesh reference member
  8013. }
  8014. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8015. function serializeAsColorCurves(sourceName) {
  8016. return generateSerializableMember(7, sourceName); // color curves
  8017. }
  8018. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8019. function serializeAsColor4(sourceName) {
  8020. return generateSerializableMember(8, sourceName); // color 4
  8021. }
  8022. BABYLON.serializeAsColor4 = serializeAsColor4;
  8023. function serializeAsImageProcessingConfiguration(sourceName) {
  8024. return generateSerializableMember(9, sourceName); // image processing
  8025. }
  8026. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8027. function serializeAsQuaternion(sourceName) {
  8028. return generateSerializableMember(10, sourceName); // quaternion member
  8029. }
  8030. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8031. /**
  8032. * Decorator used to define property that can be serialized as reference to a camera
  8033. * @param sourceName defines the name of the property to decorate
  8034. */
  8035. function serializeAsCameraReference(sourceName) {
  8036. return generateSerializableMember(11, sourceName); // camera reference member
  8037. }
  8038. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8039. var SerializationHelper = /** @class */ (function () {
  8040. function SerializationHelper() {
  8041. }
  8042. SerializationHelper.Serialize = function (entity, serializationObject) {
  8043. if (!serializationObject) {
  8044. serializationObject = {};
  8045. }
  8046. // Tags
  8047. if (BABYLON.Tags) {
  8048. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8049. }
  8050. var serializedProperties = getMergedStore(entity);
  8051. // Properties
  8052. for (var property in serializedProperties) {
  8053. var propertyDescriptor = serializedProperties[property];
  8054. var targetPropertyName = propertyDescriptor.sourceName || property;
  8055. var propertyType = propertyDescriptor.type;
  8056. var sourceProperty = entity[property];
  8057. if (sourceProperty !== undefined && sourceProperty !== null) {
  8058. switch (propertyType) {
  8059. case 0: // Value
  8060. serializationObject[targetPropertyName] = sourceProperty;
  8061. break;
  8062. case 1: // Texture
  8063. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8064. break;
  8065. case 2: // Color3
  8066. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8067. break;
  8068. case 3: // FresnelParameters
  8069. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8070. break;
  8071. case 4: // Vector2
  8072. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8073. break;
  8074. case 5: // Vector3
  8075. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8076. break;
  8077. case 6: // Mesh reference
  8078. serializationObject[targetPropertyName] = sourceProperty.id;
  8079. break;
  8080. case 7: // Color Curves
  8081. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8082. break;
  8083. case 8: // Color 4
  8084. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8085. break;
  8086. case 9: // Image Processing
  8087. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8088. break;
  8089. case 10: // Quaternion
  8090. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8091. break;
  8092. case 11: // Camera reference
  8093. serializationObject[targetPropertyName] = sourceProperty.id;
  8094. break;
  8095. }
  8096. }
  8097. }
  8098. return serializationObject;
  8099. };
  8100. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8101. if (rootUrl === void 0) { rootUrl = null; }
  8102. var destination = creationFunction();
  8103. if (!rootUrl) {
  8104. rootUrl = "";
  8105. }
  8106. // Tags
  8107. if (BABYLON.Tags) {
  8108. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8109. }
  8110. var classStore = getMergedStore(destination);
  8111. // Properties
  8112. for (var property in classStore) {
  8113. var propertyDescriptor = classStore[property];
  8114. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8115. var propertyType = propertyDescriptor.type;
  8116. if (sourceProperty !== undefined && sourceProperty !== null) {
  8117. var dest = destination;
  8118. switch (propertyType) {
  8119. case 0: // Value
  8120. dest[property] = sourceProperty;
  8121. break;
  8122. case 1: // Texture
  8123. if (scene) {
  8124. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8125. }
  8126. break;
  8127. case 2: // Color3
  8128. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8129. break;
  8130. case 3: // FresnelParameters
  8131. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8132. break;
  8133. case 4: // Vector2
  8134. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8135. break;
  8136. case 5: // Vector3
  8137. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8138. break;
  8139. case 6: // Mesh reference
  8140. if (scene) {
  8141. dest[property] = scene.getLastMeshByID(sourceProperty);
  8142. }
  8143. break;
  8144. case 7: // Color Curves
  8145. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8146. break;
  8147. case 8: // Color 4
  8148. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8149. break;
  8150. case 9: // Image Processing
  8151. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8152. break;
  8153. case 10: // Quaternion
  8154. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8155. break;
  8156. case 11: // Camera reference
  8157. if (scene) {
  8158. dest[property] = scene.getCameraByID(sourceProperty);
  8159. }
  8160. break;
  8161. }
  8162. }
  8163. }
  8164. return destination;
  8165. };
  8166. SerializationHelper.Clone = function (creationFunction, source) {
  8167. return _copySource(creationFunction, source, false);
  8168. };
  8169. SerializationHelper.Instanciate = function (creationFunction, source) {
  8170. return _copySource(creationFunction, source, true);
  8171. };
  8172. return SerializationHelper;
  8173. }());
  8174. BABYLON.SerializationHelper = SerializationHelper;
  8175. })(BABYLON || (BABYLON = {}));
  8176. //# sourceMappingURL=babylon.decorators.js.map
  8177. var BABYLON;
  8178. (function (BABYLON) {
  8179. /**
  8180. * Wrapper class for promise with external resolve and reject.
  8181. */
  8182. var Deferred = /** @class */ (function () {
  8183. /**
  8184. * Constructor for this deferred object.
  8185. */
  8186. function Deferred() {
  8187. var _this = this;
  8188. this.promise = new Promise(function (resolve, reject) {
  8189. _this._resolve = resolve;
  8190. _this._reject = reject;
  8191. });
  8192. }
  8193. Object.defineProperty(Deferred.prototype, "resolve", {
  8194. /**
  8195. * The resolve method of the promise associated with this deferred object.
  8196. */
  8197. get: function () {
  8198. return this._resolve;
  8199. },
  8200. enumerable: true,
  8201. configurable: true
  8202. });
  8203. Object.defineProperty(Deferred.prototype, "reject", {
  8204. /**
  8205. * The reject method of the promise associated with this deferred object.
  8206. */
  8207. get: function () {
  8208. return this._reject;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. return Deferred;
  8214. }());
  8215. BABYLON.Deferred = Deferred;
  8216. })(BABYLON || (BABYLON = {}));
  8217. //# sourceMappingURL=babylon.deferred.js.map
  8218. var BABYLON;
  8219. (function (BABYLON) {
  8220. /**
  8221. * A class serves as a medium between the observable and its observers
  8222. */
  8223. var EventState = /** @class */ (function () {
  8224. /**
  8225. * Create a new EventState
  8226. * @param mask defines the mask associated with this state
  8227. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8228. * @param target defines the original target of the state
  8229. * @param currentTarget defines the current target of the state
  8230. */
  8231. function EventState(mask, skipNextObservers, target, currentTarget) {
  8232. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8233. this.initalize(mask, skipNextObservers, target, currentTarget);
  8234. }
  8235. /**
  8236. * Initialize the current event state
  8237. * @param mask defines the mask associated with this state
  8238. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8239. * @param target defines the original target of the state
  8240. * @param currentTarget defines the current target of the state
  8241. * @returns the current event state
  8242. */
  8243. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8244. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8245. this.mask = mask;
  8246. this.skipNextObservers = skipNextObservers;
  8247. this.target = target;
  8248. this.currentTarget = currentTarget;
  8249. return this;
  8250. };
  8251. return EventState;
  8252. }());
  8253. BABYLON.EventState = EventState;
  8254. /**
  8255. * Represent an Observer registered to a given Observable object.
  8256. */
  8257. var Observer = /** @class */ (function () {
  8258. /**
  8259. * Creates a new observer
  8260. * @param callback defines the callback to call when the observer is notified
  8261. * @param mask defines the mask of the observer (used to filter notifications)
  8262. * @param scope defines the current scope used to restore the JS context
  8263. */
  8264. function Observer(
  8265. /**
  8266. * Defines the callback to call when the observer is notified
  8267. */
  8268. callback,
  8269. /**
  8270. * Defines the mask of the observer (used to filter notifications)
  8271. */
  8272. mask,
  8273. /**
  8274. * Defines the current scope used to restore the JS context
  8275. */
  8276. scope) {
  8277. if (scope === void 0) { scope = null; }
  8278. this.callback = callback;
  8279. this.mask = mask;
  8280. this.scope = scope;
  8281. /** @hidden */
  8282. this._willBeUnregistered = false;
  8283. /**
  8284. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8285. */
  8286. this.unregisterOnNextCall = false;
  8287. }
  8288. return Observer;
  8289. }());
  8290. BABYLON.Observer = Observer;
  8291. /**
  8292. * Represent a list of observers registered to multiple Observables object.
  8293. */
  8294. var MultiObserver = /** @class */ (function () {
  8295. function MultiObserver() {
  8296. }
  8297. /**
  8298. * Release associated resources
  8299. */
  8300. MultiObserver.prototype.dispose = function () {
  8301. if (this._observers && this._observables) {
  8302. for (var index = 0; index < this._observers.length; index++) {
  8303. this._observables[index].remove(this._observers[index]);
  8304. }
  8305. }
  8306. this._observers = null;
  8307. this._observables = null;
  8308. };
  8309. /**
  8310. * Raise a callback when one of the observable will notify
  8311. * @param observables defines a list of observables to watch
  8312. * @param callback defines the callback to call on notification
  8313. * @param mask defines the mask used to filter notifications
  8314. * @param scope defines the current scope used to restore the JS context
  8315. * @returns the new MultiObserver
  8316. */
  8317. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8318. if (mask === void 0) { mask = -1; }
  8319. if (scope === void 0) { scope = null; }
  8320. var result = new MultiObserver();
  8321. result._observers = new Array();
  8322. result._observables = observables;
  8323. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8324. var observable = observables_1[_i];
  8325. var observer = observable.add(callback, mask, false, scope);
  8326. if (observer) {
  8327. result._observers.push(observer);
  8328. }
  8329. }
  8330. return result;
  8331. };
  8332. return MultiObserver;
  8333. }());
  8334. BABYLON.MultiObserver = MultiObserver;
  8335. /**
  8336. * The Observable class is a simple implementation of the Observable pattern.
  8337. *
  8338. * 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.
  8339. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8340. * 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).
  8341. * 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.
  8342. */
  8343. var Observable = /** @class */ (function () {
  8344. /**
  8345. * Creates a new observable
  8346. * @param onObserverAdded defines a callback to call when a new observer is added
  8347. */
  8348. function Observable(onObserverAdded) {
  8349. this._observers = new Array();
  8350. this._eventState = new EventState(0);
  8351. if (onObserverAdded) {
  8352. this._onObserverAdded = onObserverAdded;
  8353. }
  8354. }
  8355. /**
  8356. * Create a new Observer with the specified callback
  8357. * @param callback the callback that will be executed for that Observer
  8358. * @param mask the mask used to filter observers
  8359. * @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.
  8360. * @param scope optional scope for the callback to be called from
  8361. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8362. * @returns the new observer created for the callback
  8363. */
  8364. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8365. if (mask === void 0) { mask = -1; }
  8366. if (insertFirst === void 0) { insertFirst = false; }
  8367. if (scope === void 0) { scope = null; }
  8368. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8369. if (!callback) {
  8370. return null;
  8371. }
  8372. var observer = new Observer(callback, mask, scope);
  8373. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8374. if (insertFirst) {
  8375. this._observers.unshift(observer);
  8376. }
  8377. else {
  8378. this._observers.push(observer);
  8379. }
  8380. if (this._onObserverAdded) {
  8381. this._onObserverAdded(observer);
  8382. }
  8383. return observer;
  8384. };
  8385. /**
  8386. * Create a new Observer with the specified callback and unregisters after the next notification
  8387. * @param callback the callback that will be executed for that Observer
  8388. * @returns the new observer created for the callback
  8389. */
  8390. Observable.prototype.addOnce = function (callback) {
  8391. return this.add(callback, undefined, undefined, undefined, true);
  8392. };
  8393. /**
  8394. * Remove an Observer from the Observable object
  8395. * @param observer the instance of the Observer to remove
  8396. * @returns false if it doesn't belong to this Observable
  8397. */
  8398. Observable.prototype.remove = function (observer) {
  8399. if (!observer) {
  8400. return false;
  8401. }
  8402. var index = this._observers.indexOf(observer);
  8403. if (index !== -1) {
  8404. this._deferUnregister(observer);
  8405. return true;
  8406. }
  8407. return false;
  8408. };
  8409. /**
  8410. * Remove a callback from the Observable object
  8411. * @param callback the callback to remove
  8412. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8413. * @returns false if it doesn't belong to this Observable
  8414. */
  8415. Observable.prototype.removeCallback = function (callback, scope) {
  8416. for (var index = 0; index < this._observers.length; index++) {
  8417. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8418. this._deferUnregister(this._observers[index]);
  8419. return true;
  8420. }
  8421. }
  8422. return false;
  8423. };
  8424. Observable.prototype._deferUnregister = function (observer) {
  8425. var _this = this;
  8426. observer.unregisterOnNextCall = false;
  8427. observer._willBeUnregistered = true;
  8428. BABYLON.Tools.SetImmediate(function () {
  8429. _this._remove(observer);
  8430. });
  8431. };
  8432. // This should only be called when not iterating over _observers to avoid callback skipping.
  8433. // Removes an observer from the _observer Array.
  8434. Observable.prototype._remove = function (observer) {
  8435. if (!observer) {
  8436. return false;
  8437. }
  8438. var index = this._observers.indexOf(observer);
  8439. if (index !== -1) {
  8440. this._observers.splice(index, 1);
  8441. return true;
  8442. }
  8443. return false;
  8444. };
  8445. /**
  8446. * Notify all Observers by calling their respective callback with the given data
  8447. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8448. * @param eventData defines the data to send to all observers
  8449. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8450. * @param target defines the original target of the state
  8451. * @param currentTarget defines the current target of the state
  8452. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8453. */
  8454. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8455. if (mask === void 0) { mask = -1; }
  8456. if (!this._observers.length) {
  8457. return true;
  8458. }
  8459. var state = this._eventState;
  8460. state.mask = mask;
  8461. state.target = target;
  8462. state.currentTarget = currentTarget;
  8463. state.skipNextObservers = false;
  8464. state.lastReturnValue = eventData;
  8465. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8466. var obs = _a[_i];
  8467. if (obs._willBeUnregistered) {
  8468. continue;
  8469. }
  8470. if (obs.mask & mask) {
  8471. if (obs.scope) {
  8472. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8473. }
  8474. else {
  8475. state.lastReturnValue = obs.callback(eventData, state);
  8476. }
  8477. if (obs.unregisterOnNextCall) {
  8478. this._deferUnregister(obs);
  8479. }
  8480. }
  8481. if (state.skipNextObservers) {
  8482. return false;
  8483. }
  8484. }
  8485. return true;
  8486. };
  8487. /**
  8488. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8489. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8490. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8491. * and it is crucial that all callbacks will be executed.
  8492. * The order of the callbacks is kept, callbacks are not executed parallel.
  8493. *
  8494. * @param eventData The data to be sent to each callback
  8495. * @param mask is used to filter observers defaults to -1
  8496. * @param target defines the callback target (see EventState)
  8497. * @param currentTarget defines he current object in the bubbling phase
  8498. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8499. */
  8500. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8501. var _this = this;
  8502. if (mask === void 0) { mask = -1; }
  8503. // create an empty promise
  8504. var p = Promise.resolve(eventData);
  8505. // no observers? return this promise.
  8506. if (!this._observers.length) {
  8507. return p;
  8508. }
  8509. var state = this._eventState;
  8510. state.mask = mask;
  8511. state.target = target;
  8512. state.currentTarget = currentTarget;
  8513. state.skipNextObservers = false;
  8514. // execute one callback after another (not using Promise.all, the order is important)
  8515. this._observers.forEach(function (obs) {
  8516. if (state.skipNextObservers) {
  8517. return;
  8518. }
  8519. if (obs._willBeUnregistered) {
  8520. return;
  8521. }
  8522. if (obs.mask & mask) {
  8523. if (obs.scope) {
  8524. p = p.then(function (lastReturnedValue) {
  8525. state.lastReturnValue = lastReturnedValue;
  8526. return obs.callback.apply(obs.scope, [eventData, state]);
  8527. });
  8528. }
  8529. else {
  8530. p = p.then(function (lastReturnedValue) {
  8531. state.lastReturnValue = lastReturnedValue;
  8532. return obs.callback(eventData, state);
  8533. });
  8534. }
  8535. if (obs.unregisterOnNextCall) {
  8536. _this._deferUnregister(obs);
  8537. }
  8538. }
  8539. });
  8540. // return the eventData
  8541. return p.then(function () { return eventData; });
  8542. };
  8543. /**
  8544. * Notify a specific observer
  8545. * @param observer defines the observer to notify
  8546. * @param eventData defines the data to be sent to each callback
  8547. * @param mask is used to filter observers defaults to -1
  8548. */
  8549. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8550. if (mask === void 0) { mask = -1; }
  8551. var state = this._eventState;
  8552. state.mask = mask;
  8553. state.skipNextObservers = false;
  8554. observer.callback(eventData, state);
  8555. };
  8556. /**
  8557. * Gets a boolean indicating if the observable has at least one observer
  8558. * @returns true is the Observable has at least one Observer registered
  8559. */
  8560. Observable.prototype.hasObservers = function () {
  8561. return this._observers.length > 0;
  8562. };
  8563. /**
  8564. * Clear the list of observers
  8565. */
  8566. Observable.prototype.clear = function () {
  8567. this._observers = new Array();
  8568. this._onObserverAdded = null;
  8569. };
  8570. /**
  8571. * Clone the current observable
  8572. * @returns a new observable
  8573. */
  8574. Observable.prototype.clone = function () {
  8575. var result = new Observable();
  8576. result._observers = this._observers.slice(0);
  8577. return result;
  8578. };
  8579. /**
  8580. * Does this observable handles observer registered with a given mask
  8581. * @param mask defines the mask to be tested
  8582. * @return whether or not one observer registered with the given mask is handeled
  8583. **/
  8584. Observable.prototype.hasSpecificMask = function (mask) {
  8585. if (mask === void 0) { mask = -1; }
  8586. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8587. var obs = _a[_i];
  8588. if (obs.mask & mask || obs.mask === mask) {
  8589. return true;
  8590. }
  8591. }
  8592. return false;
  8593. };
  8594. return Observable;
  8595. }());
  8596. BABYLON.Observable = Observable;
  8597. })(BABYLON || (BABYLON = {}));
  8598. //# sourceMappingURL=babylon.observable.js.map
  8599. var BABYLON;
  8600. (function (BABYLON) {
  8601. /**
  8602. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8603. */
  8604. var SmartArray = /** @class */ (function () {
  8605. /**
  8606. * Instantiates a Smart Array.
  8607. * @param capacity defines the default capacity of the array.
  8608. */
  8609. function SmartArray(capacity) {
  8610. /**
  8611. * The active length of the array.
  8612. */
  8613. this.length = 0;
  8614. this.data = new Array(capacity);
  8615. this._id = SmartArray._GlobalId++;
  8616. }
  8617. /**
  8618. * Pushes a value at the end of the active data.
  8619. * @param value defines the object to push in the array.
  8620. */
  8621. SmartArray.prototype.push = function (value) {
  8622. this.data[this.length++] = value;
  8623. if (this.length > this.data.length) {
  8624. this.data.length *= 2;
  8625. }
  8626. };
  8627. /**
  8628. * Iterates over the active data and apply the lambda to them.
  8629. * @param func defines the action to apply on each value.
  8630. */
  8631. SmartArray.prototype.forEach = function (func) {
  8632. for (var index = 0; index < this.length; index++) {
  8633. func(this.data[index]);
  8634. }
  8635. };
  8636. /**
  8637. * Sorts the full sets of data.
  8638. * @param compareFn defines the comparison function to apply.
  8639. */
  8640. SmartArray.prototype.sort = function (compareFn) {
  8641. this.data.sort(compareFn);
  8642. };
  8643. /**
  8644. * Resets the active data to an empty array.
  8645. */
  8646. SmartArray.prototype.reset = function () {
  8647. this.length = 0;
  8648. };
  8649. /**
  8650. * Releases all the data from the array as well as the array.
  8651. */
  8652. SmartArray.prototype.dispose = function () {
  8653. this.reset();
  8654. if (this.data) {
  8655. this.data.length = 0;
  8656. this.data = [];
  8657. }
  8658. };
  8659. /**
  8660. * Concats the active data with a given array.
  8661. * @param array defines the data to concatenate with.
  8662. */
  8663. SmartArray.prototype.concat = function (array) {
  8664. if (array.length === 0) {
  8665. return;
  8666. }
  8667. if (this.length + array.length > this.data.length) {
  8668. this.data.length = (this.length + array.length) * 2;
  8669. }
  8670. for (var index = 0; index < array.length; index++) {
  8671. this.data[this.length++] = (array.data || array)[index];
  8672. }
  8673. };
  8674. /**
  8675. * Returns the position of a value in the active data.
  8676. * @param value defines the value to find the index for
  8677. * @returns the index if found in the active data otherwise -1
  8678. */
  8679. SmartArray.prototype.indexOf = function (value) {
  8680. var position = this.data.indexOf(value);
  8681. if (position >= this.length) {
  8682. return -1;
  8683. }
  8684. return position;
  8685. };
  8686. /**
  8687. * Returns whether an element is part of the active data.
  8688. * @param value defines the value to look for
  8689. * @returns true if found in the active data otherwise false
  8690. */
  8691. SmartArray.prototype.contains = function (value) {
  8692. return this.indexOf(value) !== -1;
  8693. };
  8694. // Statics
  8695. SmartArray._GlobalId = 0;
  8696. return SmartArray;
  8697. }());
  8698. BABYLON.SmartArray = SmartArray;
  8699. /**
  8700. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8701. * The data in this array can only be present once
  8702. */
  8703. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8704. __extends(SmartArrayNoDuplicate, _super);
  8705. function SmartArrayNoDuplicate() {
  8706. var _this = _super !== null && _super.apply(this, arguments) || this;
  8707. _this._duplicateId = 0;
  8708. return _this;
  8709. }
  8710. /**
  8711. * Pushes a value at the end of the active data.
  8712. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8713. * @param value defines the object to push in the array.
  8714. */
  8715. SmartArrayNoDuplicate.prototype.push = function (value) {
  8716. _super.prototype.push.call(this, value);
  8717. if (!value.__smartArrayFlags) {
  8718. value.__smartArrayFlags = {};
  8719. }
  8720. value.__smartArrayFlags[this._id] = this._duplicateId;
  8721. };
  8722. /**
  8723. * Pushes a value at the end of the active data.
  8724. * If the data is already present, it won t be added again
  8725. * @param value defines the object to push in the array.
  8726. * @returns true if added false if it was already present
  8727. */
  8728. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8729. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8730. return false;
  8731. }
  8732. this.push(value);
  8733. return true;
  8734. };
  8735. /**
  8736. * Resets the active data to an empty array.
  8737. */
  8738. SmartArrayNoDuplicate.prototype.reset = function () {
  8739. _super.prototype.reset.call(this);
  8740. this._duplicateId++;
  8741. };
  8742. /**
  8743. * Concats the active data with a given array.
  8744. * This ensures no dupplicate will be present in the result.
  8745. * @param array defines the data to concatenate with.
  8746. */
  8747. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8748. if (array.length === 0) {
  8749. return;
  8750. }
  8751. if (this.length + array.length > this.data.length) {
  8752. this.data.length = (this.length + array.length) * 2;
  8753. }
  8754. for (var index = 0; index < array.length; index++) {
  8755. var item = (array.data || array)[index];
  8756. this.pushNoDuplicate(item);
  8757. }
  8758. };
  8759. return SmartArrayNoDuplicate;
  8760. }(SmartArray));
  8761. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8762. })(BABYLON || (BABYLON = {}));
  8763. //# sourceMappingURL=babylon.smartArray.js.map
  8764. var BABYLON;
  8765. (function (BABYLON) {
  8766. /** Class used to store color4 gradient */
  8767. var ColorGradient = /** @class */ (function () {
  8768. function ColorGradient() {
  8769. }
  8770. /**
  8771. * Will get a color picked randomly between color1 and color2.
  8772. * If color2 is undefined then color1 will be used
  8773. * @param result defines the target Color4 to store the result in
  8774. */
  8775. ColorGradient.prototype.getColorToRef = function (result) {
  8776. if (!this.color2) {
  8777. result.copyFrom(this.color1);
  8778. return;
  8779. }
  8780. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8781. };
  8782. return ColorGradient;
  8783. }());
  8784. BABYLON.ColorGradient = ColorGradient;
  8785. /** Class used to store color 3 gradient */
  8786. var Color3Gradient = /** @class */ (function () {
  8787. function Color3Gradient() {
  8788. }
  8789. return Color3Gradient;
  8790. }());
  8791. BABYLON.Color3Gradient = Color3Gradient;
  8792. /** Class used to store factor gradient */
  8793. var FactorGradient = /** @class */ (function () {
  8794. function FactorGradient() {
  8795. }
  8796. /**
  8797. * Will get a number picked randomly between factor1 and factor2.
  8798. * If factor2 is undefined then factor1 will be used
  8799. * @returns the picked number
  8800. */
  8801. FactorGradient.prototype.getFactor = function () {
  8802. if (this.factor2 === undefined) {
  8803. return this.factor1;
  8804. }
  8805. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8806. };
  8807. return FactorGradient;
  8808. }());
  8809. BABYLON.FactorGradient = FactorGradient;
  8810. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8811. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8812. var LoadFileError = /** @class */ (function (_super) {
  8813. __extends(LoadFileError, _super);
  8814. function LoadFileError(message, request) {
  8815. var _this = _super.call(this, message) || this;
  8816. _this.request = request;
  8817. _this.name = "LoadFileError";
  8818. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8819. return _this;
  8820. }
  8821. // Polyfill for Object.setPrototypeOf if necessary.
  8822. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8823. return LoadFileError;
  8824. }(Error));
  8825. BABYLON.LoadFileError = LoadFileError;
  8826. var RetryStrategy = /** @class */ (function () {
  8827. function RetryStrategy() {
  8828. }
  8829. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8830. if (maxRetries === void 0) { maxRetries = 3; }
  8831. if (baseInterval === void 0) { baseInterval = 500; }
  8832. return function (url, request, retryIndex) {
  8833. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8834. return -1;
  8835. }
  8836. return Math.pow(2, retryIndex) * baseInterval;
  8837. };
  8838. };
  8839. return RetryStrategy;
  8840. }());
  8841. BABYLON.RetryStrategy = RetryStrategy;
  8842. // Screenshots
  8843. var screenshotCanvas;
  8844. var cloneValue = function (source, destinationObject) {
  8845. if (!source)
  8846. return null;
  8847. if (source instanceof BABYLON.Mesh) {
  8848. return null;
  8849. }
  8850. if (source instanceof BABYLON.SubMesh) {
  8851. return source.clone(destinationObject);
  8852. }
  8853. else if (source.clone) {
  8854. return source.clone();
  8855. }
  8856. return null;
  8857. };
  8858. var Tools = /** @class */ (function () {
  8859. function Tools() {
  8860. }
  8861. /**
  8862. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8863. * @param u defines the coordinate on X axis
  8864. * @param v defines the coordinate on Y axis
  8865. * @param width defines the width of the source data
  8866. * @param height defines the height of the source data
  8867. * @param pixels defines the source byte array
  8868. * @param color defines the output color
  8869. */
  8870. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8871. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8872. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8873. var position = (wrappedU + wrappedV * width) * 4;
  8874. color.r = pixels[position] / 255;
  8875. color.g = pixels[position + 1] / 255;
  8876. color.b = pixels[position + 2] / 255;
  8877. color.a = pixels[position + 3] / 255;
  8878. };
  8879. /**
  8880. * Interpolates between a and b via alpha
  8881. * @param a The lower value (returned when alpha = 0)
  8882. * @param b The upper value (returned when alpha = 1)
  8883. * @param alpha The interpolation-factor
  8884. * @return The mixed value
  8885. */
  8886. Tools.Mix = function (a, b, alpha) {
  8887. return a * (1 - alpha) + b * alpha;
  8888. };
  8889. Tools.Instantiate = function (className) {
  8890. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8891. return Tools.RegisteredExternalClasses[className];
  8892. }
  8893. var arr = className.split(".");
  8894. var fn = (window || this);
  8895. for (var i = 0, len = arr.length; i < len; i++) {
  8896. fn = fn[arr[i]];
  8897. }
  8898. if (typeof fn !== "function") {
  8899. return null;
  8900. }
  8901. return fn;
  8902. };
  8903. /**
  8904. * Provides a slice function that will work even on IE
  8905. * @param data defines the array to slice
  8906. * @param start defines the start of the data (optional)
  8907. * @param end defines the end of the data (optional)
  8908. * @returns the new sliced array
  8909. */
  8910. Tools.Slice = function (data, start, end) {
  8911. if (data.slice) {
  8912. return data.slice(start, end);
  8913. }
  8914. return Array.prototype.slice.call(data, start, end);
  8915. };
  8916. Tools.SetImmediate = function (action) {
  8917. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8918. window.setImmediate(action);
  8919. }
  8920. else {
  8921. setTimeout(action, 1);
  8922. }
  8923. };
  8924. Tools.IsExponentOfTwo = function (value) {
  8925. var count = 1;
  8926. do {
  8927. count *= 2;
  8928. } while (count < value);
  8929. return count === value;
  8930. };
  8931. /**
  8932. * Returns the nearest 32-bit single precision float representation of a Number
  8933. * @param value A Number. If the parameter is of a different type, it will get converted
  8934. * to a number or to NaN if it cannot be converted
  8935. * @returns number
  8936. */
  8937. Tools.FloatRound = function (value) {
  8938. if (Math.fround) {
  8939. return Math.fround(value);
  8940. }
  8941. return (Tools._tmpFloatArray[0] = value);
  8942. };
  8943. /**
  8944. * Find the next highest power of two.
  8945. * @param x Number to start search from.
  8946. * @return Next highest power of two.
  8947. */
  8948. Tools.CeilingPOT = function (x) {
  8949. x--;
  8950. x |= x >> 1;
  8951. x |= x >> 2;
  8952. x |= x >> 4;
  8953. x |= x >> 8;
  8954. x |= x >> 16;
  8955. x++;
  8956. return x;
  8957. };
  8958. /**
  8959. * Find the next lowest power of two.
  8960. * @param x Number to start search from.
  8961. * @return Next lowest power of two.
  8962. */
  8963. Tools.FloorPOT = function (x) {
  8964. x = x | (x >> 1);
  8965. x = x | (x >> 2);
  8966. x = x | (x >> 4);
  8967. x = x | (x >> 8);
  8968. x = x | (x >> 16);
  8969. return x - (x >> 1);
  8970. };
  8971. /**
  8972. * Find the nearest power of two.
  8973. * @param x Number to start search from.
  8974. * @return Next nearest power of two.
  8975. */
  8976. Tools.NearestPOT = function (x) {
  8977. var c = Tools.CeilingPOT(x);
  8978. var f = Tools.FloorPOT(x);
  8979. return (c - x) > (x - f) ? f : c;
  8980. };
  8981. Tools.GetExponentOfTwo = function (value, max, mode) {
  8982. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8983. var pot;
  8984. switch (mode) {
  8985. case BABYLON.Engine.SCALEMODE_FLOOR:
  8986. pot = Tools.FloorPOT(value);
  8987. break;
  8988. case BABYLON.Engine.SCALEMODE_NEAREST:
  8989. pot = Tools.NearestPOT(value);
  8990. break;
  8991. case BABYLON.Engine.SCALEMODE_CEILING:
  8992. default:
  8993. pot = Tools.CeilingPOT(value);
  8994. break;
  8995. }
  8996. return Math.min(pot, max);
  8997. };
  8998. Tools.GetFilename = function (path) {
  8999. var index = path.lastIndexOf("/");
  9000. if (index < 0)
  9001. return path;
  9002. return path.substring(index + 1);
  9003. };
  9004. /**
  9005. * Extracts the "folder" part of a path (everything before the filename).
  9006. * @param uri The URI to extract the info from
  9007. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9008. * @returns The "folder" part of the path
  9009. */
  9010. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9011. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9012. var index = uri.lastIndexOf("/");
  9013. if (index < 0) {
  9014. if (returnUnchangedIfNoSlash) {
  9015. return uri;
  9016. }
  9017. return "";
  9018. }
  9019. return uri.substring(0, index + 1);
  9020. };
  9021. Tools.GetDOMTextContent = function (element) {
  9022. var result = "";
  9023. var child = element.firstChild;
  9024. while (child) {
  9025. if (child.nodeType === 3) {
  9026. result += child.textContent;
  9027. }
  9028. child = child.nextSibling;
  9029. }
  9030. return result;
  9031. };
  9032. Tools.ToDegrees = function (angle) {
  9033. return angle * 180 / Math.PI;
  9034. };
  9035. Tools.ToRadians = function (angle) {
  9036. return angle * Math.PI / 180;
  9037. };
  9038. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9039. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9040. var output = "";
  9041. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9042. var i = 0;
  9043. var bytes = new Uint8Array(buffer);
  9044. while (i < bytes.length) {
  9045. chr1 = bytes[i++];
  9046. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9047. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9048. enc1 = chr1 >> 2;
  9049. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9050. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9051. enc4 = chr3 & 63;
  9052. if (isNaN(chr2)) {
  9053. enc3 = enc4 = 64;
  9054. }
  9055. else if (isNaN(chr3)) {
  9056. enc4 = 64;
  9057. }
  9058. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9059. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9060. }
  9061. return "data:image/png;base64," + output;
  9062. };
  9063. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9064. if (bias === void 0) { bias = null; }
  9065. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9066. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9067. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9068. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  9069. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9070. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9071. }
  9072. if (bias) {
  9073. minimum.x -= minimum.x * bias.x + bias.y;
  9074. minimum.y -= minimum.y * bias.x + bias.y;
  9075. minimum.z -= minimum.z * bias.x + bias.y;
  9076. maximum.x += maximum.x * bias.x + bias.y;
  9077. maximum.y += maximum.y * bias.x + bias.y;
  9078. maximum.z += maximum.z * bias.x + bias.y;
  9079. }
  9080. return {
  9081. minimum: minimum,
  9082. maximum: maximum
  9083. };
  9084. };
  9085. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9086. if (bias === void 0) { bias = null; }
  9087. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9088. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9089. if (!stride) {
  9090. stride = 3;
  9091. }
  9092. for (var index = start; index < start + count; index++) {
  9093. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9094. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9095. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9096. }
  9097. if (bias) {
  9098. minimum.x -= minimum.x * bias.x + bias.y;
  9099. minimum.y -= minimum.y * bias.x + bias.y;
  9100. minimum.z -= minimum.z * bias.x + bias.y;
  9101. maximum.x += maximum.x * bias.x + bias.y;
  9102. maximum.y += maximum.y * bias.x + bias.y;
  9103. maximum.z += maximum.z * bias.x + bias.y;
  9104. }
  9105. return {
  9106. minimum: minimum,
  9107. maximum: maximum
  9108. };
  9109. };
  9110. Tools.Vector2ArrayFeeder = function (array) {
  9111. return function (index) {
  9112. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9113. var length = isFloatArray ? array.length / 2 : array.length;
  9114. if (index >= length) {
  9115. return null;
  9116. }
  9117. if (isFloatArray) {
  9118. var fa = array;
  9119. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9120. }
  9121. var a = array;
  9122. return a[index];
  9123. };
  9124. };
  9125. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9126. if (bias === void 0) { bias = null; }
  9127. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9128. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9129. var i = 0;
  9130. var cur = feeder(i++);
  9131. while (cur) {
  9132. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9133. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9134. cur = feeder(i++);
  9135. }
  9136. if (bias) {
  9137. minimum.x -= minimum.x * bias.x + bias.y;
  9138. minimum.y -= minimum.y * bias.x + bias.y;
  9139. maximum.x += maximum.x * bias.x + bias.y;
  9140. maximum.y += maximum.y * bias.x + bias.y;
  9141. }
  9142. return {
  9143. minimum: minimum,
  9144. maximum: maximum
  9145. };
  9146. };
  9147. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9148. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9149. return null;
  9150. return Array.isArray(obj) ? obj : [obj];
  9151. };
  9152. // Misc.
  9153. Tools.GetPointerPrefix = function () {
  9154. var eventPrefix = "pointer";
  9155. // Check if pointer events are supported
  9156. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9157. eventPrefix = "mouse";
  9158. }
  9159. return eventPrefix;
  9160. };
  9161. /**
  9162. * @param func - the function to be called
  9163. * @param requester - the object that will request the next frame. Falls back to window.
  9164. */
  9165. Tools.QueueNewFrame = function (func, requester) {
  9166. if (!Tools.IsWindowObjectExist()) {
  9167. return setTimeout(func, 16);
  9168. }
  9169. if (!requester) {
  9170. requester = window;
  9171. }
  9172. if (requester.requestAnimationFrame) {
  9173. return requester.requestAnimationFrame(func);
  9174. }
  9175. else if (requester.msRequestAnimationFrame) {
  9176. return requester.msRequestAnimationFrame(func);
  9177. }
  9178. else if (requester.webkitRequestAnimationFrame) {
  9179. return requester.webkitRequestAnimationFrame(func);
  9180. }
  9181. else if (requester.mozRequestAnimationFrame) {
  9182. return requester.mozRequestAnimationFrame(func);
  9183. }
  9184. else if (requester.oRequestAnimationFrame) {
  9185. return requester.oRequestAnimationFrame(func);
  9186. }
  9187. else {
  9188. return window.setTimeout(func, 16);
  9189. }
  9190. };
  9191. Tools.RequestFullscreen = function (element) {
  9192. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9193. if (!requestFunction)
  9194. return;
  9195. requestFunction.call(element);
  9196. };
  9197. Tools.ExitFullscreen = function () {
  9198. if (document.exitFullscreen) {
  9199. document.exitFullscreen();
  9200. }
  9201. else if (document.mozCancelFullScreen) {
  9202. document.mozCancelFullScreen();
  9203. }
  9204. else if (document.webkitCancelFullScreen) {
  9205. document.webkitCancelFullScreen();
  9206. }
  9207. else if (document.msCancelFullScreen) {
  9208. document.msCancelFullScreen();
  9209. }
  9210. };
  9211. /**
  9212. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9213. * @param url define the url we are trying
  9214. * @param element define the dom element where to configure the cors policy
  9215. */
  9216. Tools.SetCorsBehavior = function (url, element) {
  9217. if (url && url.indexOf("data:") === 0) {
  9218. return;
  9219. }
  9220. if (Tools.CorsBehavior) {
  9221. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9222. element.crossOrigin = Tools.CorsBehavior;
  9223. }
  9224. else {
  9225. var result = Tools.CorsBehavior(url);
  9226. if (result) {
  9227. element.crossOrigin = result;
  9228. }
  9229. }
  9230. }
  9231. };
  9232. // External files
  9233. Tools.CleanUrl = function (url) {
  9234. url = url.replace(/#/mg, "%23");
  9235. return url;
  9236. };
  9237. /**
  9238. * Loads an image as an HTMLImageElement.
  9239. * @param input url string, ArrayBuffer, or Blob to load
  9240. * @param onLoad callback called when the image successfully loads
  9241. * @param onError callback called when the image fails to load
  9242. * @param database database for caching
  9243. * @returns the HTMLImageElement of the loaded image
  9244. */
  9245. Tools.LoadImage = function (input, onLoad, onError, database) {
  9246. var url;
  9247. var usingObjectURL = false;
  9248. if (input instanceof ArrayBuffer) {
  9249. url = URL.createObjectURL(new Blob([input]));
  9250. usingObjectURL = true;
  9251. }
  9252. else if (input instanceof Blob) {
  9253. url = URL.createObjectURL(input);
  9254. usingObjectURL = true;
  9255. }
  9256. else {
  9257. url = Tools.CleanUrl(input);
  9258. url = Tools.PreprocessUrl(input);
  9259. }
  9260. var img = new Image();
  9261. Tools.SetCorsBehavior(url, img);
  9262. var loadHandler = function () {
  9263. if (usingObjectURL && img.src) {
  9264. URL.revokeObjectURL(img.src);
  9265. }
  9266. img.removeEventListener("load", loadHandler);
  9267. img.removeEventListener("error", errorHandler);
  9268. onLoad(img);
  9269. };
  9270. var errorHandler = function (err) {
  9271. if (usingObjectURL && img.src) {
  9272. URL.revokeObjectURL(img.src);
  9273. }
  9274. img.removeEventListener("load", loadHandler);
  9275. img.removeEventListener("error", errorHandler);
  9276. Tools.Error("Error while trying to load image: " + input);
  9277. if (onError) {
  9278. onError("Error while trying to load image: " + input, err);
  9279. }
  9280. };
  9281. img.addEventListener("load", loadHandler);
  9282. img.addEventListener("error", errorHandler);
  9283. var noIndexedDB = function () {
  9284. img.src = url;
  9285. };
  9286. var loadFromIndexedDB = function () {
  9287. if (database) {
  9288. database.loadImageFromDB(url, img);
  9289. }
  9290. };
  9291. //ANY database to do!
  9292. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9293. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9294. }
  9295. else {
  9296. if (url.indexOf("file:") !== -1) {
  9297. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9298. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9299. try {
  9300. var blobURL;
  9301. try {
  9302. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9303. }
  9304. catch (ex) {
  9305. // Chrome doesn't support oneTimeOnly parameter
  9306. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9307. }
  9308. img.src = blobURL;
  9309. usingObjectURL = true;
  9310. }
  9311. catch (e) {
  9312. img.src = "";
  9313. }
  9314. return img;
  9315. }
  9316. }
  9317. noIndexedDB();
  9318. }
  9319. return img;
  9320. };
  9321. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9322. url = Tools.CleanUrl(url);
  9323. url = Tools.PreprocessUrl(url);
  9324. // If file and file input are set
  9325. if (url.indexOf("file:") !== -1) {
  9326. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9327. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9328. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9329. }
  9330. }
  9331. var loadUrl = Tools.BaseUrl + url;
  9332. var aborted = false;
  9333. var fileRequest = {
  9334. onCompleteObservable: new BABYLON.Observable(),
  9335. abort: function () { return aborted = true; },
  9336. };
  9337. var requestFile = function () {
  9338. var request = new XMLHttpRequest();
  9339. var retryHandle = null;
  9340. fileRequest.abort = function () {
  9341. aborted = true;
  9342. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9343. request.abort();
  9344. }
  9345. if (retryHandle !== null) {
  9346. clearTimeout(retryHandle);
  9347. retryHandle = null;
  9348. }
  9349. };
  9350. var retryLoop = function (retryIndex) {
  9351. request.open('GET', loadUrl, true);
  9352. if (useArrayBuffer) {
  9353. request.responseType = "arraybuffer";
  9354. }
  9355. if (onProgress) {
  9356. request.addEventListener("progress", onProgress);
  9357. }
  9358. var onLoadEnd = function () {
  9359. request.removeEventListener("loadend", onLoadEnd);
  9360. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9361. fileRequest.onCompleteObservable.clear();
  9362. };
  9363. request.addEventListener("loadend", onLoadEnd);
  9364. var onReadyStateChange = function () {
  9365. if (aborted) {
  9366. return;
  9367. }
  9368. // In case of undefined state in some browsers.
  9369. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9370. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9371. request.removeEventListener("readystatechange", onReadyStateChange);
  9372. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9373. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9374. return;
  9375. }
  9376. var retryStrategy = Tools.DefaultRetryStrategy;
  9377. if (retryStrategy) {
  9378. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9379. if (waitTime !== -1) {
  9380. // Prevent the request from completing for retry.
  9381. request.removeEventListener("loadend", onLoadEnd);
  9382. request = new XMLHttpRequest();
  9383. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9384. return;
  9385. }
  9386. }
  9387. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9388. if (onError) {
  9389. onError(request, e);
  9390. }
  9391. else {
  9392. throw e;
  9393. }
  9394. }
  9395. };
  9396. request.addEventListener("readystatechange", onReadyStateChange);
  9397. request.send();
  9398. };
  9399. retryLoop(0);
  9400. };
  9401. // Caching all files
  9402. if (database && database.enableSceneOffline) {
  9403. var noIndexedDB_1 = function (request) {
  9404. if (request && request.status > 400) {
  9405. if (onError) {
  9406. onError(request);
  9407. }
  9408. }
  9409. else {
  9410. if (!aborted) {
  9411. requestFile();
  9412. }
  9413. }
  9414. };
  9415. var loadFromIndexedDB = function () {
  9416. // TODO: database needs to support aborting and should return a IFileRequest
  9417. if (aborted) {
  9418. return;
  9419. }
  9420. if (database) {
  9421. database.loadFileFromDB(url, function (data) {
  9422. if (!aborted) {
  9423. onSuccess(data);
  9424. }
  9425. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9426. }, onProgress ? function (event) {
  9427. if (!aborted) {
  9428. onProgress(event);
  9429. }
  9430. } : undefined, noIndexedDB_1, useArrayBuffer);
  9431. }
  9432. };
  9433. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9434. }
  9435. else {
  9436. requestFile();
  9437. }
  9438. return fileRequest;
  9439. };
  9440. /**
  9441. * Load a script (identified by an url). When the url returns, the
  9442. * content of this file is added into a new script element, attached to the DOM (body element)
  9443. */
  9444. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9445. if (!Tools.IsWindowObjectExist()) {
  9446. return;
  9447. }
  9448. var head = document.getElementsByTagName('head')[0];
  9449. var script = document.createElement('script');
  9450. script.type = 'text/javascript';
  9451. script.src = scriptUrl;
  9452. script.onload = function () {
  9453. if (onSuccess) {
  9454. onSuccess();
  9455. }
  9456. };
  9457. script.onerror = function (e) {
  9458. if (onError) {
  9459. onError("Unable to load script '" + scriptUrl + "'", e);
  9460. }
  9461. };
  9462. head.appendChild(script);
  9463. };
  9464. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9465. var reader = new FileReader();
  9466. var request = {
  9467. onCompleteObservable: new BABYLON.Observable(),
  9468. abort: function () { return reader.abort(); },
  9469. };
  9470. reader.onloadend = function (e) {
  9471. request.onCompleteObservable.notifyObservers(request);
  9472. };
  9473. reader.onload = function (e) {
  9474. //target doesn't have result from ts 1.3
  9475. callback(e.target['result']);
  9476. };
  9477. reader.onprogress = progressCallback;
  9478. reader.readAsDataURL(fileToLoad);
  9479. return request;
  9480. };
  9481. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9482. var reader = new FileReader();
  9483. var request = {
  9484. onCompleteObservable: new BABYLON.Observable(),
  9485. abort: function () { return reader.abort(); },
  9486. };
  9487. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9488. reader.onerror = function (e) {
  9489. Tools.Log("Error while reading file: " + fileToLoad.name);
  9490. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9491. };
  9492. reader.onload = function (e) {
  9493. //target doesn't have result from ts 1.3
  9494. callback(e.target['result']);
  9495. };
  9496. if (progressCallBack) {
  9497. reader.onprogress = progressCallBack;
  9498. }
  9499. if (!useArrayBuffer) {
  9500. // Asynchronous read
  9501. reader.readAsText(fileToLoad);
  9502. }
  9503. else {
  9504. reader.readAsArrayBuffer(fileToLoad);
  9505. }
  9506. return request;
  9507. };
  9508. //returns a downloadable url to a file content.
  9509. Tools.FileAsURL = function (content) {
  9510. var fileBlob = new Blob([content]);
  9511. var url = window.URL || window.webkitURL;
  9512. var link = url.createObjectURL(fileBlob);
  9513. return link;
  9514. };
  9515. // Misc.
  9516. Tools.Format = function (value, decimals) {
  9517. if (decimals === void 0) { decimals = 2; }
  9518. return value.toFixed(decimals);
  9519. };
  9520. Tools.CheckExtends = function (v, min, max) {
  9521. if (v.x < min.x)
  9522. min.x = v.x;
  9523. if (v.y < min.y)
  9524. min.y = v.y;
  9525. if (v.z < min.z)
  9526. min.z = v.z;
  9527. if (v.x > max.x)
  9528. max.x = v.x;
  9529. if (v.y > max.y)
  9530. max.y = v.y;
  9531. if (v.z > max.z)
  9532. max.z = v.z;
  9533. };
  9534. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9535. for (var prop in source) {
  9536. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9537. continue;
  9538. }
  9539. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9540. continue;
  9541. }
  9542. var sourceValue = source[prop];
  9543. var typeOfSourceValue = typeof sourceValue;
  9544. if (typeOfSourceValue === "function") {
  9545. continue;
  9546. }
  9547. try {
  9548. if (typeOfSourceValue === "object") {
  9549. if (sourceValue instanceof Array) {
  9550. destination[prop] = [];
  9551. if (sourceValue.length > 0) {
  9552. if (typeof sourceValue[0] == "object") {
  9553. for (var index = 0; index < sourceValue.length; index++) {
  9554. var clonedValue = cloneValue(sourceValue[index], destination);
  9555. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9556. destination[prop].push(clonedValue);
  9557. }
  9558. }
  9559. }
  9560. else {
  9561. destination[prop] = sourceValue.slice(0);
  9562. }
  9563. }
  9564. }
  9565. else {
  9566. destination[prop] = cloneValue(sourceValue, destination);
  9567. }
  9568. }
  9569. else {
  9570. destination[prop] = sourceValue;
  9571. }
  9572. }
  9573. catch (e) {
  9574. // Just ignore error (it could be because of a read-only property)
  9575. }
  9576. }
  9577. };
  9578. Tools.IsEmpty = function (obj) {
  9579. for (var i in obj) {
  9580. if (obj.hasOwnProperty(i)) {
  9581. return false;
  9582. }
  9583. }
  9584. return true;
  9585. };
  9586. Tools.RegisterTopRootEvents = function (events) {
  9587. for (var index = 0; index < events.length; index++) {
  9588. var event = events[index];
  9589. window.addEventListener(event.name, event.handler, false);
  9590. try {
  9591. if (window.parent) {
  9592. window.parent.addEventListener(event.name, event.handler, false);
  9593. }
  9594. }
  9595. catch (e) {
  9596. // Silently fails...
  9597. }
  9598. }
  9599. };
  9600. Tools.UnregisterTopRootEvents = function (events) {
  9601. for (var index = 0; index < events.length; index++) {
  9602. var event = events[index];
  9603. window.removeEventListener(event.name, event.handler);
  9604. try {
  9605. if (window.parent) {
  9606. window.parent.removeEventListener(event.name, event.handler);
  9607. }
  9608. }
  9609. catch (e) {
  9610. // Silently fails...
  9611. }
  9612. }
  9613. };
  9614. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9615. if (mimeType === void 0) { mimeType = "image/png"; }
  9616. // Read the contents of the framebuffer
  9617. var numberOfChannelsByLine = width * 4;
  9618. var halfHeight = height / 2;
  9619. //Reading datas from WebGL
  9620. var data = engine.readPixels(0, 0, width, height);
  9621. //To flip image on Y axis.
  9622. for (var i = 0; i < halfHeight; i++) {
  9623. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9624. var currentCell = j + i * numberOfChannelsByLine;
  9625. var targetLine = height - i - 1;
  9626. var targetCell = j + targetLine * numberOfChannelsByLine;
  9627. var temp = data[currentCell];
  9628. data[currentCell] = data[targetCell];
  9629. data[targetCell] = temp;
  9630. }
  9631. }
  9632. // Create a 2D canvas to store the result
  9633. if (!screenshotCanvas) {
  9634. screenshotCanvas = document.createElement('canvas');
  9635. }
  9636. screenshotCanvas.width = width;
  9637. screenshotCanvas.height = height;
  9638. var context = screenshotCanvas.getContext('2d');
  9639. if (context) {
  9640. // Copy the pixels to a 2D canvas
  9641. var imageData = context.createImageData(width, height);
  9642. var castData = (imageData.data);
  9643. castData.set(data);
  9644. context.putImageData(imageData, 0, 0);
  9645. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9646. }
  9647. };
  9648. /**
  9649. * Converts the canvas data to blob.
  9650. * This acts as a polyfill for browsers not supporting the to blob function.
  9651. * @param canvas Defines the canvas to extract the data from
  9652. * @param successCallback Defines the callback triggered once the data are available
  9653. * @param mimeType Defines the mime type of the result
  9654. */
  9655. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9656. if (mimeType === void 0) { mimeType = "image/png"; }
  9657. // We need HTMLCanvasElement.toBlob for HD screenshots
  9658. if (!canvas.toBlob) {
  9659. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9660. canvas.toBlob = function (callback, type, quality) {
  9661. var _this = this;
  9662. setTimeout(function () {
  9663. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9664. for (var i = 0; i < len; i++) {
  9665. arr[i] = binStr.charCodeAt(i);
  9666. }
  9667. callback(new Blob([arr]));
  9668. });
  9669. };
  9670. }
  9671. canvas.toBlob(function (blob) {
  9672. successCallback(blob);
  9673. }, mimeType);
  9674. };
  9675. /**
  9676. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9677. * @param successCallback Defines the callback triggered once the data are available
  9678. * @param mimeType Defines the mime type of the result
  9679. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9680. */
  9681. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9682. if (mimeType === void 0) { mimeType = "image/png"; }
  9683. if (successCallback) {
  9684. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9685. successCallback(base64Image);
  9686. }
  9687. else {
  9688. this.ToBlob(screenshotCanvas, function (blob) {
  9689. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9690. if (("download" in document.createElement("a"))) {
  9691. if (!fileName) {
  9692. var date = new Date();
  9693. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9694. fileName = "screenshot_" + stringDate + ".png";
  9695. }
  9696. Tools.Download(blob, fileName);
  9697. }
  9698. else {
  9699. var url = URL.createObjectURL(blob);
  9700. var newWindow = window.open("");
  9701. if (!newWindow)
  9702. return;
  9703. var img = newWindow.document.createElement("img");
  9704. img.onload = function () {
  9705. // no longer need to read the blob so it's revoked
  9706. URL.revokeObjectURL(url);
  9707. };
  9708. img.src = url;
  9709. newWindow.document.body.appendChild(img);
  9710. }
  9711. }, mimeType);
  9712. }
  9713. };
  9714. /**
  9715. * Downloads a blob in the browser
  9716. * @param blob defines the blob to download
  9717. * @param fileName defines the name of the downloaded file
  9718. */
  9719. Tools.Download = function (blob, fileName) {
  9720. if (navigator && navigator.msSaveBlob) {
  9721. navigator.msSaveBlob(blob, fileName);
  9722. return;
  9723. }
  9724. var url = window.URL.createObjectURL(blob);
  9725. var a = document.createElement("a");
  9726. document.body.appendChild(a);
  9727. a.style.display = "none";
  9728. a.href = url;
  9729. a.download = fileName;
  9730. a.addEventListener("click", function () {
  9731. if (a.parentElement) {
  9732. a.parentElement.removeChild(a);
  9733. }
  9734. });
  9735. a.click();
  9736. window.URL.revokeObjectURL(url);
  9737. };
  9738. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9739. if (mimeType === void 0) { mimeType = "image/png"; }
  9740. var width;
  9741. var height;
  9742. // If a precision value is specified
  9743. if (size.precision) {
  9744. width = Math.round(engine.getRenderWidth() * size.precision);
  9745. height = Math.round(width / engine.getAspectRatio(camera));
  9746. }
  9747. else if (size.width && size.height) {
  9748. width = size.width;
  9749. height = size.height;
  9750. }
  9751. //If passing only width, computing height to keep display canvas ratio.
  9752. else if (size.width && !size.height) {
  9753. width = size.width;
  9754. height = Math.round(width / engine.getAspectRatio(camera));
  9755. }
  9756. //If passing only height, computing width to keep display canvas ratio.
  9757. else if (size.height && !size.width) {
  9758. height = size.height;
  9759. width = Math.round(height * engine.getAspectRatio(camera));
  9760. }
  9761. //Assuming here that "size" parameter is a number
  9762. else if (!isNaN(size)) {
  9763. height = size;
  9764. width = size;
  9765. }
  9766. else {
  9767. Tools.Error("Invalid 'size' parameter !");
  9768. return;
  9769. }
  9770. if (!screenshotCanvas) {
  9771. screenshotCanvas = document.createElement('canvas');
  9772. }
  9773. screenshotCanvas.width = width;
  9774. screenshotCanvas.height = height;
  9775. var renderContext = screenshotCanvas.getContext("2d");
  9776. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9777. var newWidth = width;
  9778. var newHeight = newWidth / ratio;
  9779. if (newHeight > height) {
  9780. newHeight = height;
  9781. newWidth = newHeight * ratio;
  9782. }
  9783. var offsetX = Math.max(0, width - newWidth) / 2;
  9784. var offsetY = Math.max(0, height - newHeight) / 2;
  9785. var renderingCanvas = engine.getRenderingCanvas();
  9786. if (renderContext && renderingCanvas) {
  9787. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9788. }
  9789. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9790. };
  9791. /**
  9792. * Generates an image screenshot from the specified camera.
  9793. *
  9794. * @param engine The engine to use for rendering
  9795. * @param camera The camera to use for rendering
  9796. * @param size This parameter can be set to a single number or to an object with the
  9797. * following (optional) properties: precision, width, height. If a single number is passed,
  9798. * it will be used for both width and height. If an object is passed, the screenshot size
  9799. * will be derived from the parameters. The precision property is a multiplier allowing
  9800. * rendering at a higher or lower resolution.
  9801. * @param successCallback The callback receives a single parameter which contains the
  9802. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9803. * src parameter of an <img> to display it.
  9804. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9805. * Check your browser for supported MIME types.
  9806. * @param samples Texture samples (default: 1)
  9807. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9808. * @param fileName A name for for the downloaded file.
  9809. * @constructor
  9810. */
  9811. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9812. if (mimeType === void 0) { mimeType = "image/png"; }
  9813. if (samples === void 0) { samples = 1; }
  9814. if (antialiasing === void 0) { antialiasing = false; }
  9815. var width;
  9816. var height;
  9817. //If a precision value is specified
  9818. if (size.precision) {
  9819. width = Math.round(engine.getRenderWidth() * size.precision);
  9820. height = Math.round(width / engine.getAspectRatio(camera));
  9821. size = { width: width, height: height };
  9822. }
  9823. else if (size.width && size.height) {
  9824. width = size.width;
  9825. height = size.height;
  9826. }
  9827. //If passing only width, computing height to keep display canvas ratio.
  9828. else if (size.width && !size.height) {
  9829. width = size.width;
  9830. height = Math.round(width / engine.getAspectRatio(camera));
  9831. size = { width: width, height: height };
  9832. }
  9833. //If passing only height, computing width to keep display canvas ratio.
  9834. else if (size.height && !size.width) {
  9835. height = size.height;
  9836. width = Math.round(height * engine.getAspectRatio(camera));
  9837. size = { width: width, height: height };
  9838. }
  9839. //Assuming here that "size" parameter is a number
  9840. else if (!isNaN(size)) {
  9841. height = size;
  9842. width = size;
  9843. }
  9844. else {
  9845. Tools.Error("Invalid 'size' parameter !");
  9846. return;
  9847. }
  9848. var scene = camera.getScene();
  9849. var previousCamera = null;
  9850. if (scene.activeCamera !== camera) {
  9851. previousCamera = scene.activeCamera;
  9852. scene.activeCamera = camera;
  9853. }
  9854. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9855. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9856. texture.renderList = null;
  9857. texture.samples = samples;
  9858. if (antialiasing) {
  9859. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9860. }
  9861. texture.onAfterRenderObservable.add(function () {
  9862. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9863. });
  9864. scene.incrementRenderId();
  9865. scene.resetCachedMaterial();
  9866. texture.render(true);
  9867. texture.dispose();
  9868. if (previousCamera) {
  9869. scene.activeCamera = previousCamera;
  9870. }
  9871. camera.getProjectionMatrix(true); // Force cache refresh;
  9872. };
  9873. // XHR response validator for local file scenario
  9874. Tools.ValidateXHRData = function (xhr, dataType) {
  9875. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9876. if (dataType === void 0) { dataType = 7; }
  9877. try {
  9878. if (dataType & 1) {
  9879. if (xhr.responseText && xhr.responseText.length > 0) {
  9880. return true;
  9881. }
  9882. else if (dataType === 1) {
  9883. return false;
  9884. }
  9885. }
  9886. if (dataType & 2) {
  9887. // Check header width and height since there is no "TGA" magic number
  9888. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9889. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9890. return true;
  9891. }
  9892. else if (dataType === 2) {
  9893. return false;
  9894. }
  9895. }
  9896. if (dataType & 4) {
  9897. // Check for the "DDS" magic number
  9898. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9899. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9900. return true;
  9901. }
  9902. else {
  9903. return false;
  9904. }
  9905. }
  9906. }
  9907. catch (e) {
  9908. // Global protection
  9909. }
  9910. return false;
  9911. };
  9912. /**
  9913. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9914. * Be aware Math.random() could cause collisions, but:
  9915. * "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"
  9916. */
  9917. Tools.RandomId = function () {
  9918. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9919. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9920. return v.toString(16);
  9921. });
  9922. };
  9923. /**
  9924. * Test if the given uri is a base64 string.
  9925. * @param uri The uri to test
  9926. * @return True if the uri is a base64 string or false otherwise.
  9927. */
  9928. Tools.IsBase64 = function (uri) {
  9929. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9930. };
  9931. /**
  9932. * Decode the given base64 uri.
  9933. * @param uri The uri to decode
  9934. * @return The decoded base64 data.
  9935. */
  9936. Tools.DecodeBase64 = function (uri) {
  9937. var decodedString = atob(uri.split(",")[1]);
  9938. var bufferLength = decodedString.length;
  9939. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9940. for (var i = 0; i < bufferLength; i++) {
  9941. bufferView[i] = decodedString.charCodeAt(i);
  9942. }
  9943. return bufferView.buffer;
  9944. };
  9945. Object.defineProperty(Tools, "NoneLogLevel", {
  9946. get: function () {
  9947. return Tools._NoneLogLevel;
  9948. },
  9949. enumerable: true,
  9950. configurable: true
  9951. });
  9952. Object.defineProperty(Tools, "MessageLogLevel", {
  9953. get: function () {
  9954. return Tools._MessageLogLevel;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(Tools, "WarningLogLevel", {
  9960. get: function () {
  9961. return Tools._WarningLogLevel;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(Tools, "ErrorLogLevel", {
  9967. get: function () {
  9968. return Tools._ErrorLogLevel;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. Object.defineProperty(Tools, "AllLogLevel", {
  9974. get: function () {
  9975. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9976. },
  9977. enumerable: true,
  9978. configurable: true
  9979. });
  9980. Tools._AddLogEntry = function (entry) {
  9981. Tools._LogCache = entry + Tools._LogCache;
  9982. if (Tools.OnNewCacheEntry) {
  9983. Tools.OnNewCacheEntry(entry);
  9984. }
  9985. };
  9986. Tools._FormatMessage = function (message) {
  9987. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9988. var date = new Date();
  9989. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9990. };
  9991. Tools._LogDisabled = function (message) {
  9992. // nothing to do
  9993. };
  9994. Tools._LogEnabled = function (message) {
  9995. var formattedMessage = Tools._FormatMessage(message);
  9996. console.log("BJS - " + formattedMessage);
  9997. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9998. Tools._AddLogEntry(entry);
  9999. };
  10000. Tools._WarnDisabled = function (message) {
  10001. // nothing to do
  10002. };
  10003. Tools._WarnEnabled = function (message) {
  10004. var formattedMessage = Tools._FormatMessage(message);
  10005. console.warn("BJS - " + formattedMessage);
  10006. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10007. Tools._AddLogEntry(entry);
  10008. };
  10009. Tools._ErrorDisabled = function (message) {
  10010. // nothing to do
  10011. };
  10012. Tools._ErrorEnabled = function (message) {
  10013. Tools.errorsCount++;
  10014. var formattedMessage = Tools._FormatMessage(message);
  10015. console.error("BJS - " + formattedMessage);
  10016. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10017. Tools._AddLogEntry(entry);
  10018. };
  10019. Object.defineProperty(Tools, "LogCache", {
  10020. get: function () {
  10021. return Tools._LogCache;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Tools.ClearLogCache = function () {
  10027. Tools._LogCache = "";
  10028. Tools.errorsCount = 0;
  10029. };
  10030. Object.defineProperty(Tools, "LogLevels", {
  10031. set: function (level) {
  10032. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10033. Tools.Log = Tools._LogEnabled;
  10034. }
  10035. else {
  10036. Tools.Log = Tools._LogDisabled;
  10037. }
  10038. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10039. Tools.Warn = Tools._WarnEnabled;
  10040. }
  10041. else {
  10042. Tools.Warn = Tools._WarnDisabled;
  10043. }
  10044. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10045. Tools.Error = Tools._ErrorEnabled;
  10046. }
  10047. else {
  10048. Tools.Error = Tools._ErrorDisabled;
  10049. }
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. /**
  10055. * Check if the loaded document was accessed via `file:`-Protocol.
  10056. * @returns boolean
  10057. */
  10058. Tools.IsFileURL = function () {
  10059. return location.protocol === "file:";
  10060. };
  10061. Tools.IsWindowObjectExist = function () {
  10062. return (typeof window) !== "undefined";
  10063. };
  10064. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  10065. get: function () {
  10066. return Tools._PerformanceNoneLogLevel;
  10067. },
  10068. enumerable: true,
  10069. configurable: true
  10070. });
  10071. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  10072. get: function () {
  10073. return Tools._PerformanceUserMarkLogLevel;
  10074. },
  10075. enumerable: true,
  10076. configurable: true
  10077. });
  10078. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  10079. get: function () {
  10080. return Tools._PerformanceConsoleLogLevel;
  10081. },
  10082. enumerable: true,
  10083. configurable: true
  10084. });
  10085. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10086. set: function (level) {
  10087. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10088. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10089. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10090. return;
  10091. }
  10092. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10093. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10094. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10095. return;
  10096. }
  10097. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10098. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10099. },
  10100. enumerable: true,
  10101. configurable: true
  10102. });
  10103. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10104. };
  10105. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10106. };
  10107. Tools._StartUserMark = function (counterName, condition) {
  10108. if (condition === void 0) { condition = true; }
  10109. if (!Tools._performance) {
  10110. if (!Tools.IsWindowObjectExist()) {
  10111. return;
  10112. }
  10113. Tools._performance = window.performance;
  10114. }
  10115. if (!condition || !Tools._performance.mark) {
  10116. return;
  10117. }
  10118. Tools._performance.mark(counterName + "-Begin");
  10119. };
  10120. Tools._EndUserMark = function (counterName, condition) {
  10121. if (condition === void 0) { condition = true; }
  10122. if (!condition || !Tools._performance.mark) {
  10123. return;
  10124. }
  10125. Tools._performance.mark(counterName + "-End");
  10126. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10127. };
  10128. Tools._StartPerformanceConsole = function (counterName, condition) {
  10129. if (condition === void 0) { condition = true; }
  10130. if (!condition) {
  10131. return;
  10132. }
  10133. Tools._StartUserMark(counterName, condition);
  10134. if (console.time) {
  10135. console.time(counterName);
  10136. }
  10137. };
  10138. Tools._EndPerformanceConsole = function (counterName, condition) {
  10139. if (condition === void 0) { condition = true; }
  10140. if (!condition) {
  10141. return;
  10142. }
  10143. Tools._EndUserMark(counterName, condition);
  10144. if (console.time) {
  10145. console.timeEnd(counterName);
  10146. }
  10147. };
  10148. Object.defineProperty(Tools, "Now", {
  10149. get: function () {
  10150. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10151. return window.performance.now();
  10152. }
  10153. return Date.now();
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. /**
  10159. * This method will return the name of the class used to create the instance of the given object.
  10160. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10161. * @param object the object to get the class name from
  10162. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10163. */
  10164. Tools.GetClassName = function (object, isType) {
  10165. if (isType === void 0) { isType = false; }
  10166. var name = null;
  10167. if (!isType && object.getClassName) {
  10168. name = object.getClassName();
  10169. }
  10170. else {
  10171. if (object instanceof Object) {
  10172. var classObj = isType ? object : Object.getPrototypeOf(object);
  10173. name = classObj.constructor["__bjsclassName__"];
  10174. }
  10175. if (!name) {
  10176. name = typeof object;
  10177. }
  10178. }
  10179. return name;
  10180. };
  10181. Tools.First = function (array, predicate) {
  10182. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10183. var el = array_1[_i];
  10184. if (predicate(el)) {
  10185. return el;
  10186. }
  10187. }
  10188. return null;
  10189. };
  10190. /**
  10191. * This method will return the name of the full name of the class, including its owning module (if any).
  10192. * 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).
  10193. * @param object the object to get the class name from
  10194. * @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.
  10195. */
  10196. Tools.getFullClassName = function (object, isType) {
  10197. if (isType === void 0) { isType = false; }
  10198. var className = null;
  10199. var moduleName = null;
  10200. if (!isType && object.getClassName) {
  10201. className = object.getClassName();
  10202. }
  10203. else {
  10204. if (object instanceof Object) {
  10205. var classObj = isType ? object : Object.getPrototypeOf(object);
  10206. className = classObj.constructor["__bjsclassName__"];
  10207. moduleName = classObj.constructor["__bjsmoduleName__"];
  10208. }
  10209. if (!className) {
  10210. className = typeof object;
  10211. }
  10212. }
  10213. if (!className) {
  10214. return null;
  10215. }
  10216. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10217. };
  10218. /**
  10219. * 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.
  10220. * @param array
  10221. */
  10222. Tools.arrayOrStringFeeder = function (array) {
  10223. return function (index) {
  10224. if (index >= array.length) {
  10225. return null;
  10226. }
  10227. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10228. if (val && val.getHashCode) {
  10229. val = val.getHashCode();
  10230. }
  10231. if (typeof val === "string") {
  10232. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10233. }
  10234. return val;
  10235. };
  10236. };
  10237. /**
  10238. * Compute the hashCode of a stream of number
  10239. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10240. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10241. * @return the hash code computed
  10242. */
  10243. Tools.hashCodeFromStream = function (feeder) {
  10244. // Based from here: http://stackoverflow.com/a/7616484/802124
  10245. var hash = 0;
  10246. var index = 0;
  10247. var chr = feeder(index++);
  10248. while (chr != null) {
  10249. hash = ((hash << 5) - hash) + chr;
  10250. hash |= 0; // Convert to 32bit integer
  10251. chr = feeder(index++);
  10252. }
  10253. return hash;
  10254. };
  10255. /**
  10256. * Returns a promise that resolves after the given amount of time.
  10257. * @param delay Number of milliseconds to delay
  10258. * @returns Promise that resolves after the given amount of time
  10259. */
  10260. Tools.DelayAsync = function (delay) {
  10261. return new Promise(function (resolve) {
  10262. setTimeout(function () {
  10263. resolve();
  10264. }, delay);
  10265. });
  10266. };
  10267. /**
  10268. * Gets the current gradient from an array of IValueGradient
  10269. * @param ratio defines the current ratio to get
  10270. * @param gradients defines the array of IValueGradient
  10271. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10272. */
  10273. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10274. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10275. var currentGradient = gradients[gradientIndex];
  10276. var nextGradient = gradients[gradientIndex + 1];
  10277. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10278. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10279. updateFunc(currentGradient, nextGradient, scale);
  10280. return;
  10281. }
  10282. }
  10283. // Use last index if over
  10284. var lastIndex = gradients.length - 1;
  10285. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10286. };
  10287. Tools.BaseUrl = "";
  10288. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10289. /**
  10290. * Default behaviour for cors in the application.
  10291. * It can be a string if the expected behavior is identical in the entire app.
  10292. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10293. */
  10294. Tools.CorsBehavior = "anonymous";
  10295. Tools.UseFallbackTexture = true;
  10296. /**
  10297. * Use this object to register external classes like custom textures or material
  10298. * to allow the laoders to instantiate them
  10299. */
  10300. Tools.RegisteredExternalClasses = {};
  10301. // Used in case of a texture loading problem
  10302. 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";
  10303. Tools._tmpFloatArray = new Float32Array(1);
  10304. Tools.PreprocessUrl = function (url) {
  10305. return url;
  10306. };
  10307. // Logs
  10308. Tools._NoneLogLevel = 0;
  10309. Tools._MessageLogLevel = 1;
  10310. Tools._WarningLogLevel = 2;
  10311. Tools._ErrorLogLevel = 4;
  10312. Tools._LogCache = "";
  10313. Tools.errorsCount = 0;
  10314. Tools.Log = Tools._LogEnabled;
  10315. Tools.Warn = Tools._WarnEnabled;
  10316. Tools.Error = Tools._ErrorEnabled;
  10317. // Performances
  10318. Tools._PerformanceNoneLogLevel = 0;
  10319. Tools._PerformanceUserMarkLogLevel = 1;
  10320. Tools._PerformanceConsoleLogLevel = 2;
  10321. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10322. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10323. return Tools;
  10324. }());
  10325. BABYLON.Tools = Tools;
  10326. /**
  10327. * This class is used to track a performance counter which is number based.
  10328. * The user has access to many properties which give statistics of different nature
  10329. *
  10330. * The implementer can track two kinds of Performance Counter: time and count
  10331. * 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.
  10332. * 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.
  10333. */
  10334. var PerfCounter = /** @class */ (function () {
  10335. function PerfCounter() {
  10336. this._startMonitoringTime = 0;
  10337. this._min = 0;
  10338. this._max = 0;
  10339. this._average = 0;
  10340. this._lastSecAverage = 0;
  10341. this._current = 0;
  10342. this._totalValueCount = 0;
  10343. this._totalAccumulated = 0;
  10344. this._lastSecAccumulated = 0;
  10345. this._lastSecTime = 0;
  10346. this._lastSecValueCount = 0;
  10347. }
  10348. Object.defineProperty(PerfCounter.prototype, "min", {
  10349. /**
  10350. * Returns the smallest value ever
  10351. */
  10352. get: function () {
  10353. return this._min;
  10354. },
  10355. enumerable: true,
  10356. configurable: true
  10357. });
  10358. Object.defineProperty(PerfCounter.prototype, "max", {
  10359. /**
  10360. * Returns the biggest value ever
  10361. */
  10362. get: function () {
  10363. return this._max;
  10364. },
  10365. enumerable: true,
  10366. configurable: true
  10367. });
  10368. Object.defineProperty(PerfCounter.prototype, "average", {
  10369. /**
  10370. * Returns the average value since the performance counter is running
  10371. */
  10372. get: function () {
  10373. return this._average;
  10374. },
  10375. enumerable: true,
  10376. configurable: true
  10377. });
  10378. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10379. /**
  10380. * Returns the average value of the last second the counter was monitored
  10381. */
  10382. get: function () {
  10383. return this._lastSecAverage;
  10384. },
  10385. enumerable: true,
  10386. configurable: true
  10387. });
  10388. Object.defineProperty(PerfCounter.prototype, "current", {
  10389. /**
  10390. * Returns the current value
  10391. */
  10392. get: function () {
  10393. return this._current;
  10394. },
  10395. enumerable: true,
  10396. configurable: true
  10397. });
  10398. Object.defineProperty(PerfCounter.prototype, "total", {
  10399. get: function () {
  10400. return this._totalAccumulated;
  10401. },
  10402. enumerable: true,
  10403. configurable: true
  10404. });
  10405. Object.defineProperty(PerfCounter.prototype, "count", {
  10406. get: function () {
  10407. return this._totalValueCount;
  10408. },
  10409. enumerable: true,
  10410. configurable: true
  10411. });
  10412. /**
  10413. * Call this method to start monitoring a new frame.
  10414. * 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.
  10415. */
  10416. PerfCounter.prototype.fetchNewFrame = function () {
  10417. this._totalValueCount++;
  10418. this._current = 0;
  10419. this._lastSecValueCount++;
  10420. };
  10421. /**
  10422. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10423. * @param newCount the count value to add to the monitored count
  10424. * @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.
  10425. */
  10426. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10427. if (!PerfCounter.Enabled) {
  10428. return;
  10429. }
  10430. this._current += newCount;
  10431. if (fetchResult) {
  10432. this._fetchResult();
  10433. }
  10434. };
  10435. /**
  10436. * Start monitoring this performance counter
  10437. */
  10438. PerfCounter.prototype.beginMonitoring = function () {
  10439. if (!PerfCounter.Enabled) {
  10440. return;
  10441. }
  10442. this._startMonitoringTime = Tools.Now;
  10443. };
  10444. /**
  10445. * Compute the time lapsed since the previous beginMonitoring() call.
  10446. * @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
  10447. */
  10448. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10449. if (newFrame === void 0) { newFrame = true; }
  10450. if (!PerfCounter.Enabled) {
  10451. return;
  10452. }
  10453. if (newFrame) {
  10454. this.fetchNewFrame();
  10455. }
  10456. var currentTime = Tools.Now;
  10457. this._current = currentTime - this._startMonitoringTime;
  10458. if (newFrame) {
  10459. this._fetchResult();
  10460. }
  10461. };
  10462. PerfCounter.prototype._fetchResult = function () {
  10463. this._totalAccumulated += this._current;
  10464. this._lastSecAccumulated += this._current;
  10465. // Min/Max update
  10466. this._min = Math.min(this._min, this._current);
  10467. this._max = Math.max(this._max, this._current);
  10468. this._average = this._totalAccumulated / this._totalValueCount;
  10469. // Reset last sec?
  10470. var now = Tools.Now;
  10471. if ((now - this._lastSecTime) > 1000) {
  10472. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10473. this._lastSecTime = now;
  10474. this._lastSecAccumulated = 0;
  10475. this._lastSecValueCount = 0;
  10476. }
  10477. };
  10478. PerfCounter.Enabled = true;
  10479. return PerfCounter;
  10480. }());
  10481. BABYLON.PerfCounter = PerfCounter;
  10482. /**
  10483. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10484. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10485. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10486. * @param name The name of the class, case should be preserved
  10487. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10488. */
  10489. function className(name, module) {
  10490. return function (target) {
  10491. target["__bjsclassName__"] = name;
  10492. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10493. };
  10494. }
  10495. BABYLON.className = className;
  10496. /**
  10497. * An implementation of a loop for asynchronous functions.
  10498. */
  10499. var AsyncLoop = /** @class */ (function () {
  10500. /**
  10501. * Constructor.
  10502. * @param iterations the number of iterations.
  10503. * @param func the function to run each iteration
  10504. * @param successCallback the callback that will be called upon succesful execution
  10505. * @param offset starting offset.
  10506. */
  10507. function AsyncLoop(
  10508. /**
  10509. * Defines the number of iterations for the loop
  10510. */
  10511. iterations, func, successCallback, offset) {
  10512. if (offset === void 0) { offset = 0; }
  10513. this.iterations = iterations;
  10514. this.index = offset - 1;
  10515. this._done = false;
  10516. this._fn = func;
  10517. this._successCallback = successCallback;
  10518. }
  10519. /**
  10520. * Execute the next iteration. Must be called after the last iteration was finished.
  10521. */
  10522. AsyncLoop.prototype.executeNext = function () {
  10523. if (!this._done) {
  10524. if (this.index + 1 < this.iterations) {
  10525. ++this.index;
  10526. this._fn(this);
  10527. }
  10528. else {
  10529. this.breakLoop();
  10530. }
  10531. }
  10532. };
  10533. /**
  10534. * Break the loop and run the success callback.
  10535. */
  10536. AsyncLoop.prototype.breakLoop = function () {
  10537. this._done = true;
  10538. this._successCallback();
  10539. };
  10540. /**
  10541. * Create and run an async loop.
  10542. * @param iterations the number of iterations.
  10543. * @param fn the function to run each iteration
  10544. * @param successCallback the callback that will be called upon succesful execution
  10545. * @param offset starting offset.
  10546. * @returns the created async loop object
  10547. */
  10548. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  10549. if (offset === void 0) { offset = 0; }
  10550. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  10551. loop.executeNext();
  10552. return loop;
  10553. };
  10554. /**
  10555. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10556. * @param iterations total number of iterations
  10557. * @param syncedIterations number of synchronous iterations in each async iteration.
  10558. * @param fn the function to call each iteration.
  10559. * @param callback a success call back that will be called when iterating stops.
  10560. * @param breakFunction a break condition (optional)
  10561. * @param timeout timeout settings for the setTimeout function. default - 0.
  10562. * @returns the created async loop object
  10563. */
  10564. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10565. if (timeout === void 0) { timeout = 0; }
  10566. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10567. if (breakFunction && breakFunction())
  10568. loop.breakLoop();
  10569. else {
  10570. setTimeout(function () {
  10571. for (var i = 0; i < syncedIterations; ++i) {
  10572. var iteration = (loop.index * syncedIterations) + i;
  10573. if (iteration >= iterations)
  10574. break;
  10575. fn(iteration);
  10576. if (breakFunction && breakFunction()) {
  10577. loop.breakLoop();
  10578. break;
  10579. }
  10580. }
  10581. loop.executeNext();
  10582. }, timeout);
  10583. }
  10584. }, callback);
  10585. };
  10586. return AsyncLoop;
  10587. }());
  10588. BABYLON.AsyncLoop = AsyncLoop;
  10589. })(BABYLON || (BABYLON = {}));
  10590. //# sourceMappingURL=babylon.tools.js.map
  10591. var BABYLON;
  10592. (function (BABYLON) {
  10593. var PromiseStates;
  10594. (function (PromiseStates) {
  10595. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10596. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10597. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10598. })(PromiseStates || (PromiseStates = {}));
  10599. var FulFillmentAgregator = /** @class */ (function () {
  10600. function FulFillmentAgregator() {
  10601. this.count = 0;
  10602. this.target = 0;
  10603. this.results = [];
  10604. }
  10605. return FulFillmentAgregator;
  10606. }());
  10607. var InternalPromise = /** @class */ (function () {
  10608. function InternalPromise(resolver) {
  10609. var _this = this;
  10610. this._state = PromiseStates.Pending;
  10611. this._children = new Array();
  10612. this._rejectWasConsumed = false;
  10613. if (!resolver) {
  10614. return;
  10615. }
  10616. try {
  10617. resolver(function (value) {
  10618. _this._resolve(value);
  10619. }, function (reason) {
  10620. _this._reject(reason);
  10621. });
  10622. }
  10623. catch (e) {
  10624. this._reject(e);
  10625. }
  10626. }
  10627. Object.defineProperty(InternalPromise.prototype, "_result", {
  10628. get: function () {
  10629. return this._resultValue;
  10630. },
  10631. set: function (value) {
  10632. this._resultValue = value;
  10633. if (this._parent && this._parent._result === undefined) {
  10634. this._parent._result = value;
  10635. }
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. InternalPromise.prototype.catch = function (onRejected) {
  10641. return this.then(undefined, onRejected);
  10642. };
  10643. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10644. var _this = this;
  10645. var newPromise = new InternalPromise();
  10646. newPromise._onFulfilled = onFulfilled;
  10647. newPromise._onRejected = onRejected;
  10648. // Composition
  10649. this._children.push(newPromise);
  10650. newPromise._parent = this;
  10651. if (this._state !== PromiseStates.Pending) {
  10652. BABYLON.Tools.SetImmediate(function () {
  10653. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10654. var returnedValue = newPromise._resolve(_this._result);
  10655. if (returnedValue !== undefined && returnedValue !== null) {
  10656. if (returnedValue._state !== undefined) {
  10657. var returnedPromise = returnedValue;
  10658. newPromise._children.push(returnedPromise);
  10659. returnedPromise._parent = newPromise;
  10660. newPromise = returnedPromise;
  10661. }
  10662. else {
  10663. newPromise._result = returnedValue;
  10664. }
  10665. }
  10666. }
  10667. else {
  10668. newPromise._reject(_this._reason);
  10669. }
  10670. });
  10671. }
  10672. return newPromise;
  10673. };
  10674. InternalPromise.prototype._moveChildren = function (children) {
  10675. var _this = this;
  10676. var _a;
  10677. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10678. this._children.forEach(function (child) {
  10679. child._parent = _this;
  10680. });
  10681. if (this._state === PromiseStates.Fulfilled) {
  10682. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10683. var child = _b[_i];
  10684. child._resolve(this._result);
  10685. }
  10686. }
  10687. else if (this._state === PromiseStates.Rejected) {
  10688. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10689. var child = _d[_c];
  10690. child._reject(this._reason);
  10691. }
  10692. }
  10693. };
  10694. InternalPromise.prototype._resolve = function (value) {
  10695. try {
  10696. this._state = PromiseStates.Fulfilled;
  10697. var returnedValue = null;
  10698. if (this._onFulfilled) {
  10699. returnedValue = this._onFulfilled(value);
  10700. }
  10701. if (returnedValue !== undefined && returnedValue !== null) {
  10702. if (returnedValue._state !== undefined) {
  10703. // Transmit children
  10704. var returnedPromise = returnedValue;
  10705. returnedPromise._parent = this;
  10706. returnedPromise._moveChildren(this._children);
  10707. value = returnedPromise._result;
  10708. }
  10709. else {
  10710. value = returnedValue;
  10711. }
  10712. }
  10713. this._result = value;
  10714. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10715. var child = _a[_i];
  10716. child._resolve(value);
  10717. }
  10718. this._children.length = 0;
  10719. delete this._onFulfilled;
  10720. delete this._onRejected;
  10721. }
  10722. catch (e) {
  10723. this._reject(e, true);
  10724. }
  10725. };
  10726. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10727. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10728. this._state = PromiseStates.Rejected;
  10729. this._reason = reason;
  10730. if (this._onRejected && !onLocalThrow) {
  10731. try {
  10732. this._onRejected(reason);
  10733. this._rejectWasConsumed = true;
  10734. }
  10735. catch (e) {
  10736. reason = e;
  10737. }
  10738. }
  10739. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10740. var child = _a[_i];
  10741. if (this._rejectWasConsumed) {
  10742. child._resolve(null);
  10743. }
  10744. else {
  10745. child._reject(reason);
  10746. }
  10747. }
  10748. this._children.length = 0;
  10749. delete this._onFulfilled;
  10750. delete this._onRejected;
  10751. };
  10752. InternalPromise.resolve = function (value) {
  10753. var newPromise = new InternalPromise();
  10754. newPromise._resolve(value);
  10755. return newPromise;
  10756. };
  10757. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10758. promise.then(function (value) {
  10759. agregator.results[index] = value;
  10760. agregator.count++;
  10761. if (agregator.count === agregator.target) {
  10762. agregator.rootPromise._resolve(agregator.results);
  10763. }
  10764. return null;
  10765. }, function (reason) {
  10766. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10767. agregator.rootPromise._reject(reason);
  10768. }
  10769. });
  10770. };
  10771. InternalPromise.all = function (promises) {
  10772. var newPromise = new InternalPromise();
  10773. var agregator = new FulFillmentAgregator();
  10774. agregator.target = promises.length;
  10775. agregator.rootPromise = newPromise;
  10776. if (promises.length) {
  10777. for (var index = 0; index < promises.length; index++) {
  10778. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10779. }
  10780. }
  10781. else {
  10782. newPromise._resolve([]);
  10783. }
  10784. return newPromise;
  10785. };
  10786. InternalPromise.race = function (promises) {
  10787. var newPromise = new InternalPromise();
  10788. if (promises.length) {
  10789. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10790. var promise = promises_1[_i];
  10791. promise.then(function (value) {
  10792. if (newPromise) {
  10793. newPromise._resolve(value);
  10794. newPromise = null;
  10795. }
  10796. return null;
  10797. }, function (reason) {
  10798. if (newPromise) {
  10799. newPromise._reject(reason);
  10800. newPromise = null;
  10801. }
  10802. });
  10803. }
  10804. }
  10805. return newPromise;
  10806. };
  10807. return InternalPromise;
  10808. }());
  10809. /**
  10810. * Helper class that provides a small promise polyfill
  10811. */
  10812. var PromisePolyfill = /** @class */ (function () {
  10813. function PromisePolyfill() {
  10814. }
  10815. /**
  10816. * Static function used to check if the polyfill is required
  10817. * If this is the case then the function will inject the polyfill to window.Promise
  10818. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10819. */
  10820. PromisePolyfill.Apply = function (force) {
  10821. if (force === void 0) { force = false; }
  10822. if (force || typeof Promise === 'undefined') {
  10823. var root = window;
  10824. root.Promise = InternalPromise;
  10825. }
  10826. };
  10827. return PromisePolyfill;
  10828. }());
  10829. BABYLON.PromisePolyfill = PromisePolyfill;
  10830. })(BABYLON || (BABYLON = {}));
  10831. //# sourceMappingURL=babylon.promise.js.map
  10832. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10833. var BABYLON;
  10834. (function (BABYLON) {
  10835. /**
  10836. * Helper class to push actions to a pool of workers.
  10837. */
  10838. var WorkerPool = /** @class */ (function () {
  10839. /**
  10840. * Constructor
  10841. * @param workers Array of workers to use for actions
  10842. */
  10843. function WorkerPool(workers) {
  10844. this._pendingActions = new Array();
  10845. this._workerInfos = workers.map(function (worker) { return ({
  10846. worker: worker,
  10847. active: false
  10848. }); });
  10849. }
  10850. /**
  10851. * Terminates all workers and clears any pending actions.
  10852. */
  10853. WorkerPool.prototype.dispose = function () {
  10854. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10855. var workerInfo = _a[_i];
  10856. workerInfo.worker.terminate();
  10857. }
  10858. delete this._workerInfos;
  10859. delete this._pendingActions;
  10860. };
  10861. /**
  10862. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10863. * pended until a worker has completed its action.
  10864. * @param action The action to perform. Call onComplete when the action is complete.
  10865. */
  10866. WorkerPool.prototype.push = function (action) {
  10867. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10868. var workerInfo = _a[_i];
  10869. if (!workerInfo.active) {
  10870. this._execute(workerInfo, action);
  10871. return;
  10872. }
  10873. }
  10874. this._pendingActions.push(action);
  10875. };
  10876. WorkerPool.prototype._execute = function (workerInfo, action) {
  10877. var _this = this;
  10878. workerInfo.active = true;
  10879. action(workerInfo.worker, function () {
  10880. workerInfo.active = false;
  10881. var nextAction = _this._pendingActions.shift();
  10882. if (nextAction) {
  10883. _this._execute(workerInfo, nextAction);
  10884. }
  10885. });
  10886. };
  10887. return WorkerPool;
  10888. }());
  10889. BABYLON.WorkerPool = WorkerPool;
  10890. })(BABYLON || (BABYLON = {}));
  10891. //# sourceMappingURL=babylon.workerPool.js.map
  10892. var BABYLON;
  10893. (function (BABYLON) {
  10894. /**
  10895. * @hidden
  10896. **/
  10897. var _AlphaState = /** @class */ (function () {
  10898. /**
  10899. * Initializes the state.
  10900. */
  10901. function _AlphaState() {
  10902. this._isAlphaBlendDirty = false;
  10903. this._isBlendFunctionParametersDirty = false;
  10904. this._isBlendEquationParametersDirty = false;
  10905. this._isBlendConstantsDirty = false;
  10906. this._alphaBlend = false;
  10907. this._blendFunctionParameters = new Array(4);
  10908. this._blendEquationParameters = new Array(2);
  10909. this._blendConstants = new Array(4);
  10910. this.reset();
  10911. }
  10912. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10913. get: function () {
  10914. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10920. get: function () {
  10921. return this._alphaBlend;
  10922. },
  10923. set: function (value) {
  10924. if (this._alphaBlend === value) {
  10925. return;
  10926. }
  10927. this._alphaBlend = value;
  10928. this._isAlphaBlendDirty = true;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10934. if (this._blendConstants[0] === r &&
  10935. this._blendConstants[1] === g &&
  10936. this._blendConstants[2] === b &&
  10937. this._blendConstants[3] === a) {
  10938. return;
  10939. }
  10940. this._blendConstants[0] = r;
  10941. this._blendConstants[1] = g;
  10942. this._blendConstants[2] = b;
  10943. this._blendConstants[3] = a;
  10944. this._isBlendConstantsDirty = true;
  10945. };
  10946. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10947. if (this._blendFunctionParameters[0] === value0 &&
  10948. this._blendFunctionParameters[1] === value1 &&
  10949. this._blendFunctionParameters[2] === value2 &&
  10950. this._blendFunctionParameters[3] === value3) {
  10951. return;
  10952. }
  10953. this._blendFunctionParameters[0] = value0;
  10954. this._blendFunctionParameters[1] = value1;
  10955. this._blendFunctionParameters[2] = value2;
  10956. this._blendFunctionParameters[3] = value3;
  10957. this._isBlendFunctionParametersDirty = true;
  10958. };
  10959. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10960. if (this._blendEquationParameters[0] === rgb &&
  10961. this._blendEquationParameters[1] === alpha) {
  10962. return;
  10963. }
  10964. this._blendEquationParameters[0] = rgb;
  10965. this._blendEquationParameters[1] = alpha;
  10966. this._isBlendEquationParametersDirty = true;
  10967. };
  10968. _AlphaState.prototype.reset = function () {
  10969. this._alphaBlend = false;
  10970. this._blendFunctionParameters[0] = null;
  10971. this._blendFunctionParameters[1] = null;
  10972. this._blendFunctionParameters[2] = null;
  10973. this._blendFunctionParameters[3] = null;
  10974. this._blendEquationParameters[0] = null;
  10975. this._blendEquationParameters[1] = null;
  10976. this._blendConstants[0] = null;
  10977. this._blendConstants[1] = null;
  10978. this._blendConstants[2] = null;
  10979. this._blendConstants[3] = null;
  10980. this._isAlphaBlendDirty = true;
  10981. this._isBlendFunctionParametersDirty = false;
  10982. this._isBlendEquationParametersDirty = false;
  10983. this._isBlendConstantsDirty = false;
  10984. };
  10985. _AlphaState.prototype.apply = function (gl) {
  10986. if (!this.isDirty) {
  10987. return;
  10988. }
  10989. // Alpha blend
  10990. if (this._isAlphaBlendDirty) {
  10991. if (this._alphaBlend) {
  10992. gl.enable(gl.BLEND);
  10993. }
  10994. else {
  10995. gl.disable(gl.BLEND);
  10996. }
  10997. this._isAlphaBlendDirty = false;
  10998. }
  10999. // Alpha function
  11000. if (this._isBlendFunctionParametersDirty) {
  11001. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11002. this._isBlendFunctionParametersDirty = false;
  11003. }
  11004. // Alpha equation
  11005. if (this._isBlendEquationParametersDirty) {
  11006. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11007. this._isBlendEquationParametersDirty = false;
  11008. }
  11009. // Constants
  11010. if (this._isBlendConstantsDirty) {
  11011. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11012. this._isBlendConstantsDirty = false;
  11013. }
  11014. };
  11015. return _AlphaState;
  11016. }());
  11017. BABYLON._AlphaState = _AlphaState;
  11018. })(BABYLON || (BABYLON = {}));
  11019. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11020. var BABYLON;
  11021. (function (BABYLON) {
  11022. /**
  11023. * @hidden
  11024. **/
  11025. var _DepthCullingState = /** @class */ (function () {
  11026. /**
  11027. * Initializes the state.
  11028. */
  11029. function _DepthCullingState() {
  11030. this._isDepthTestDirty = false;
  11031. this._isDepthMaskDirty = false;
  11032. this._isDepthFuncDirty = false;
  11033. this._isCullFaceDirty = false;
  11034. this._isCullDirty = false;
  11035. this._isZOffsetDirty = false;
  11036. this._isFrontFaceDirty = false;
  11037. this.reset();
  11038. }
  11039. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11040. get: function () {
  11041. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11047. get: function () {
  11048. return this._zOffset;
  11049. },
  11050. set: function (value) {
  11051. if (this._zOffset === value) {
  11052. return;
  11053. }
  11054. this._zOffset = value;
  11055. this._isZOffsetDirty = true;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11061. get: function () {
  11062. return this._cullFace;
  11063. },
  11064. set: function (value) {
  11065. if (this._cullFace === value) {
  11066. return;
  11067. }
  11068. this._cullFace = value;
  11069. this._isCullFaceDirty = true;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11075. get: function () {
  11076. return this._cull;
  11077. },
  11078. set: function (value) {
  11079. if (this._cull === value) {
  11080. return;
  11081. }
  11082. this._cull = value;
  11083. this._isCullDirty = true;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11089. get: function () {
  11090. return this._depthFunc;
  11091. },
  11092. set: function (value) {
  11093. if (this._depthFunc === value) {
  11094. return;
  11095. }
  11096. this._depthFunc = value;
  11097. this._isDepthFuncDirty = true;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11103. get: function () {
  11104. return this._depthMask;
  11105. },
  11106. set: function (value) {
  11107. if (this._depthMask === value) {
  11108. return;
  11109. }
  11110. this._depthMask = value;
  11111. this._isDepthMaskDirty = true;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11117. get: function () {
  11118. return this._depthTest;
  11119. },
  11120. set: function (value) {
  11121. if (this._depthTest === value) {
  11122. return;
  11123. }
  11124. this._depthTest = value;
  11125. this._isDepthTestDirty = true;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11131. get: function () {
  11132. return this._frontFace;
  11133. },
  11134. set: function (value) {
  11135. if (this._frontFace === value) {
  11136. return;
  11137. }
  11138. this._frontFace = value;
  11139. this._isFrontFaceDirty = true;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. _DepthCullingState.prototype.reset = function () {
  11145. this._depthMask = true;
  11146. this._depthTest = true;
  11147. this._depthFunc = null;
  11148. this._cullFace = null;
  11149. this._cull = null;
  11150. this._zOffset = 0;
  11151. this._frontFace = null;
  11152. this._isDepthTestDirty = true;
  11153. this._isDepthMaskDirty = true;
  11154. this._isDepthFuncDirty = false;
  11155. this._isCullFaceDirty = false;
  11156. this._isCullDirty = false;
  11157. this._isZOffsetDirty = false;
  11158. this._isFrontFaceDirty = false;
  11159. };
  11160. _DepthCullingState.prototype.apply = function (gl) {
  11161. if (!this.isDirty) {
  11162. return;
  11163. }
  11164. // Cull
  11165. if (this._isCullDirty) {
  11166. if (this.cull) {
  11167. gl.enable(gl.CULL_FACE);
  11168. }
  11169. else {
  11170. gl.disable(gl.CULL_FACE);
  11171. }
  11172. this._isCullDirty = false;
  11173. }
  11174. // Cull face
  11175. if (this._isCullFaceDirty) {
  11176. gl.cullFace(this.cullFace);
  11177. this._isCullFaceDirty = false;
  11178. }
  11179. // Depth mask
  11180. if (this._isDepthMaskDirty) {
  11181. gl.depthMask(this.depthMask);
  11182. this._isDepthMaskDirty = false;
  11183. }
  11184. // Depth test
  11185. if (this._isDepthTestDirty) {
  11186. if (this.depthTest) {
  11187. gl.enable(gl.DEPTH_TEST);
  11188. }
  11189. else {
  11190. gl.disable(gl.DEPTH_TEST);
  11191. }
  11192. this._isDepthTestDirty = false;
  11193. }
  11194. // Depth func
  11195. if (this._isDepthFuncDirty) {
  11196. gl.depthFunc(this.depthFunc);
  11197. this._isDepthFuncDirty = false;
  11198. }
  11199. // zOffset
  11200. if (this._isZOffsetDirty) {
  11201. if (this.zOffset) {
  11202. gl.enable(gl.POLYGON_OFFSET_FILL);
  11203. gl.polygonOffset(this.zOffset, 0);
  11204. }
  11205. else {
  11206. gl.disable(gl.POLYGON_OFFSET_FILL);
  11207. }
  11208. this._isZOffsetDirty = false;
  11209. }
  11210. // Front face
  11211. if (this._isFrontFaceDirty) {
  11212. gl.frontFace(this.frontFace);
  11213. this._isFrontFaceDirty = false;
  11214. }
  11215. };
  11216. return _DepthCullingState;
  11217. }());
  11218. BABYLON._DepthCullingState = _DepthCullingState;
  11219. })(BABYLON || (BABYLON = {}));
  11220. //# sourceMappingURL=babylon.depthCullingState.js.map
  11221. var BABYLON;
  11222. (function (BABYLON) {
  11223. /**
  11224. * @hidden
  11225. **/
  11226. var _StencilState = /** @class */ (function () {
  11227. function _StencilState() {
  11228. this._isStencilTestDirty = false;
  11229. this._isStencilMaskDirty = false;
  11230. this._isStencilFuncDirty = false;
  11231. this._isStencilOpDirty = false;
  11232. this.reset();
  11233. }
  11234. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11235. get: function () {
  11236. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11237. },
  11238. enumerable: true,
  11239. configurable: true
  11240. });
  11241. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11242. get: function () {
  11243. return this._stencilFunc;
  11244. },
  11245. set: function (value) {
  11246. if (this._stencilFunc === value) {
  11247. return;
  11248. }
  11249. this._stencilFunc = value;
  11250. this._isStencilFuncDirty = true;
  11251. },
  11252. enumerable: true,
  11253. configurable: true
  11254. });
  11255. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11256. get: function () {
  11257. return this._stencilFuncRef;
  11258. },
  11259. set: function (value) {
  11260. if (this._stencilFuncRef === value) {
  11261. return;
  11262. }
  11263. this._stencilFuncRef = value;
  11264. this._isStencilFuncDirty = true;
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11270. get: function () {
  11271. return this._stencilFuncMask;
  11272. },
  11273. set: function (value) {
  11274. if (this._stencilFuncMask === value) {
  11275. return;
  11276. }
  11277. this._stencilFuncMask = value;
  11278. this._isStencilFuncDirty = true;
  11279. },
  11280. enumerable: true,
  11281. configurable: true
  11282. });
  11283. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11284. get: function () {
  11285. return this._stencilOpStencilFail;
  11286. },
  11287. set: function (value) {
  11288. if (this._stencilOpStencilFail === value) {
  11289. return;
  11290. }
  11291. this._stencilOpStencilFail = value;
  11292. this._isStencilOpDirty = true;
  11293. },
  11294. enumerable: true,
  11295. configurable: true
  11296. });
  11297. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11298. get: function () {
  11299. return this._stencilOpDepthFail;
  11300. },
  11301. set: function (value) {
  11302. if (this._stencilOpDepthFail === value) {
  11303. return;
  11304. }
  11305. this._stencilOpDepthFail = value;
  11306. this._isStencilOpDirty = true;
  11307. },
  11308. enumerable: true,
  11309. configurable: true
  11310. });
  11311. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11312. get: function () {
  11313. return this._stencilOpStencilDepthPass;
  11314. },
  11315. set: function (value) {
  11316. if (this._stencilOpStencilDepthPass === value) {
  11317. return;
  11318. }
  11319. this._stencilOpStencilDepthPass = value;
  11320. this._isStencilOpDirty = true;
  11321. },
  11322. enumerable: true,
  11323. configurable: true
  11324. });
  11325. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11326. get: function () {
  11327. return this._stencilMask;
  11328. },
  11329. set: function (value) {
  11330. if (this._stencilMask === value) {
  11331. return;
  11332. }
  11333. this._stencilMask = value;
  11334. this._isStencilMaskDirty = true;
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11340. get: function () {
  11341. return this._stencilTest;
  11342. },
  11343. set: function (value) {
  11344. if (this._stencilTest === value) {
  11345. return;
  11346. }
  11347. this._stencilTest = value;
  11348. this._isStencilTestDirty = true;
  11349. },
  11350. enumerable: true,
  11351. configurable: true
  11352. });
  11353. _StencilState.prototype.reset = function () {
  11354. this._stencilTest = false;
  11355. this._stencilMask = 0xFF;
  11356. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11357. this._stencilFuncRef = 1;
  11358. this._stencilFuncMask = 0xFF;
  11359. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11360. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11361. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11362. this._isStencilTestDirty = true;
  11363. this._isStencilMaskDirty = true;
  11364. this._isStencilFuncDirty = true;
  11365. this._isStencilOpDirty = true;
  11366. };
  11367. _StencilState.prototype.apply = function (gl) {
  11368. if (!this.isDirty) {
  11369. return;
  11370. }
  11371. // Stencil test
  11372. if (this._isStencilTestDirty) {
  11373. if (this.stencilTest) {
  11374. gl.enable(gl.STENCIL_TEST);
  11375. }
  11376. else {
  11377. gl.disable(gl.STENCIL_TEST);
  11378. }
  11379. this._isStencilTestDirty = false;
  11380. }
  11381. // Stencil mask
  11382. if (this._isStencilMaskDirty) {
  11383. gl.stencilMask(this.stencilMask);
  11384. this._isStencilMaskDirty = false;
  11385. }
  11386. // Stencil func
  11387. if (this._isStencilFuncDirty) {
  11388. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11389. this._isStencilFuncDirty = false;
  11390. }
  11391. // Stencil op
  11392. if (this._isStencilOpDirty) {
  11393. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11394. this._isStencilOpDirty = false;
  11395. }
  11396. };
  11397. return _StencilState;
  11398. }());
  11399. BABYLON._StencilState = _StencilState;
  11400. })(BABYLON || (BABYLON = {}));
  11401. //# sourceMappingURL=babylon.stencilState.js.map
  11402. var __assign = (this && this.__assign) || function () {
  11403. __assign = Object.assign || function(t) {
  11404. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11405. s = arguments[i];
  11406. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11407. t[p] = s[p];
  11408. }
  11409. return t;
  11410. };
  11411. return __assign.apply(this, arguments);
  11412. };
  11413. var BABYLON;
  11414. (function (BABYLON) {
  11415. /**
  11416. * Keeps track of all the buffer info used in engine.
  11417. */
  11418. var BufferPointer = /** @class */ (function () {
  11419. function BufferPointer() {
  11420. }
  11421. return BufferPointer;
  11422. }());
  11423. /**
  11424. * Interface for attribute information associated with buffer instanciation
  11425. */
  11426. var InstancingAttributeInfo = /** @class */ (function () {
  11427. function InstancingAttributeInfo() {
  11428. }
  11429. return InstancingAttributeInfo;
  11430. }());
  11431. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11432. /**
  11433. * Define options used to create a render target texture
  11434. */
  11435. var RenderTargetCreationOptions = /** @class */ (function () {
  11436. function RenderTargetCreationOptions() {
  11437. }
  11438. return RenderTargetCreationOptions;
  11439. }());
  11440. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11441. /**
  11442. * Define options used to create a depth texture
  11443. */
  11444. var DepthTextureCreationOptions = /** @class */ (function () {
  11445. function DepthTextureCreationOptions() {
  11446. }
  11447. return DepthTextureCreationOptions;
  11448. }());
  11449. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11450. /**
  11451. * Class used to describe the capabilities of the engine relatively to the current browser
  11452. */
  11453. var EngineCapabilities = /** @class */ (function () {
  11454. function EngineCapabilities() {
  11455. }
  11456. return EngineCapabilities;
  11457. }());
  11458. BABYLON.EngineCapabilities = EngineCapabilities;
  11459. /**
  11460. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11461. */
  11462. var Engine = /** @class */ (function () {
  11463. /**
  11464. * Creates a new engine
  11465. * @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
  11466. * @param antialias defines enable antialiasing (default: false)
  11467. * @param options defines further options to be sent to the getContext() function
  11468. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11469. */
  11470. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11471. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11472. var _this = this;
  11473. // Public members
  11474. /**
  11475. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11476. */
  11477. this.forcePOTTextures = false;
  11478. /**
  11479. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11480. */
  11481. this.isFullscreen = false;
  11482. /**
  11483. * Gets a boolean indicating if the pointer is currently locked
  11484. */
  11485. this.isPointerLock = false;
  11486. /**
  11487. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11488. */
  11489. this.cullBackFaces = true;
  11490. /**
  11491. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11492. */
  11493. this.renderEvenInBackground = true;
  11494. /**
  11495. * Gets or sets a boolean indicating that cache can be kept between frames
  11496. */
  11497. this.preventCacheWipeBetweenFrames = false;
  11498. /**
  11499. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11500. **/
  11501. this.enableOfflineSupport = false;
  11502. /**
  11503. * 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)
  11504. **/
  11505. this.disableManifestCheck = false;
  11506. /**
  11507. * Gets the list of created scenes
  11508. */
  11509. this.scenes = new Array();
  11510. /**
  11511. * Gets the list of created postprocesses
  11512. */
  11513. this.postProcesses = new Array();
  11514. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11515. this.validateShaderPrograms = false;
  11516. // Observables
  11517. /**
  11518. * Observable event triggered each time the rendering canvas is resized
  11519. */
  11520. this.onResizeObservable = new BABYLON.Observable();
  11521. /**
  11522. * Observable event triggered each time the canvas loses focus
  11523. */
  11524. this.onCanvasBlurObservable = new BABYLON.Observable();
  11525. /**
  11526. * Observable event triggered each time the canvas gains focus
  11527. */
  11528. this.onCanvasFocusObservable = new BABYLON.Observable();
  11529. /**
  11530. * Observable event triggered each time the canvas receives pointerout event
  11531. */
  11532. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11533. /**
  11534. * Observable event triggered before each texture is initialized
  11535. */
  11536. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11537. //WebVR
  11538. this._vrDisplay = undefined;
  11539. this._vrSupported = false;
  11540. this._vrExclusivePointerMode = false;
  11541. // Uniform buffers list
  11542. /**
  11543. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11544. */
  11545. this.disableUniformBuffers = false;
  11546. /** @hidden */
  11547. this._uniformBuffers = new Array();
  11548. // Observables
  11549. /**
  11550. * Observable raised when the engine begins a new frame
  11551. */
  11552. this.onBeginFrameObservable = new BABYLON.Observable();
  11553. /**
  11554. * Observable raised when the engine ends the current frame
  11555. */
  11556. this.onEndFrameObservable = new BABYLON.Observable();
  11557. /**
  11558. * Observable raised when the engine is about to compile a shader
  11559. */
  11560. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11561. /**
  11562. * Observable raised when the engine has jsut compiled a shader
  11563. */
  11564. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11565. this._windowIsBackground = false;
  11566. this._webGLVersion = 1.0;
  11567. /** @hidden */
  11568. this._badOS = false;
  11569. /** @hidden */
  11570. this._badDesktopOS = false;
  11571. /**
  11572. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11573. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11574. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11575. */
  11576. this.disableTextureBindingOptimization = false;
  11577. /**
  11578. * Observable signaled when VR display mode changes
  11579. */
  11580. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11581. /**
  11582. * Observable signaled when VR request present is complete
  11583. */
  11584. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11585. /**
  11586. * Observable signaled when VR request present starts
  11587. */
  11588. this.onVRRequestPresentStart = new BABYLON.Observable();
  11589. this._colorWrite = true;
  11590. /** @hidden */
  11591. this._drawCalls = new BABYLON.PerfCounter();
  11592. /** @hidden */
  11593. this._textureCollisions = new BABYLON.PerfCounter();
  11594. this._renderingQueueLaunched = false;
  11595. this._activeRenderLoops = new Array();
  11596. // Deterministic lockstepMaxSteps
  11597. this._deterministicLockstep = false;
  11598. this._lockstepMaxSteps = 4;
  11599. // Lost context
  11600. /**
  11601. * Observable signaled when a context lost event is raised
  11602. */
  11603. this.onContextLostObservable = new BABYLON.Observable();
  11604. /**
  11605. * Observable signaled when a context restored event is raised
  11606. */
  11607. this.onContextRestoredObservable = new BABYLON.Observable();
  11608. this._contextWasLost = false;
  11609. this._doNotHandleContextLost = false;
  11610. // FPS
  11611. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11612. this._fps = 60;
  11613. this._deltaTime = 0;
  11614. /**
  11615. * Turn this value on if you want to pause FPS computation when in background
  11616. */
  11617. this.disablePerformanceMonitorInBackground = false;
  11618. // States
  11619. /** @hidden */
  11620. this._depthCullingState = new BABYLON._DepthCullingState();
  11621. /** @hidden */
  11622. this._stencilState = new BABYLON._StencilState();
  11623. /** @hidden */
  11624. this._alphaState = new BABYLON._AlphaState();
  11625. /** @hidden */
  11626. this._alphaMode = Engine.ALPHA_DISABLE;
  11627. // Cache
  11628. this._internalTexturesCache = new Array();
  11629. /** @hidden */
  11630. this._activeChannel = 0;
  11631. this._currentTextureChannel = -1;
  11632. /** @hidden */
  11633. this._boundTexturesCache = {};
  11634. this._compiledEffects = {};
  11635. this._vertexAttribArraysEnabled = [];
  11636. this._uintIndicesCurrentlySet = false;
  11637. this._currentBoundBuffer = new Array();
  11638. /** @hidden */
  11639. this._currentFramebuffer = null;
  11640. this._currentBufferPointers = new Array();
  11641. this._currentInstanceLocations = new Array();
  11642. this._currentInstanceBuffers = new Array();
  11643. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11644. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11645. this._vaoRecordInProgress = false;
  11646. this._mustWipeVertexAttributes = false;
  11647. this._nextFreeTextureSlots = new Array();
  11648. this._maxSimultaneousTextures = 0;
  11649. this._activeRequests = new Array();
  11650. // Hardware supported Compressed Textures
  11651. this._texturesSupported = new Array();
  11652. /**
  11653. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11654. */
  11655. this.premultipliedAlpha = true;
  11656. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11657. this._onVRFullScreenTriggered = function () {
  11658. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11659. //get the old size before we change
  11660. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11661. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11662. //get the width and height, change the render size
  11663. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11664. _this.setHardwareScalingLevel(1);
  11665. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11666. }
  11667. else {
  11668. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11669. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11670. }
  11671. };
  11672. this._unpackFlipYCached = null;
  11673. /**
  11674. * In case you are sharing the context with other applications, it might
  11675. * be interested to not cache the unpack flip y state to ensure a consistent
  11676. * value would be set.
  11677. */
  11678. this.enableUnpackFlipYCached = true;
  11679. this._boundUniforms = {};
  11680. // Register promises
  11681. BABYLON.PromisePolyfill.Apply();
  11682. var canvas = null;
  11683. Engine.Instances.push(this);
  11684. if (!canvasOrContext) {
  11685. return;
  11686. }
  11687. options = options || {};
  11688. if (canvasOrContext.getContext) {
  11689. canvas = canvasOrContext;
  11690. this._renderingCanvas = canvas;
  11691. if (antialias != null) {
  11692. options.antialias = antialias;
  11693. }
  11694. if (options.deterministicLockstep === undefined) {
  11695. options.deterministicLockstep = false;
  11696. }
  11697. if (options.lockstepMaxSteps === undefined) {
  11698. options.lockstepMaxSteps = 4;
  11699. }
  11700. if (options.preserveDrawingBuffer === undefined) {
  11701. options.preserveDrawingBuffer = false;
  11702. }
  11703. if (options.audioEngine === undefined) {
  11704. options.audioEngine = true;
  11705. }
  11706. if (options.stencil === undefined) {
  11707. options.stencil = true;
  11708. }
  11709. if (options.premultipliedAlpha === false) {
  11710. this.premultipliedAlpha = false;
  11711. }
  11712. this._deterministicLockstep = options.deterministicLockstep;
  11713. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11714. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11715. // Exceptions
  11716. if (navigator && navigator.userAgent) {
  11717. var ua = navigator.userAgent;
  11718. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11719. var exception = _a[_i];
  11720. var key = exception.key;
  11721. var targets = exception.targets;
  11722. if (ua.indexOf(key) > -1) {
  11723. if (exception.capture && exception.captureConstraint) {
  11724. var capture = exception.capture;
  11725. var constraint = exception.captureConstraint;
  11726. var regex = new RegExp(capture);
  11727. var matches = regex.exec(ua);
  11728. if (matches && matches.length > 0) {
  11729. var capturedValue = parseInt(matches[matches.length - 1]);
  11730. if (capturedValue >= constraint) {
  11731. continue;
  11732. }
  11733. }
  11734. }
  11735. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11736. var target = targets_1[_b];
  11737. switch (target) {
  11738. case "uniformBuffer":
  11739. this.disableUniformBuffers = true;
  11740. break;
  11741. case "textureBindingOptimization":
  11742. this.disableTextureBindingOptimization = true;
  11743. break;
  11744. }
  11745. }
  11746. }
  11747. }
  11748. }
  11749. // GL
  11750. if (!options.disableWebGL2Support) {
  11751. try {
  11752. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11753. if (this._gl) {
  11754. this._webGLVersion = 2.0;
  11755. }
  11756. }
  11757. catch (e) {
  11758. // Do nothing
  11759. }
  11760. }
  11761. if (!this._gl) {
  11762. if (!canvas) {
  11763. throw new Error("The provided canvas is null or undefined.");
  11764. }
  11765. try {
  11766. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11767. }
  11768. catch (e) {
  11769. throw new Error("WebGL not supported");
  11770. }
  11771. }
  11772. if (!this._gl) {
  11773. throw new Error("WebGL not supported");
  11774. }
  11775. this._onCanvasFocus = function () {
  11776. _this.onCanvasFocusObservable.notifyObservers(_this);
  11777. };
  11778. this._onCanvasBlur = function () {
  11779. _this.onCanvasBlurObservable.notifyObservers(_this);
  11780. };
  11781. canvas.addEventListener("focus", this._onCanvasFocus);
  11782. canvas.addEventListener("blur", this._onCanvasBlur);
  11783. this._onBlur = function () {
  11784. if (_this.disablePerformanceMonitorInBackground) {
  11785. _this._performanceMonitor.disable();
  11786. }
  11787. _this._windowIsBackground = true;
  11788. };
  11789. this._onFocus = function () {
  11790. if (_this.disablePerformanceMonitorInBackground) {
  11791. _this._performanceMonitor.enable();
  11792. }
  11793. _this._windowIsBackground = false;
  11794. };
  11795. this._onCanvasPointerOut = function (ev) {
  11796. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11797. };
  11798. window.addEventListener("blur", this._onBlur);
  11799. window.addEventListener("focus", this._onFocus);
  11800. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11801. // Context lost
  11802. if (!this._doNotHandleContextLost) {
  11803. this._onContextLost = function (evt) {
  11804. evt.preventDefault();
  11805. _this._contextWasLost = true;
  11806. BABYLON.Tools.Warn("WebGL context lost.");
  11807. _this.onContextLostObservable.notifyObservers(_this);
  11808. };
  11809. this._onContextRestored = function (evt) {
  11810. // Adding a timeout to avoid race condition at browser level
  11811. setTimeout(function () {
  11812. // Rebuild gl context
  11813. _this._initGLContext();
  11814. // Rebuild effects
  11815. _this._rebuildEffects();
  11816. // Rebuild textures
  11817. _this._rebuildInternalTextures();
  11818. // Rebuild buffers
  11819. _this._rebuildBuffers();
  11820. // Cache
  11821. _this.wipeCaches(true);
  11822. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11823. _this.onContextRestoredObservable.notifyObservers(_this);
  11824. _this._contextWasLost = false;
  11825. }, 0);
  11826. };
  11827. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11828. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11829. }
  11830. }
  11831. else {
  11832. this._gl = canvasOrContext;
  11833. this._renderingCanvas = this._gl.canvas;
  11834. if (this._gl.renderbufferStorageMultisample) {
  11835. this._webGLVersion = 2.0;
  11836. }
  11837. options.stencil = this._gl.getContextAttributes().stencil;
  11838. }
  11839. // Viewport
  11840. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11841. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11842. this.resize();
  11843. this._isStencilEnable = options.stencil ? true : false;
  11844. this._initGLContext();
  11845. if (canvas) {
  11846. // Fullscreen
  11847. this._onFullscreenChange = function () {
  11848. if (document.fullscreen !== undefined) {
  11849. _this.isFullscreen = document.fullscreen;
  11850. }
  11851. else if (document.mozFullScreen !== undefined) {
  11852. _this.isFullscreen = document.mozFullScreen;
  11853. }
  11854. else if (document.webkitIsFullScreen !== undefined) {
  11855. _this.isFullscreen = document.webkitIsFullScreen;
  11856. }
  11857. else if (document.msIsFullScreen !== undefined) {
  11858. _this.isFullscreen = document.msIsFullScreen;
  11859. }
  11860. // Pointer lock
  11861. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11862. canvas.requestPointerLock = canvas.requestPointerLock ||
  11863. canvas.msRequestPointerLock ||
  11864. canvas.mozRequestPointerLock ||
  11865. canvas.webkitRequestPointerLock;
  11866. if (canvas.requestPointerLock) {
  11867. canvas.requestPointerLock();
  11868. }
  11869. }
  11870. };
  11871. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11872. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11873. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11874. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11875. // Pointer lock
  11876. this._onPointerLockChange = function () {
  11877. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11878. document.webkitPointerLockElement === canvas ||
  11879. document.msPointerLockElement === canvas ||
  11880. document.pointerLockElement === canvas);
  11881. };
  11882. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11883. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11884. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11885. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11886. this._onVRDisplayPointerRestricted = function () {
  11887. if (canvas) {
  11888. canvas.requestPointerLock();
  11889. }
  11890. };
  11891. this._onVRDisplayPointerUnrestricted = function () {
  11892. document.exitPointerLock();
  11893. };
  11894. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11895. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11896. }
  11897. // Create Audio Engine if needed.
  11898. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11899. Engine.audioEngine = Engine.AudioEngineFactory(this);
  11900. }
  11901. // Prepare buffer pointers
  11902. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11903. this._currentBufferPointers[i] = new BufferPointer();
  11904. }
  11905. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11906. // Load WebVR Devices
  11907. if (options.autoEnableWebVR) {
  11908. this.initWebVR();
  11909. }
  11910. // Detect if we are running on a faulty buggy OS.
  11911. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11912. // Detect if we are running on a faulty buggy desktop OS.
  11913. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11914. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11915. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11916. }
  11917. Object.defineProperty(Engine, "LastCreatedEngine", {
  11918. /**
  11919. * Gets the latest created engine
  11920. */
  11921. get: function () {
  11922. if (Engine.Instances.length === 0) {
  11923. return null;
  11924. }
  11925. return Engine.Instances[Engine.Instances.length - 1];
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "LastCreatedScene", {
  11931. /**
  11932. * Gets the latest created scene
  11933. */
  11934. get: function () {
  11935. var lastCreatedEngine = Engine.LastCreatedEngine;
  11936. if (!lastCreatedEngine) {
  11937. return null;
  11938. }
  11939. if (lastCreatedEngine.scenes.length === 0) {
  11940. return null;
  11941. }
  11942. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. /**
  11948. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11949. * @param flag defines which part of the materials must be marked as dirty
  11950. * @param predicate defines a predicate used to filter which materials should be affected
  11951. */
  11952. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11953. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11954. var engine = Engine.Instances[engineIndex];
  11955. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11956. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11957. }
  11958. }
  11959. };
  11960. Object.defineProperty(Engine, "Version", {
  11961. /**
  11962. * Returns the current version of the framework
  11963. */
  11964. get: function () {
  11965. return "3.3.0-rc.1";
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11971. /**
  11972. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11973. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11974. */
  11975. get: function () {
  11976. return this._vrExclusivePointerMode;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11982. /**
  11983. * Gets a boolean indicating that the engine supports uniform buffers
  11984. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11985. */
  11986. get: function () {
  11987. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11993. /**
  11994. * Gets a boolean indicating that only power of 2 textures are supported
  11995. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11996. */
  11997. get: function () {
  11998. return this._webGLVersion < 2 || this.forcePOTTextures;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12004. /**
  12005. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12006. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12007. */
  12008. get: function () {
  12009. return this._doNotHandleContextLost;
  12010. },
  12011. set: function (value) {
  12012. this._doNotHandleContextLost = value;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12018. /**
  12019. * Gets the performance monitor attached to this engine
  12020. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12021. */
  12022. get: function () {
  12023. return this._performanceMonitor;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12029. /**
  12030. * Gets the list of texture formats supported
  12031. */
  12032. get: function () {
  12033. return this._texturesSupported;
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12039. /**
  12040. * Gets the list of texture formats in use
  12041. */
  12042. get: function () {
  12043. return this._textureFormatInUse;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine.prototype, "currentViewport", {
  12049. /**
  12050. * Gets the current viewport
  12051. */
  12052. get: function () {
  12053. return this._cachedViewport;
  12054. },
  12055. enumerable: true,
  12056. configurable: true
  12057. });
  12058. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12059. /**
  12060. * Gets the default empty texture
  12061. */
  12062. get: function () {
  12063. if (!this._emptyTexture) {
  12064. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12065. }
  12066. return this._emptyTexture;
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12072. /**
  12073. * Gets the default empty 3D texture
  12074. */
  12075. get: function () {
  12076. if (!this._emptyTexture3D) {
  12077. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12078. }
  12079. return this._emptyTexture3D;
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12085. /**
  12086. * Gets the default empty cube texture
  12087. */
  12088. get: function () {
  12089. if (!this._emptyCubeTexture) {
  12090. var faceData = new Uint8Array(4);
  12091. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12092. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12093. }
  12094. return this._emptyCubeTexture;
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Engine.prototype._rebuildInternalTextures = function () {
  12100. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12101. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12102. var internalTexture = currentState_1[_i];
  12103. internalTexture._rebuild();
  12104. }
  12105. };
  12106. Engine.prototype._rebuildEffects = function () {
  12107. for (var key in this._compiledEffects) {
  12108. var effect = this._compiledEffects[key];
  12109. effect._prepareEffect();
  12110. }
  12111. BABYLON.Effect.ResetCache();
  12112. };
  12113. Engine.prototype._rebuildBuffers = function () {
  12114. // Index / Vertex
  12115. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12116. var scene = _a[_i];
  12117. scene.resetCachedMaterial();
  12118. scene._rebuildGeometries();
  12119. scene._rebuildTextures();
  12120. }
  12121. // Uniforms
  12122. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12123. var uniformBuffer = _c[_b];
  12124. uniformBuffer._rebuild();
  12125. }
  12126. };
  12127. Engine.prototype._initGLContext = function () {
  12128. // Caps
  12129. this._caps = new EngineCapabilities();
  12130. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12131. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12132. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12133. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12134. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12135. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12136. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12137. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12138. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12139. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12140. // Infos
  12141. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12142. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12143. if (rendererInfo != null) {
  12144. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12145. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12146. }
  12147. if (!this._glVendor) {
  12148. this._glVendor = "Unknown vendor";
  12149. }
  12150. if (!this._glRenderer) {
  12151. this._glRenderer = "Unknown renderer";
  12152. }
  12153. // Constants
  12154. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12155. if (this._gl.RGBA16F !== 0x881A) {
  12156. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12157. }
  12158. if (this._gl.RGBA32F !== 0x8814) {
  12159. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12160. }
  12161. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12162. this._gl.DEPTH24_STENCIL8 = 35056;
  12163. }
  12164. // Extensions
  12165. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12166. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12167. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12168. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12169. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12170. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12171. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12172. 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');
  12173. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12174. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12175. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12176. this._caps.highPrecisionShaderSupported = true;
  12177. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12178. if (this._caps.timerQuery) {
  12179. if (this._webGLVersion === 1) {
  12180. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12181. }
  12182. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12183. }
  12184. // Checks if some of the format renders first to allow the use of webgl inspector.
  12185. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12186. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12187. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12188. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12189. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12190. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12191. if (this._webGLVersion > 1) {
  12192. this._gl.HALF_FLOAT_OES = 0x140B;
  12193. }
  12194. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12195. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12196. // Draw buffers
  12197. if (this._webGLVersion > 1) {
  12198. this._caps.drawBuffersExtension = true;
  12199. }
  12200. else {
  12201. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12202. if (drawBuffersExtension !== null) {
  12203. this._caps.drawBuffersExtension = true;
  12204. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12205. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12206. for (var i = 0; i < 16; i++) {
  12207. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12208. }
  12209. }
  12210. else {
  12211. this._caps.drawBuffersExtension = false;
  12212. }
  12213. }
  12214. // Depth Texture
  12215. if (this._webGLVersion > 1) {
  12216. this._caps.depthTextureExtension = true;
  12217. }
  12218. else {
  12219. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12220. if (depthTextureExtension != null) {
  12221. this._caps.depthTextureExtension = true;
  12222. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12223. }
  12224. }
  12225. // Vertex array object
  12226. if (this._webGLVersion > 1) {
  12227. this._caps.vertexArrayObject = true;
  12228. }
  12229. else {
  12230. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12231. if (vertexArrayObjectExtension != null) {
  12232. this._caps.vertexArrayObject = true;
  12233. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12234. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12235. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12236. }
  12237. else {
  12238. this._caps.vertexArrayObject = false;
  12239. }
  12240. }
  12241. // Instances count
  12242. if (this._webGLVersion > 1) {
  12243. this._caps.instancedArrays = true;
  12244. }
  12245. else {
  12246. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12247. if (instanceExtension != null) {
  12248. this._caps.instancedArrays = true;
  12249. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12250. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12251. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12252. }
  12253. else {
  12254. this._caps.instancedArrays = false;
  12255. }
  12256. }
  12257. // Intelligently add supported compressed formats in order to check for.
  12258. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12259. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12260. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12261. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12262. if (this._caps.astc)
  12263. this.texturesSupported.push('-astc.ktx');
  12264. if (this._caps.s3tc)
  12265. this.texturesSupported.push('-dxt.ktx');
  12266. if (this._caps.pvrtc)
  12267. this.texturesSupported.push('-pvrtc.ktx');
  12268. if (this._caps.etc2)
  12269. this.texturesSupported.push('-etc2.ktx');
  12270. if (this._caps.etc1)
  12271. this.texturesSupported.push('-etc1.ktx');
  12272. if (this._gl.getShaderPrecisionFormat) {
  12273. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12274. if (highp) {
  12275. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12276. }
  12277. }
  12278. // Depth buffer
  12279. this.setDepthBuffer(true);
  12280. this.setDepthFunctionToLessOrEqual();
  12281. this.setDepthWrite(true);
  12282. // Texture maps
  12283. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12284. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12285. this._nextFreeTextureSlots.push(slot);
  12286. }
  12287. };
  12288. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12289. /**
  12290. * Gets version of the current webGL context
  12291. */
  12292. get: function () {
  12293. return this._webGLVersion;
  12294. },
  12295. enumerable: true,
  12296. configurable: true
  12297. });
  12298. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12299. /**
  12300. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12301. */
  12302. get: function () {
  12303. return this._isStencilEnable;
  12304. },
  12305. enumerable: true,
  12306. configurable: true
  12307. });
  12308. Engine.prototype._prepareWorkingCanvas = function () {
  12309. if (this._workingCanvas) {
  12310. return;
  12311. }
  12312. this._workingCanvas = document.createElement("canvas");
  12313. var context = this._workingCanvas.getContext("2d");
  12314. if (context) {
  12315. this._workingContext = context;
  12316. }
  12317. };
  12318. /**
  12319. * Reset the texture cache to empty state
  12320. */
  12321. Engine.prototype.resetTextureCache = function () {
  12322. for (var key in this._boundTexturesCache) {
  12323. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12324. continue;
  12325. }
  12326. var boundTexture = this._boundTexturesCache[key];
  12327. if (boundTexture) {
  12328. this._removeDesignatedSlot(boundTexture);
  12329. }
  12330. this._boundTexturesCache[key] = null;
  12331. }
  12332. if (!this.disableTextureBindingOptimization) {
  12333. this._nextFreeTextureSlots = [];
  12334. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12335. this._nextFreeTextureSlots.push(slot);
  12336. }
  12337. }
  12338. this._currentTextureChannel = -1;
  12339. };
  12340. /**
  12341. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12342. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12343. * @returns true if engine is in deterministic lock step mode
  12344. */
  12345. Engine.prototype.isDeterministicLockStep = function () {
  12346. return this._deterministicLockstep;
  12347. };
  12348. /**
  12349. * Gets the max steps when engine is running in deterministic lock step
  12350. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12351. * @returns the max steps
  12352. */
  12353. Engine.prototype.getLockstepMaxSteps = function () {
  12354. return this._lockstepMaxSteps;
  12355. };
  12356. /**
  12357. * Gets an object containing information about the current webGL context
  12358. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12359. */
  12360. Engine.prototype.getGlInfo = function () {
  12361. return {
  12362. vendor: this._glVendor,
  12363. renderer: this._glRenderer,
  12364. version: this._glVersion
  12365. };
  12366. };
  12367. /**
  12368. * Gets current aspect ratio
  12369. * @param camera defines the camera to use to get the aspect ratio
  12370. * @param useScreen defines if screen size must be used (or the current render target if any)
  12371. * @returns a number defining the aspect ratio
  12372. */
  12373. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12374. if (useScreen === void 0) { useScreen = false; }
  12375. var viewport = camera.viewport;
  12376. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12377. };
  12378. /**
  12379. * Gets current screen aspect ratio
  12380. * @returns a number defining the aspect ratio
  12381. */
  12382. Engine.prototype.getScreenAspectRatio = function () {
  12383. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12384. };
  12385. /**
  12386. * Gets the current render width
  12387. * @param useScreen defines if screen size must be used (or the current render target if any)
  12388. * @returns a number defining the current render width
  12389. */
  12390. Engine.prototype.getRenderWidth = function (useScreen) {
  12391. if (useScreen === void 0) { useScreen = false; }
  12392. if (!useScreen && this._currentRenderTarget) {
  12393. return this._currentRenderTarget.width;
  12394. }
  12395. return this._gl.drawingBufferWidth;
  12396. };
  12397. /**
  12398. * Gets the current render height
  12399. * @param useScreen defines if screen size must be used (or the current render target if any)
  12400. * @returns a number defining the current render height
  12401. */
  12402. Engine.prototype.getRenderHeight = function (useScreen) {
  12403. if (useScreen === void 0) { useScreen = false; }
  12404. if (!useScreen && this._currentRenderTarget) {
  12405. return this._currentRenderTarget.height;
  12406. }
  12407. return this._gl.drawingBufferHeight;
  12408. };
  12409. /**
  12410. * Gets the HTML canvas attached with the current webGL context
  12411. * @returns a HTML canvas
  12412. */
  12413. Engine.prototype.getRenderingCanvas = function () {
  12414. return this._renderingCanvas;
  12415. };
  12416. /**
  12417. * Gets the client rect of the HTML canvas attached with the current webGL context
  12418. * @returns a client rectanglee
  12419. */
  12420. Engine.prototype.getRenderingCanvasClientRect = function () {
  12421. if (!this._renderingCanvas) {
  12422. return null;
  12423. }
  12424. return this._renderingCanvas.getBoundingClientRect();
  12425. };
  12426. /**
  12427. * Defines the hardware scaling level.
  12428. * By default the hardware scaling level is computed from the window device ratio.
  12429. * 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.
  12430. * @param level defines the level to use
  12431. */
  12432. Engine.prototype.setHardwareScalingLevel = function (level) {
  12433. this._hardwareScalingLevel = level;
  12434. this.resize();
  12435. };
  12436. /**
  12437. * Gets the current hardware scaling level.
  12438. * By default the hardware scaling level is computed from the window device ratio.
  12439. * 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.
  12440. * @returns a number indicating the current hardware scaling level
  12441. */
  12442. Engine.prototype.getHardwareScalingLevel = function () {
  12443. return this._hardwareScalingLevel;
  12444. };
  12445. /**
  12446. * Gets the list of loaded textures
  12447. * @returns an array containing all loaded textures
  12448. */
  12449. Engine.prototype.getLoadedTexturesCache = function () {
  12450. return this._internalTexturesCache;
  12451. };
  12452. /**
  12453. * Gets the object containing all engine capabilities
  12454. * @returns the EngineCapabilities object
  12455. */
  12456. Engine.prototype.getCaps = function () {
  12457. return this._caps;
  12458. };
  12459. Object.defineProperty(Engine.prototype, "drawCalls", {
  12460. /** @hidden */
  12461. get: function () {
  12462. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12463. return 0;
  12464. },
  12465. enumerable: true,
  12466. configurable: true
  12467. });
  12468. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12469. /** @hidden */
  12470. get: function () {
  12471. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12472. return null;
  12473. },
  12474. enumerable: true,
  12475. configurable: true
  12476. });
  12477. /**
  12478. * Gets the current depth function
  12479. * @returns a number defining the depth function
  12480. */
  12481. Engine.prototype.getDepthFunction = function () {
  12482. return this._depthCullingState.depthFunc;
  12483. };
  12484. /**
  12485. * Sets the current depth function
  12486. * @param depthFunc defines the function to use
  12487. */
  12488. Engine.prototype.setDepthFunction = function (depthFunc) {
  12489. this._depthCullingState.depthFunc = depthFunc;
  12490. };
  12491. /**
  12492. * Sets the current depth function to GREATER
  12493. */
  12494. Engine.prototype.setDepthFunctionToGreater = function () {
  12495. this._depthCullingState.depthFunc = this._gl.GREATER;
  12496. };
  12497. /**
  12498. * Sets the current depth function to GEQUAL
  12499. */
  12500. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12501. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12502. };
  12503. /**
  12504. * Sets the current depth function to LESS
  12505. */
  12506. Engine.prototype.setDepthFunctionToLess = function () {
  12507. this._depthCullingState.depthFunc = this._gl.LESS;
  12508. };
  12509. /**
  12510. * Sets the current depth function to LEQUAL
  12511. */
  12512. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12513. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12514. };
  12515. /**
  12516. * Gets a boolean indicating if stencil buffer is enabled
  12517. * @returns the current stencil buffer state
  12518. */
  12519. Engine.prototype.getStencilBuffer = function () {
  12520. return this._stencilState.stencilTest;
  12521. };
  12522. /**
  12523. * Enable or disable the stencil buffer
  12524. * @param enable defines if the stencil buffer must be enabled or disabled
  12525. */
  12526. Engine.prototype.setStencilBuffer = function (enable) {
  12527. this._stencilState.stencilTest = enable;
  12528. };
  12529. /**
  12530. * Gets the current stencil mask
  12531. * @returns a number defining the new stencil mask to use
  12532. */
  12533. Engine.prototype.getStencilMask = function () {
  12534. return this._stencilState.stencilMask;
  12535. };
  12536. /**
  12537. * Sets the current stencil mask
  12538. * @param mask defines the new stencil mask to use
  12539. */
  12540. Engine.prototype.setStencilMask = function (mask) {
  12541. this._stencilState.stencilMask = mask;
  12542. };
  12543. /**
  12544. * Gets the current stencil function
  12545. * @returns a number defining the stencil function to use
  12546. */
  12547. Engine.prototype.getStencilFunction = function () {
  12548. return this._stencilState.stencilFunc;
  12549. };
  12550. /**
  12551. * Gets the current stencil reference value
  12552. * @returns a number defining the stencil reference value to use
  12553. */
  12554. Engine.prototype.getStencilFunctionReference = function () {
  12555. return this._stencilState.stencilFuncRef;
  12556. };
  12557. /**
  12558. * Gets the current stencil mask
  12559. * @returns a number defining the stencil mask to use
  12560. */
  12561. Engine.prototype.getStencilFunctionMask = function () {
  12562. return this._stencilState.stencilFuncMask;
  12563. };
  12564. /**
  12565. * Sets the current stencil function
  12566. * @param stencilFunc defines the new stencil function to use
  12567. */
  12568. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12569. this._stencilState.stencilFunc = stencilFunc;
  12570. };
  12571. /**
  12572. * Sets the current stencil reference
  12573. * @param reference defines the new stencil reference to use
  12574. */
  12575. Engine.prototype.setStencilFunctionReference = function (reference) {
  12576. this._stencilState.stencilFuncRef = reference;
  12577. };
  12578. /**
  12579. * Sets the current stencil mask
  12580. * @param mask defines the new stencil mask to use
  12581. */
  12582. Engine.prototype.setStencilFunctionMask = function (mask) {
  12583. this._stencilState.stencilFuncMask = mask;
  12584. };
  12585. /**
  12586. * Gets the current stencil operation when stencil fails
  12587. * @returns a number defining stencil operation to use when stencil fails
  12588. */
  12589. Engine.prototype.getStencilOperationFail = function () {
  12590. return this._stencilState.stencilOpStencilFail;
  12591. };
  12592. /**
  12593. * Gets the current stencil operation when depth fails
  12594. * @returns a number defining stencil operation to use when depth fails
  12595. */
  12596. Engine.prototype.getStencilOperationDepthFail = function () {
  12597. return this._stencilState.stencilOpDepthFail;
  12598. };
  12599. /**
  12600. * Gets the current stencil operation when stencil passes
  12601. * @returns a number defining stencil operation to use when stencil passes
  12602. */
  12603. Engine.prototype.getStencilOperationPass = function () {
  12604. return this._stencilState.stencilOpStencilDepthPass;
  12605. };
  12606. /**
  12607. * Sets the stencil operation to use when stencil fails
  12608. * @param operation defines the stencil operation to use when stencil fails
  12609. */
  12610. Engine.prototype.setStencilOperationFail = function (operation) {
  12611. this._stencilState.stencilOpStencilFail = operation;
  12612. };
  12613. /**
  12614. * Sets the stencil operation to use when depth fails
  12615. * @param operation defines the stencil operation to use when depth fails
  12616. */
  12617. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12618. this._stencilState.stencilOpDepthFail = operation;
  12619. };
  12620. /**
  12621. * Sets the stencil operation to use when stencil passes
  12622. * @param operation defines the stencil operation to use when stencil passes
  12623. */
  12624. Engine.prototype.setStencilOperationPass = function (operation) {
  12625. this._stencilState.stencilOpStencilDepthPass = operation;
  12626. };
  12627. /**
  12628. * Sets a boolean indicating if the dithering state is enabled or disabled
  12629. * @param value defines the dithering state
  12630. */
  12631. Engine.prototype.setDitheringState = function (value) {
  12632. if (value) {
  12633. this._gl.enable(this._gl.DITHER);
  12634. }
  12635. else {
  12636. this._gl.disable(this._gl.DITHER);
  12637. }
  12638. };
  12639. /**
  12640. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12641. * @param value defines the rasterizer state
  12642. */
  12643. Engine.prototype.setRasterizerState = function (value) {
  12644. if (value) {
  12645. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12646. }
  12647. else {
  12648. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12649. }
  12650. };
  12651. /**
  12652. * stop executing a render loop function and remove it from the execution array
  12653. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12654. */
  12655. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12656. if (!renderFunction) {
  12657. this._activeRenderLoops = [];
  12658. return;
  12659. }
  12660. var index = this._activeRenderLoops.indexOf(renderFunction);
  12661. if (index >= 0) {
  12662. this._activeRenderLoops.splice(index, 1);
  12663. }
  12664. };
  12665. /** @hidden */
  12666. Engine.prototype._renderLoop = function () {
  12667. if (!this._contextWasLost) {
  12668. var shouldRender = true;
  12669. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12670. shouldRender = false;
  12671. }
  12672. if (shouldRender) {
  12673. // Start new frame
  12674. this.beginFrame();
  12675. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12676. var renderFunction = this._activeRenderLoops[index];
  12677. renderFunction();
  12678. }
  12679. // Present
  12680. this.endFrame();
  12681. }
  12682. }
  12683. if (this._activeRenderLoops.length > 0) {
  12684. // Register new frame
  12685. var requester = null;
  12686. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12687. requester = this._vrDisplay;
  12688. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12689. }
  12690. else {
  12691. this._renderingQueueLaunched = false;
  12692. }
  12693. };
  12694. /**
  12695. * Register and execute a render loop. The engine can have more than one render function
  12696. * @param renderFunction defines the function to continuously execute
  12697. */
  12698. Engine.prototype.runRenderLoop = function (renderFunction) {
  12699. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12700. return;
  12701. }
  12702. this._activeRenderLoops.push(renderFunction);
  12703. if (!this._renderingQueueLaunched) {
  12704. this._renderingQueueLaunched = true;
  12705. this._bindedRenderFunction = this._renderLoop.bind(this);
  12706. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12707. }
  12708. };
  12709. /**
  12710. * Toggle full screen mode
  12711. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12712. */
  12713. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12714. if (this.isFullscreen) {
  12715. BABYLON.Tools.ExitFullscreen();
  12716. }
  12717. else {
  12718. this._pointerLockRequested = requestPointerLock;
  12719. if (this._renderingCanvas) {
  12720. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12721. }
  12722. }
  12723. };
  12724. /**
  12725. * Clear the current render buffer or the current render target (if any is set up)
  12726. * @param color defines the color to use
  12727. * @param backBuffer defines if the back buffer must be cleared
  12728. * @param depth defines if the depth buffer must be cleared
  12729. * @param stencil defines if the stencil buffer must be cleared
  12730. */
  12731. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12732. if (stencil === void 0) { stencil = false; }
  12733. this.applyStates();
  12734. var mode = 0;
  12735. if (backBuffer && color) {
  12736. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12737. mode |= this._gl.COLOR_BUFFER_BIT;
  12738. }
  12739. if (depth) {
  12740. this._gl.clearDepth(1.0);
  12741. mode |= this._gl.DEPTH_BUFFER_BIT;
  12742. }
  12743. if (stencil) {
  12744. this._gl.clearStencil(0);
  12745. mode |= this._gl.STENCIL_BUFFER_BIT;
  12746. }
  12747. this._gl.clear(mode);
  12748. };
  12749. /**
  12750. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12751. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12752. * @param y defines the y-coordinate of the corner of the clear rectangle
  12753. * @param width defines the width of the clear rectangle
  12754. * @param height defines the height of the clear rectangle
  12755. * @param clearColor defines the clear color
  12756. */
  12757. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12758. var gl = this._gl;
  12759. // Save state
  12760. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12761. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12762. // Change state
  12763. gl.enable(gl.SCISSOR_TEST);
  12764. gl.scissor(x, y, width, height);
  12765. // Clear
  12766. this.clear(clearColor, true, true, true);
  12767. // Restore state
  12768. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12769. if (curScissor === true) {
  12770. gl.enable(gl.SCISSOR_TEST);
  12771. }
  12772. else {
  12773. gl.disable(gl.SCISSOR_TEST);
  12774. }
  12775. };
  12776. /** @hidden */
  12777. Engine.prototype._viewport = function (x, y, width, height) {
  12778. if (x !== this._viewportCached.x ||
  12779. y !== this._viewportCached.y ||
  12780. width !== this._viewportCached.z ||
  12781. height !== this._viewportCached.w) {
  12782. this._viewportCached.x = x;
  12783. this._viewportCached.y = y;
  12784. this._viewportCached.z = width;
  12785. this._viewportCached.w = height;
  12786. this._gl.viewport(x, y, width, height);
  12787. }
  12788. };
  12789. /**
  12790. * Set the WebGL's viewport
  12791. * @param viewport defines the viewport element to be used
  12792. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12793. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12794. */
  12795. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12796. var width = requiredWidth || this.getRenderWidth();
  12797. var height = requiredHeight || this.getRenderHeight();
  12798. var x = viewport.x || 0;
  12799. var y = viewport.y || 0;
  12800. this._cachedViewport = viewport;
  12801. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12802. };
  12803. /**
  12804. * Directly set the WebGL Viewport
  12805. * @param x defines the x coordinate of the viewport (in screen space)
  12806. * @param y defines the y coordinate of the viewport (in screen space)
  12807. * @param width defines the width of the viewport (in screen space)
  12808. * @param height defines the height of the viewport (in screen space)
  12809. * @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
  12810. */
  12811. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12812. var currentViewport = this._cachedViewport;
  12813. this._cachedViewport = null;
  12814. this._viewport(x, y, width, height);
  12815. return currentViewport;
  12816. };
  12817. /**
  12818. * Begin a new frame
  12819. */
  12820. Engine.prototype.beginFrame = function () {
  12821. this.onBeginFrameObservable.notifyObservers(this);
  12822. this._measureFps();
  12823. };
  12824. /**
  12825. * Enf the current frame
  12826. */
  12827. Engine.prototype.endFrame = function () {
  12828. // Force a flush in case we are using a bad OS.
  12829. if (this._badOS) {
  12830. this.flushFramebuffer();
  12831. }
  12832. // Submit frame to the vr device, if enabled
  12833. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12834. // TODO: We should only submit the frame if we read frameData successfully.
  12835. this._vrDisplay.submitFrame();
  12836. }
  12837. this.onEndFrameObservable.notifyObservers(this);
  12838. };
  12839. /**
  12840. * Resize the view according to the canvas' size
  12841. */
  12842. Engine.prototype.resize = function () {
  12843. // We're not resizing the size of the canvas while in VR mode & presenting
  12844. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12845. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12846. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12847. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12848. }
  12849. };
  12850. /**
  12851. * Force a specific size of the canvas
  12852. * @param width defines the new canvas' width
  12853. * @param height defines the new canvas' height
  12854. */
  12855. Engine.prototype.setSize = function (width, height) {
  12856. if (!this._renderingCanvas) {
  12857. return;
  12858. }
  12859. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12860. return;
  12861. }
  12862. this._renderingCanvas.width = width;
  12863. this._renderingCanvas.height = height;
  12864. for (var index = 0; index < this.scenes.length; index++) {
  12865. var scene = this.scenes[index];
  12866. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12867. var cam = scene.cameras[camIndex];
  12868. cam._currentRenderId = 0;
  12869. }
  12870. }
  12871. if (this.onResizeObservable.hasObservers) {
  12872. this.onResizeObservable.notifyObservers(this);
  12873. }
  12874. };
  12875. // WebVR functions
  12876. /**
  12877. * Gets a boolean indicating if a webVR device was detected
  12878. * @returns true if a webVR device was detected
  12879. */
  12880. Engine.prototype.isVRDevicePresent = function () {
  12881. return !!this._vrDisplay;
  12882. };
  12883. /**
  12884. * Gets the current webVR device
  12885. * @returns the current webVR device (or null)
  12886. */
  12887. Engine.prototype.getVRDevice = function () {
  12888. return this._vrDisplay;
  12889. };
  12890. /**
  12891. * Initializes a webVR display and starts listening to display change events
  12892. * The onVRDisplayChangedObservable will be notified upon these changes
  12893. * @returns The onVRDisplayChangedObservable
  12894. */
  12895. Engine.prototype.initWebVR = function () {
  12896. this.initWebVRAsync();
  12897. return this.onVRDisplayChangedObservable;
  12898. };
  12899. /**
  12900. * Initializes a webVR display and starts listening to display change events
  12901. * The onVRDisplayChangedObservable will be notified upon these changes
  12902. * @returns A promise containing a VRDisplay and if vr is supported
  12903. */
  12904. Engine.prototype.initWebVRAsync = function () {
  12905. var _this = this;
  12906. var notifyObservers = function () {
  12907. var eventArgs = {
  12908. vrDisplay: _this._vrDisplay,
  12909. vrSupported: _this._vrSupported
  12910. };
  12911. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12912. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12913. };
  12914. if (!this._onVrDisplayConnect) {
  12915. this._onVrDisplayConnect = function (event) {
  12916. _this._vrDisplay = event.display;
  12917. notifyObservers();
  12918. };
  12919. this._onVrDisplayDisconnect = function () {
  12920. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12921. _this._vrDisplay = undefined;
  12922. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12923. notifyObservers();
  12924. };
  12925. this._onVrDisplayPresentChange = function () {
  12926. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12927. };
  12928. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12929. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12930. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12931. }
  12932. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12933. this._webVRInitPromise.then(notifyObservers);
  12934. return this._webVRInitPromise;
  12935. };
  12936. /**
  12937. * Call this function to switch to webVR mode
  12938. * Will do nothing if webVR is not supported or if there is no webVR device
  12939. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12940. */
  12941. Engine.prototype.enableVR = function () {
  12942. var _this = this;
  12943. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12944. var onResolved = function () {
  12945. _this.onVRRequestPresentComplete.notifyObservers(true);
  12946. _this._onVRFullScreenTriggered();
  12947. };
  12948. var onRejected = function () {
  12949. _this.onVRRequestPresentComplete.notifyObservers(false);
  12950. };
  12951. this.onVRRequestPresentStart.notifyObservers(this);
  12952. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12953. }
  12954. };
  12955. /**
  12956. * Call this function to leave webVR mode
  12957. * Will do nothing if webVR is not supported or if there is no webVR device
  12958. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12959. */
  12960. Engine.prototype.disableVR = function () {
  12961. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12962. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12963. }
  12964. };
  12965. Engine.prototype._getVRDisplaysAsync = function () {
  12966. var _this = this;
  12967. return new Promise(function (res, rej) {
  12968. if (navigator.getVRDisplays) {
  12969. navigator.getVRDisplays().then(function (devices) {
  12970. _this._vrSupported = true;
  12971. // note that devices may actually be an empty array. This is fine;
  12972. // we expect this._vrDisplay to be undefined in this case.
  12973. _this._vrDisplay = devices[0];
  12974. res({
  12975. vrDisplay: _this._vrDisplay,
  12976. vrSupported: _this._vrSupported
  12977. });
  12978. });
  12979. }
  12980. else {
  12981. _this._vrDisplay = undefined;
  12982. _this._vrSupported = false;
  12983. res({
  12984. vrDisplay: _this._vrDisplay,
  12985. vrSupported: _this._vrSupported
  12986. });
  12987. }
  12988. });
  12989. };
  12990. /**
  12991. * Binds the frame buffer to the specified texture.
  12992. * @param texture The texture to render to or null for the default canvas
  12993. * @param faceIndex The face of the texture to render to in case of cube texture
  12994. * @param requiredWidth The width of the target to render to
  12995. * @param requiredHeight The height of the target to render to
  12996. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12997. * @param depthStencilTexture The depth stencil texture to use to render
  12998. * @param lodLevel defines le lod level to bind to the frame buffer
  12999. */
  13000. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13001. if (lodLevel === void 0) { lodLevel = 0; }
  13002. if (this._currentRenderTarget) {
  13003. this.unBindFramebuffer(this._currentRenderTarget);
  13004. }
  13005. this._currentRenderTarget = texture;
  13006. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13007. var gl = this._gl;
  13008. if (texture.isCube) {
  13009. if (faceIndex === undefined) {
  13010. faceIndex = 0;
  13011. }
  13012. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13013. if (depthStencilTexture) {
  13014. if (depthStencilTexture._generateStencilBuffer) {
  13015. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13016. }
  13017. else {
  13018. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13019. }
  13020. }
  13021. }
  13022. if (this._cachedViewport && !forceFullscreenViewport) {
  13023. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13024. }
  13025. else {
  13026. if (!requiredWidth) {
  13027. requiredWidth = texture.width;
  13028. if (lodLevel) {
  13029. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13030. }
  13031. }
  13032. if (!requiredHeight) {
  13033. requiredHeight = texture.height;
  13034. if (lodLevel) {
  13035. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13036. }
  13037. }
  13038. this._viewport(0, 0, requiredWidth, requiredHeight);
  13039. }
  13040. this.wipeCaches();
  13041. };
  13042. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13043. if (this._currentFramebuffer !== framebuffer) {
  13044. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13045. this._currentFramebuffer = framebuffer;
  13046. }
  13047. };
  13048. /**
  13049. * Unbind the current render target texture from the webGL context
  13050. * @param texture defines the render target texture to unbind
  13051. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13052. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13053. */
  13054. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13055. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13056. this._currentRenderTarget = null;
  13057. // If MSAA, we need to bitblt back to main texture
  13058. var gl = this._gl;
  13059. if (texture._MSAAFramebuffer) {
  13060. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13061. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13062. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13063. }
  13064. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13065. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13066. gl.generateMipmap(gl.TEXTURE_2D);
  13067. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13068. }
  13069. if (onBeforeUnbind) {
  13070. if (texture._MSAAFramebuffer) {
  13071. // Bind the correct framebuffer
  13072. this.bindUnboundFramebuffer(texture._framebuffer);
  13073. }
  13074. onBeforeUnbind();
  13075. }
  13076. this.bindUnboundFramebuffer(null);
  13077. };
  13078. /**
  13079. * Unbind a list of render target textures from the webGL context
  13080. * This is used only when drawBuffer extension or webGL2 are active
  13081. * @param textures defines the render target textures to unbind
  13082. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13083. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13084. */
  13085. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13086. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13087. this._currentRenderTarget = null;
  13088. // If MSAA, we need to bitblt back to main texture
  13089. var gl = this._gl;
  13090. if (textures[0]._MSAAFramebuffer) {
  13091. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13092. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13093. var attachments = textures[0]._attachments;
  13094. if (!attachments) {
  13095. attachments = new Array(textures.length);
  13096. textures[0]._attachments = attachments;
  13097. }
  13098. for (var i = 0; i < textures.length; i++) {
  13099. var texture = textures[i];
  13100. for (var j = 0; j < attachments.length; j++) {
  13101. attachments[j] = gl.NONE;
  13102. }
  13103. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13104. gl.readBuffer(attachments[i]);
  13105. gl.drawBuffers(attachments);
  13106. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13107. }
  13108. for (var i = 0; i < attachments.length; i++) {
  13109. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13110. }
  13111. gl.drawBuffers(attachments);
  13112. }
  13113. for (var i = 0; i < textures.length; i++) {
  13114. var texture = textures[i];
  13115. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13116. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13117. gl.generateMipmap(gl.TEXTURE_2D);
  13118. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13119. }
  13120. }
  13121. if (onBeforeUnbind) {
  13122. if (textures[0]._MSAAFramebuffer) {
  13123. // Bind the correct framebuffer
  13124. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13125. }
  13126. onBeforeUnbind();
  13127. }
  13128. this.bindUnboundFramebuffer(null);
  13129. };
  13130. /**
  13131. * Force the mipmap generation for the given render target texture
  13132. * @param texture defines the render target texture to use
  13133. */
  13134. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13135. if (texture.generateMipMaps) {
  13136. var gl = this._gl;
  13137. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13138. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13139. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13140. }
  13141. };
  13142. /**
  13143. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13144. */
  13145. Engine.prototype.flushFramebuffer = function () {
  13146. this._gl.flush();
  13147. };
  13148. /**
  13149. * Unbind the current render target and bind the default framebuffer
  13150. */
  13151. Engine.prototype.restoreDefaultFramebuffer = function () {
  13152. if (this._currentRenderTarget) {
  13153. this.unBindFramebuffer(this._currentRenderTarget);
  13154. }
  13155. else {
  13156. this.bindUnboundFramebuffer(null);
  13157. }
  13158. if (this._cachedViewport) {
  13159. this.setViewport(this._cachedViewport);
  13160. }
  13161. this.wipeCaches();
  13162. };
  13163. // UBOs
  13164. /**
  13165. * Create an uniform buffer
  13166. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13167. * @param elements defines the content of the uniform buffer
  13168. * @returns the webGL uniform buffer
  13169. */
  13170. Engine.prototype.createUniformBuffer = function (elements) {
  13171. var ubo = this._gl.createBuffer();
  13172. if (!ubo) {
  13173. throw new Error("Unable to create uniform buffer");
  13174. }
  13175. this.bindUniformBuffer(ubo);
  13176. if (elements instanceof Float32Array) {
  13177. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13178. }
  13179. else {
  13180. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13181. }
  13182. this.bindUniformBuffer(null);
  13183. ubo.references = 1;
  13184. return ubo;
  13185. };
  13186. /**
  13187. * Create a dynamic uniform buffer
  13188. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13189. * @param elements defines the content of the uniform buffer
  13190. * @returns the webGL uniform buffer
  13191. */
  13192. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13193. var ubo = this._gl.createBuffer();
  13194. if (!ubo) {
  13195. throw new Error("Unable to create dynamic uniform buffer");
  13196. }
  13197. this.bindUniformBuffer(ubo);
  13198. if (elements instanceof Float32Array) {
  13199. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13200. }
  13201. else {
  13202. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13203. }
  13204. this.bindUniformBuffer(null);
  13205. ubo.references = 1;
  13206. return ubo;
  13207. };
  13208. /**
  13209. * Update an existing uniform buffer
  13210. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13211. * @param uniformBuffer defines the target uniform buffer
  13212. * @param elements defines the content to update
  13213. * @param offset defines the offset in the uniform buffer where update should start
  13214. * @param count defines the size of the data to update
  13215. */
  13216. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13217. this.bindUniformBuffer(uniformBuffer);
  13218. if (offset === undefined) {
  13219. offset = 0;
  13220. }
  13221. if (count === undefined) {
  13222. if (elements instanceof Float32Array) {
  13223. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13224. }
  13225. else {
  13226. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13227. }
  13228. }
  13229. else {
  13230. if (elements instanceof Float32Array) {
  13231. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13232. }
  13233. else {
  13234. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13235. }
  13236. }
  13237. this.bindUniformBuffer(null);
  13238. };
  13239. // VBOs
  13240. Engine.prototype._resetVertexBufferBinding = function () {
  13241. this.bindArrayBuffer(null);
  13242. this._cachedVertexBuffers = null;
  13243. };
  13244. /**
  13245. * Creates a vertex buffer
  13246. * @param data the data for the vertex buffer
  13247. * @returns the new WebGL static buffer
  13248. */
  13249. Engine.prototype.createVertexBuffer = function (data) {
  13250. var vbo = this._gl.createBuffer();
  13251. if (!vbo) {
  13252. throw new Error("Unable to create vertex buffer");
  13253. }
  13254. this.bindArrayBuffer(vbo);
  13255. if (data instanceof Array) {
  13256. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13257. }
  13258. else {
  13259. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13260. }
  13261. this._resetVertexBufferBinding();
  13262. vbo.references = 1;
  13263. return vbo;
  13264. };
  13265. /**
  13266. * Creates a dynamic vertex buffer
  13267. * @param data the data for the dynamic vertex buffer
  13268. * @returns the new WebGL dynamic buffer
  13269. */
  13270. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13271. var vbo = this._gl.createBuffer();
  13272. if (!vbo) {
  13273. throw new Error("Unable to create dynamic vertex buffer");
  13274. }
  13275. this.bindArrayBuffer(vbo);
  13276. if (data instanceof Array) {
  13277. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13278. }
  13279. else {
  13280. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13281. }
  13282. this._resetVertexBufferBinding();
  13283. vbo.references = 1;
  13284. return vbo;
  13285. };
  13286. /**
  13287. * Update a dynamic index buffer
  13288. * @param indexBuffer defines the target index buffer
  13289. * @param indices defines the data to update
  13290. * @param offset defines the offset in the target index buffer where update should start
  13291. */
  13292. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13293. if (offset === void 0) { offset = 0; }
  13294. // Force cache update
  13295. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13296. this.bindIndexBuffer(indexBuffer);
  13297. var arrayBuffer;
  13298. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13299. arrayBuffer = indices;
  13300. }
  13301. else {
  13302. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13303. }
  13304. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13305. this._resetIndexBufferBinding();
  13306. };
  13307. /**
  13308. * Updates a dynamic vertex buffer.
  13309. * @param vertexBuffer the vertex buffer to update
  13310. * @param data the data used to update the vertex buffer
  13311. * @param byteOffset the byte offset of the data
  13312. * @param byteLength the byte length of the data
  13313. */
  13314. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13315. this.bindArrayBuffer(vertexBuffer);
  13316. if (byteOffset === undefined) {
  13317. byteOffset = 0;
  13318. }
  13319. if (byteLength === undefined) {
  13320. if (data instanceof Array) {
  13321. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13322. }
  13323. else {
  13324. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13325. }
  13326. }
  13327. else {
  13328. if (data instanceof Array) {
  13329. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13330. }
  13331. else {
  13332. if (data instanceof ArrayBuffer) {
  13333. data = new Uint8Array(data, byteOffset, byteLength);
  13334. }
  13335. else {
  13336. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13337. }
  13338. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13339. }
  13340. }
  13341. this._resetVertexBufferBinding();
  13342. };
  13343. Engine.prototype._resetIndexBufferBinding = function () {
  13344. this.bindIndexBuffer(null);
  13345. this._cachedIndexBuffer = null;
  13346. };
  13347. /**
  13348. * Creates a new index buffer
  13349. * @param indices defines the content of the index buffer
  13350. * @param updatable defines if the index buffer must be updatable
  13351. * @returns a new webGL buffer
  13352. */
  13353. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13354. var vbo = this._gl.createBuffer();
  13355. if (!vbo) {
  13356. throw new Error("Unable to create index buffer");
  13357. }
  13358. this.bindIndexBuffer(vbo);
  13359. // Check for 32 bits indices
  13360. var arrayBuffer;
  13361. var need32Bits = false;
  13362. if (indices instanceof Uint16Array) {
  13363. arrayBuffer = indices;
  13364. }
  13365. else {
  13366. //check 32 bit support
  13367. if (this._caps.uintIndices) {
  13368. if (indices instanceof Uint32Array) {
  13369. arrayBuffer = indices;
  13370. need32Bits = true;
  13371. }
  13372. else {
  13373. //number[] or Int32Array, check if 32 bit is necessary
  13374. for (var index = 0; index < indices.length; index++) {
  13375. if (indices[index] > 65535) {
  13376. need32Bits = true;
  13377. break;
  13378. }
  13379. }
  13380. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13381. }
  13382. }
  13383. else {
  13384. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13385. arrayBuffer = new Uint16Array(indices);
  13386. }
  13387. }
  13388. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13389. this._resetIndexBufferBinding();
  13390. vbo.references = 1;
  13391. vbo.is32Bits = need32Bits;
  13392. return vbo;
  13393. };
  13394. /**
  13395. * Bind a webGL buffer to the webGL context
  13396. * @param buffer defines the buffer to bind
  13397. */
  13398. Engine.prototype.bindArrayBuffer = function (buffer) {
  13399. if (!this._vaoRecordInProgress) {
  13400. this._unbindVertexArrayObject();
  13401. }
  13402. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13403. };
  13404. /**
  13405. * Bind an uniform buffer to the current webGL context
  13406. * @param buffer defines the buffer to bind
  13407. */
  13408. Engine.prototype.bindUniformBuffer = function (buffer) {
  13409. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13410. };
  13411. /**
  13412. * Bind a buffer to the current webGL context at a given location
  13413. * @param buffer defines the buffer to bind
  13414. * @param location defines the index where to bind the buffer
  13415. */
  13416. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13417. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13418. };
  13419. /**
  13420. * Bind a specific block at a given index in a specific shader program
  13421. * @param shaderProgram defines the shader program
  13422. * @param blockName defines the block name
  13423. * @param index defines the index where to bind the block
  13424. */
  13425. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13426. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13427. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13428. };
  13429. ;
  13430. Engine.prototype.bindIndexBuffer = function (buffer) {
  13431. if (!this._vaoRecordInProgress) {
  13432. this._unbindVertexArrayObject();
  13433. }
  13434. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13435. };
  13436. Engine.prototype.bindBuffer = function (buffer, target) {
  13437. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13438. this._gl.bindBuffer(target, buffer);
  13439. this._currentBoundBuffer[target] = buffer;
  13440. }
  13441. };
  13442. /**
  13443. * update the bound buffer with the given data
  13444. * @param data defines the data to update
  13445. */
  13446. Engine.prototype.updateArrayBuffer = function (data) {
  13447. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13448. };
  13449. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13450. var pointer = this._currentBufferPointers[indx];
  13451. var changed = false;
  13452. if (!pointer.active) {
  13453. changed = true;
  13454. pointer.active = true;
  13455. pointer.index = indx;
  13456. pointer.size = size;
  13457. pointer.type = type;
  13458. pointer.normalized = normalized;
  13459. pointer.stride = stride;
  13460. pointer.offset = offset;
  13461. pointer.buffer = buffer;
  13462. }
  13463. else {
  13464. if (pointer.buffer !== buffer) {
  13465. pointer.buffer = buffer;
  13466. changed = true;
  13467. }
  13468. if (pointer.size !== size) {
  13469. pointer.size = size;
  13470. changed = true;
  13471. }
  13472. if (pointer.type !== type) {
  13473. pointer.type = type;
  13474. changed = true;
  13475. }
  13476. if (pointer.normalized !== normalized) {
  13477. pointer.normalized = normalized;
  13478. changed = true;
  13479. }
  13480. if (pointer.stride !== stride) {
  13481. pointer.stride = stride;
  13482. changed = true;
  13483. }
  13484. if (pointer.offset !== offset) {
  13485. pointer.offset = offset;
  13486. changed = true;
  13487. }
  13488. }
  13489. if (changed || this._vaoRecordInProgress) {
  13490. this.bindArrayBuffer(buffer);
  13491. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13492. }
  13493. };
  13494. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13495. if (indexBuffer == null) {
  13496. return;
  13497. }
  13498. if (this._cachedIndexBuffer !== indexBuffer) {
  13499. this._cachedIndexBuffer = indexBuffer;
  13500. this.bindIndexBuffer(indexBuffer);
  13501. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13502. }
  13503. };
  13504. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13505. var attributes = effect.getAttributesNames();
  13506. if (!this._vaoRecordInProgress) {
  13507. this._unbindVertexArrayObject();
  13508. }
  13509. this.unbindAllAttributes();
  13510. for (var index = 0; index < attributes.length; index++) {
  13511. var order = effect.getAttributeLocation(index);
  13512. if (order >= 0) {
  13513. var vertexBuffer = vertexBuffers[attributes[index]];
  13514. if (!vertexBuffer) {
  13515. continue;
  13516. }
  13517. this._gl.enableVertexAttribArray(order);
  13518. if (!this._vaoRecordInProgress) {
  13519. this._vertexAttribArraysEnabled[order] = true;
  13520. }
  13521. var buffer = vertexBuffer.getBuffer();
  13522. if (buffer) {
  13523. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13524. if (vertexBuffer.getIsInstanced()) {
  13525. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13526. if (!this._vaoRecordInProgress) {
  13527. this._currentInstanceLocations.push(order);
  13528. this._currentInstanceBuffers.push(buffer);
  13529. }
  13530. }
  13531. }
  13532. }
  13533. }
  13534. };
  13535. /**
  13536. * Records a vertex array object
  13537. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13538. * @param vertexBuffers defines the list of vertex buffers to store
  13539. * @param indexBuffer defines the index buffer to store
  13540. * @param effect defines the effect to store
  13541. * @returns the new vertex array object
  13542. */
  13543. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13544. var vao = this._gl.createVertexArray();
  13545. this._vaoRecordInProgress = true;
  13546. this._gl.bindVertexArray(vao);
  13547. this._mustWipeVertexAttributes = true;
  13548. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13549. this.bindIndexBuffer(indexBuffer);
  13550. this._vaoRecordInProgress = false;
  13551. this._gl.bindVertexArray(null);
  13552. return vao;
  13553. };
  13554. /**
  13555. * Bind a specific vertex array object
  13556. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13557. * @param vertexArrayObject defines the vertex array object to bind
  13558. * @param indexBuffer defines the index buffer to bind
  13559. */
  13560. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13561. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13562. this._cachedVertexArrayObject = vertexArrayObject;
  13563. this._gl.bindVertexArray(vertexArrayObject);
  13564. this._cachedVertexBuffers = null;
  13565. this._cachedIndexBuffer = null;
  13566. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13567. this._mustWipeVertexAttributes = true;
  13568. }
  13569. };
  13570. /**
  13571. * Bind webGl buffers directly to the webGL context
  13572. * @param vertexBuffer defines the vertex buffer to bind
  13573. * @param indexBuffer defines the index buffer to bind
  13574. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13575. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13576. * @param effect defines the effect associated with the vertex buffer
  13577. */
  13578. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13579. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13580. this._cachedVertexBuffers = vertexBuffer;
  13581. this._cachedEffectForVertexBuffers = effect;
  13582. var attributesCount = effect.getAttributesCount();
  13583. this._unbindVertexArrayObject();
  13584. this.unbindAllAttributes();
  13585. var offset = 0;
  13586. for (var index = 0; index < attributesCount; index++) {
  13587. if (index < vertexDeclaration.length) {
  13588. var order = effect.getAttributeLocation(index);
  13589. if (order >= 0) {
  13590. this._gl.enableVertexAttribArray(order);
  13591. this._vertexAttribArraysEnabled[order] = true;
  13592. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13593. }
  13594. offset += vertexDeclaration[index] * 4;
  13595. }
  13596. }
  13597. }
  13598. this._bindIndexBufferWithCache(indexBuffer);
  13599. };
  13600. Engine.prototype._unbindVertexArrayObject = function () {
  13601. if (!this._cachedVertexArrayObject) {
  13602. return;
  13603. }
  13604. this._cachedVertexArrayObject = null;
  13605. this._gl.bindVertexArray(null);
  13606. };
  13607. /**
  13608. * Bind a list of vertex buffers to the webGL context
  13609. * @param vertexBuffers defines the list of vertex buffers to bind
  13610. * @param indexBuffer defines the index buffer to bind
  13611. * @param effect defines the effect associated with the vertex buffers
  13612. */
  13613. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13614. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13615. this._cachedVertexBuffers = vertexBuffers;
  13616. this._cachedEffectForVertexBuffers = effect;
  13617. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13618. }
  13619. this._bindIndexBufferWithCache(indexBuffer);
  13620. };
  13621. /**
  13622. * Unbind all instance attributes
  13623. */
  13624. Engine.prototype.unbindInstanceAttributes = function () {
  13625. var boundBuffer;
  13626. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13627. var instancesBuffer = this._currentInstanceBuffers[i];
  13628. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13629. boundBuffer = instancesBuffer;
  13630. this.bindArrayBuffer(instancesBuffer);
  13631. }
  13632. var offsetLocation = this._currentInstanceLocations[i];
  13633. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13634. }
  13635. this._currentInstanceBuffers.length = 0;
  13636. this._currentInstanceLocations.length = 0;
  13637. };
  13638. /**
  13639. * Release and free the memory of a vertex array object
  13640. * @param vao defines the vertex array object to delete
  13641. */
  13642. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13643. this._gl.deleteVertexArray(vao);
  13644. };
  13645. /** @hidden */
  13646. Engine.prototype._releaseBuffer = function (buffer) {
  13647. buffer.references--;
  13648. if (buffer.references === 0) {
  13649. this._gl.deleteBuffer(buffer);
  13650. return true;
  13651. }
  13652. return false;
  13653. };
  13654. /**
  13655. * Creates a webGL buffer to use with instanciation
  13656. * @param capacity defines the size of the buffer
  13657. * @returns the webGL buffer
  13658. */
  13659. Engine.prototype.createInstancesBuffer = function (capacity) {
  13660. var buffer = this._gl.createBuffer();
  13661. if (!buffer) {
  13662. throw new Error("Unable to create instance buffer");
  13663. }
  13664. buffer.capacity = capacity;
  13665. this.bindArrayBuffer(buffer);
  13666. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13667. return buffer;
  13668. };
  13669. /**
  13670. * Delete a webGL buffer used with instanciation
  13671. * @param buffer defines the webGL buffer to delete
  13672. */
  13673. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13674. this._gl.deleteBuffer(buffer);
  13675. };
  13676. /**
  13677. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13678. * @param instancesBuffer defines the webGL buffer to update and bind
  13679. * @param data defines the data to store in the buffer
  13680. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13681. */
  13682. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13683. this.bindArrayBuffer(instancesBuffer);
  13684. if (data) {
  13685. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13686. }
  13687. if (offsetLocations[0].index !== undefined) {
  13688. var stride = 0;
  13689. for (var i = 0; i < offsetLocations.length; i++) {
  13690. var ai = offsetLocations[i];
  13691. stride += ai.attributeSize * 4;
  13692. }
  13693. for (var i = 0; i < offsetLocations.length; i++) {
  13694. var ai = offsetLocations[i];
  13695. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13696. this._gl.enableVertexAttribArray(ai.index);
  13697. this._vertexAttribArraysEnabled[ai.index] = true;
  13698. }
  13699. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13700. this._gl.vertexAttribDivisor(ai.index, 1);
  13701. this._currentInstanceLocations.push(ai.index);
  13702. this._currentInstanceBuffers.push(instancesBuffer);
  13703. }
  13704. }
  13705. else {
  13706. for (var index = 0; index < 4; index++) {
  13707. var offsetLocation = offsetLocations[index];
  13708. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13709. this._gl.enableVertexAttribArray(offsetLocation);
  13710. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13711. }
  13712. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13713. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13714. this._currentInstanceLocations.push(offsetLocation);
  13715. this._currentInstanceBuffers.push(instancesBuffer);
  13716. }
  13717. }
  13718. };
  13719. /**
  13720. * Apply all cached states (depth, culling, stencil and alpha)
  13721. */
  13722. Engine.prototype.applyStates = function () {
  13723. this._depthCullingState.apply(this._gl);
  13724. this._stencilState.apply(this._gl);
  13725. this._alphaState.apply(this._gl);
  13726. };
  13727. /**
  13728. * Send a draw order
  13729. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13730. * @param indexStart defines the starting index
  13731. * @param indexCount defines the number of index to draw
  13732. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13733. */
  13734. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13735. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13736. };
  13737. /**
  13738. * Draw a list of points
  13739. * @param verticesStart defines the index of first vertex to draw
  13740. * @param verticesCount defines the count of vertices to draw
  13741. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13742. */
  13743. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13744. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13745. };
  13746. /**
  13747. * Draw a list of unindexed primitives
  13748. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13749. * @param verticesStart defines the index of first vertex to draw
  13750. * @param verticesCount defines the count of vertices to draw
  13751. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13752. */
  13753. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13754. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13755. };
  13756. /**
  13757. * Draw a list of indexed primitives
  13758. * @param fillMode defines the primitive to use
  13759. * @param indexStart defines the starting index
  13760. * @param indexCount defines the number of index to draw
  13761. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13762. */
  13763. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13764. // Apply states
  13765. this.applyStates();
  13766. this._drawCalls.addCount(1, false);
  13767. // Render
  13768. var drawMode = this._drawMode(fillMode);
  13769. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13770. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13771. if (instancesCount) {
  13772. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13773. }
  13774. else {
  13775. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13776. }
  13777. };
  13778. /**
  13779. * Draw a list of unindexed primitives
  13780. * @param fillMode defines the primitive to use
  13781. * @param verticesStart defines the index of first vertex to draw
  13782. * @param verticesCount defines the count of vertices to draw
  13783. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13784. */
  13785. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13786. // Apply states
  13787. this.applyStates();
  13788. this._drawCalls.addCount(1, false);
  13789. var drawMode = this._drawMode(fillMode);
  13790. if (instancesCount) {
  13791. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13792. }
  13793. else {
  13794. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13795. }
  13796. };
  13797. Engine.prototype._drawMode = function (fillMode) {
  13798. switch (fillMode) {
  13799. // Triangle views
  13800. case BABYLON.Material.TriangleFillMode:
  13801. return this._gl.TRIANGLES;
  13802. case BABYLON.Material.PointFillMode:
  13803. return this._gl.POINTS;
  13804. case BABYLON.Material.WireFrameFillMode:
  13805. return this._gl.LINES;
  13806. // Draw modes
  13807. case BABYLON.Material.PointListDrawMode:
  13808. return this._gl.POINTS;
  13809. case BABYLON.Material.LineListDrawMode:
  13810. return this._gl.LINES;
  13811. case BABYLON.Material.LineLoopDrawMode:
  13812. return this._gl.LINE_LOOP;
  13813. case BABYLON.Material.LineStripDrawMode:
  13814. return this._gl.LINE_STRIP;
  13815. case BABYLON.Material.TriangleStripDrawMode:
  13816. return this._gl.TRIANGLE_STRIP;
  13817. case BABYLON.Material.TriangleFanDrawMode:
  13818. return this._gl.TRIANGLE_FAN;
  13819. default:
  13820. return this._gl.TRIANGLES;
  13821. }
  13822. };
  13823. // Shaders
  13824. /** @hidden */
  13825. Engine.prototype._releaseEffect = function (effect) {
  13826. if (this._compiledEffects[effect._key]) {
  13827. delete this._compiledEffects[effect._key];
  13828. this._deleteProgram(effect.getProgram());
  13829. }
  13830. };
  13831. /** @hidden */
  13832. Engine.prototype._deleteProgram = function (program) {
  13833. if (program) {
  13834. program.__SPECTOR_rebuildProgram = null;
  13835. if (program.transformFeedback) {
  13836. this.deleteTransformFeedback(program.transformFeedback);
  13837. program.transformFeedback = null;
  13838. }
  13839. this._gl.deleteProgram(program);
  13840. }
  13841. };
  13842. /**
  13843. * Create a new effect (used to store vertex/fragment shaders)
  13844. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13845. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13846. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13847. * @param samplers defines an array of string used to represent textures
  13848. * @param defines defines the string containing the defines to use to compile the shaders
  13849. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13850. * @param onCompiled defines a function to call when the effect creation is successful
  13851. * @param onError defines a function to call when the effect creation has failed
  13852. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13853. * @returns the new Effect
  13854. */
  13855. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13856. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13857. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13858. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13859. if (this._compiledEffects[name]) {
  13860. var compiledEffect = this._compiledEffects[name];
  13861. if (onCompiled && compiledEffect.isReady()) {
  13862. onCompiled(compiledEffect);
  13863. }
  13864. return compiledEffect;
  13865. }
  13866. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13867. effect._key = name;
  13868. this._compiledEffects[name] = effect;
  13869. return effect;
  13870. };
  13871. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13872. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13873. };
  13874. ;
  13875. Engine.prototype._compileRawShader = function (source, type) {
  13876. var gl = this._gl;
  13877. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13878. gl.shaderSource(shader, source);
  13879. gl.compileShader(shader);
  13880. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13881. var log = gl.getShaderInfoLog(shader);
  13882. if (log) {
  13883. throw new Error(log);
  13884. }
  13885. }
  13886. if (!shader) {
  13887. throw new Error("Something went wrong while compile the shader.");
  13888. }
  13889. return shader;
  13890. };
  13891. ;
  13892. /**
  13893. * Directly creates a webGL program
  13894. * @param vertexCode defines the vertex shader code to use
  13895. * @param fragmentCode defines the fragment shader code to use
  13896. * @param context defines the webGL context to use (if not set, the current one will be used)
  13897. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13898. * @returns the new webGL program
  13899. */
  13900. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13901. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13902. context = context || this._gl;
  13903. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13904. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13905. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13906. };
  13907. /**
  13908. * Creates a webGL program
  13909. * @param vertexCode defines the vertex shader code to use
  13910. * @param fragmentCode defines the fragment shader code to use
  13911. * @param defines defines the string containing the defines to use to compile the shaders
  13912. * @param context defines the webGL context to use (if not set, the current one will be used)
  13913. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13914. * @returns the new webGL program
  13915. */
  13916. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13917. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13918. context = context || this._gl;
  13919. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13920. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13921. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13922. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13923. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13924. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13925. return program;
  13926. };
  13927. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13928. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13929. var shaderProgram = context.createProgram();
  13930. if (!shaderProgram) {
  13931. throw new Error("Unable to create program");
  13932. }
  13933. context.attachShader(shaderProgram, vertexShader);
  13934. context.attachShader(shaderProgram, fragmentShader);
  13935. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13936. var transformFeedback = this.createTransformFeedback();
  13937. this.bindTransformFeedback(transformFeedback);
  13938. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13939. shaderProgram.transformFeedback = transformFeedback;
  13940. }
  13941. context.linkProgram(shaderProgram);
  13942. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13943. this.bindTransformFeedback(null);
  13944. }
  13945. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13946. if (!linked) {
  13947. var error = context.getProgramInfoLog(shaderProgram);
  13948. if (error) {
  13949. throw new Error(error);
  13950. }
  13951. }
  13952. if (this.validateShaderPrograms) {
  13953. context.validateProgram(shaderProgram);
  13954. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13955. if (!validated) {
  13956. var error = context.getProgramInfoLog(shaderProgram);
  13957. if (error) {
  13958. throw new Error(error);
  13959. }
  13960. }
  13961. }
  13962. context.deleteShader(vertexShader);
  13963. context.deleteShader(fragmentShader);
  13964. return shaderProgram;
  13965. };
  13966. /**
  13967. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13968. * @param shaderProgram defines the webGL program to use
  13969. * @param uniformsNames defines the list of uniform names
  13970. * @returns an array of webGL uniform locations
  13971. */
  13972. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13973. var results = new Array();
  13974. for (var index = 0; index < uniformsNames.length; index++) {
  13975. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13976. }
  13977. return results;
  13978. };
  13979. /**
  13980. * Gets the lsit of active attributes for a given webGL program
  13981. * @param shaderProgram defines the webGL program to use
  13982. * @param attributesNames defines the list of attribute names to get
  13983. * @returns an array of indices indicating the offset of each attribute
  13984. */
  13985. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13986. var results = [];
  13987. for (var index = 0; index < attributesNames.length; index++) {
  13988. try {
  13989. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13990. }
  13991. catch (e) {
  13992. results.push(-1);
  13993. }
  13994. }
  13995. return results;
  13996. };
  13997. /**
  13998. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13999. * @param effect defines the effect to activate
  14000. */
  14001. Engine.prototype.enableEffect = function (effect) {
  14002. if (!effect || effect === this._currentEffect) {
  14003. return;
  14004. }
  14005. // Use program
  14006. this.bindSamplers(effect);
  14007. this._currentEffect = effect;
  14008. if (effect.onBind) {
  14009. effect.onBind(effect);
  14010. }
  14011. if (effect._onBindObservable) {
  14012. effect._onBindObservable.notifyObservers(effect);
  14013. }
  14014. };
  14015. /**
  14016. * Set the value of an uniform to an array of int32
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param array defines the array of int32 to store
  14019. */
  14020. Engine.prototype.setIntArray = function (uniform, array) {
  14021. if (!uniform)
  14022. return;
  14023. this._gl.uniform1iv(uniform, array);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to an array of int32 (stored as vec2)
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param array defines the array of int32 to store
  14029. */
  14030. Engine.prototype.setIntArray2 = function (uniform, array) {
  14031. if (!uniform || array.length % 2 !== 0)
  14032. return;
  14033. this._gl.uniform2iv(uniform, array);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to an array of int32 (stored as vec3)
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param array defines the array of int32 to store
  14039. */
  14040. Engine.prototype.setIntArray3 = function (uniform, array) {
  14041. if (!uniform || array.length % 3 !== 0)
  14042. return;
  14043. this._gl.uniform3iv(uniform, array);
  14044. };
  14045. /**
  14046. * Set the value of an uniform to an array of int32 (stored as vec4)
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param array defines the array of int32 to store
  14049. */
  14050. Engine.prototype.setIntArray4 = function (uniform, array) {
  14051. if (!uniform || array.length % 4 !== 0)
  14052. return;
  14053. this._gl.uniform4iv(uniform, array);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to an array of float32
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param array defines the array of float32 to store
  14059. */
  14060. Engine.prototype.setFloatArray = function (uniform, array) {
  14061. if (!uniform)
  14062. return;
  14063. this._gl.uniform1fv(uniform, array);
  14064. };
  14065. /**
  14066. * Set the value of an uniform to an array of float32 (stored as vec2)
  14067. * @param uniform defines the webGL uniform location where to store the value
  14068. * @param array defines the array of float32 to store
  14069. */
  14070. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14071. if (!uniform || array.length % 2 !== 0)
  14072. return;
  14073. this._gl.uniform2fv(uniform, array);
  14074. };
  14075. /**
  14076. * Set the value of an uniform to an array of float32 (stored as vec3)
  14077. * @param uniform defines the webGL uniform location where to store the value
  14078. * @param array defines the array of float32 to store
  14079. */
  14080. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14081. if (!uniform || array.length % 3 !== 0)
  14082. return;
  14083. this._gl.uniform3fv(uniform, array);
  14084. };
  14085. /**
  14086. * Set the value of an uniform to an array of float32 (stored as vec4)
  14087. * @param uniform defines the webGL uniform location where to store the value
  14088. * @param array defines the array of float32 to store
  14089. */
  14090. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14091. if (!uniform || array.length % 4 !== 0)
  14092. return;
  14093. this._gl.uniform4fv(uniform, array);
  14094. };
  14095. /**
  14096. * Set the value of an uniform to an array of number
  14097. * @param uniform defines the webGL uniform location where to store the value
  14098. * @param array defines the array of number to store
  14099. */
  14100. Engine.prototype.setArray = function (uniform, array) {
  14101. if (!uniform)
  14102. return;
  14103. this._gl.uniform1fv(uniform, array);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to an array of number (stored as vec2)
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param array defines the array of number to store
  14109. */
  14110. Engine.prototype.setArray2 = function (uniform, array) {
  14111. if (!uniform || array.length % 2 !== 0)
  14112. return;
  14113. this._gl.uniform2fv(uniform, array);
  14114. };
  14115. /**
  14116. * Set the value of an uniform to an array of number (stored as vec3)
  14117. * @param uniform defines the webGL uniform location where to store the value
  14118. * @param array defines the array of number to store
  14119. */
  14120. Engine.prototype.setArray3 = function (uniform, array) {
  14121. if (!uniform || array.length % 3 !== 0)
  14122. return;
  14123. this._gl.uniform3fv(uniform, array);
  14124. };
  14125. /**
  14126. * Set the value of an uniform to an array of number (stored as vec4)
  14127. * @param uniform defines the webGL uniform location where to store the value
  14128. * @param array defines the array of number to store
  14129. */
  14130. Engine.prototype.setArray4 = function (uniform, array) {
  14131. if (!uniform || array.length % 4 !== 0)
  14132. return;
  14133. this._gl.uniform4fv(uniform, array);
  14134. };
  14135. /**
  14136. * Set the value of an uniform to an array of float32 (stored as matrices)
  14137. * @param uniform defines the webGL uniform location where to store the value
  14138. * @param matrices defines the array of float32 to store
  14139. */
  14140. Engine.prototype.setMatrices = function (uniform, matrices) {
  14141. if (!uniform)
  14142. return;
  14143. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14144. };
  14145. /**
  14146. * Set the value of an uniform to a matrix
  14147. * @param uniform defines the webGL uniform location where to store the value
  14148. * @param matrix defines the matrix to store
  14149. */
  14150. Engine.prototype.setMatrix = function (uniform, matrix) {
  14151. if (!uniform)
  14152. return;
  14153. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14154. };
  14155. /**
  14156. * Set the value of an uniform to a matrix (3x3)
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14159. */
  14160. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14161. if (!uniform)
  14162. return;
  14163. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to a matrix (2x2)
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14169. */
  14170. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14171. if (!uniform)
  14172. return;
  14173. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14174. };
  14175. /**
  14176. * Set the value of an uniform to a number (int)
  14177. * @param uniform defines the webGL uniform location where to store the value
  14178. * @param value defines the int number to store
  14179. */
  14180. Engine.prototype.setInt = function (uniform, value) {
  14181. if (!uniform)
  14182. return;
  14183. this._gl.uniform1i(uniform, value);
  14184. };
  14185. /**
  14186. * Set the value of an uniform to a number (float)
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param value defines the float number to store
  14189. */
  14190. Engine.prototype.setFloat = function (uniform, value) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniform1f(uniform, value);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to a vec2
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param x defines the 1st component of the value
  14199. * @param y defines the 2nd component of the value
  14200. */
  14201. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14202. if (!uniform)
  14203. return;
  14204. this._gl.uniform2f(uniform, x, y);
  14205. };
  14206. /**
  14207. * Set the value of an uniform to a vec3
  14208. * @param uniform defines the webGL uniform location where to store the value
  14209. * @param x defines the 1st component of the value
  14210. * @param y defines the 2nd component of the value
  14211. * @param z defines the 3rd component of the value
  14212. */
  14213. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14214. if (!uniform)
  14215. return;
  14216. this._gl.uniform3f(uniform, x, y, z);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to a boolean
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param bool defines the boolean to store
  14222. */
  14223. Engine.prototype.setBool = function (uniform, bool) {
  14224. if (!uniform)
  14225. return;
  14226. this._gl.uniform1i(uniform, bool);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to a vec4
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param x defines the 1st component of the value
  14232. * @param y defines the 2nd component of the value
  14233. * @param z defines the 3rd component of the value
  14234. * @param w defines the 4th component of the value
  14235. */
  14236. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14237. if (!uniform)
  14238. return;
  14239. this._gl.uniform4f(uniform, x, y, z, w);
  14240. };
  14241. /**
  14242. * Set the value of an uniform to a Color3
  14243. * @param uniform defines the webGL uniform location where to store the value
  14244. * @param color3 defines the color to store
  14245. */
  14246. Engine.prototype.setColor3 = function (uniform, color3) {
  14247. if (!uniform)
  14248. return;
  14249. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14250. };
  14251. /**
  14252. * Set the value of an uniform to a Color3 and an alpha value
  14253. * @param uniform defines the webGL uniform location where to store the value
  14254. * @param color3 defines the color to store
  14255. * @param alpha defines the alpha component to store
  14256. */
  14257. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14258. if (!uniform)
  14259. return;
  14260. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14261. };
  14262. /**
  14263. * Sets a Color4 on a uniform variable
  14264. * @param uniform defines the uniform location
  14265. * @param color4 defines the value to be set
  14266. */
  14267. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14268. if (!uniform)
  14269. return;
  14270. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14271. };
  14272. // States
  14273. /**
  14274. * Set various states to the webGL context
  14275. * @param culling defines backface culling state
  14276. * @param zOffset defines the value to apply to zOffset (0 by default)
  14277. * @param force defines if states must be applied even if cache is up to date
  14278. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14279. */
  14280. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14281. if (zOffset === void 0) { zOffset = 0; }
  14282. if (reverseSide === void 0) { reverseSide = false; }
  14283. // Culling
  14284. if (this._depthCullingState.cull !== culling || force) {
  14285. this._depthCullingState.cull = culling;
  14286. }
  14287. // Cull face
  14288. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14289. if (this._depthCullingState.cullFace !== cullFace || force) {
  14290. this._depthCullingState.cullFace = cullFace;
  14291. }
  14292. // Z offset
  14293. this.setZOffset(zOffset);
  14294. // Front face
  14295. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14296. if (this._depthCullingState.frontFace !== frontFace || force) {
  14297. this._depthCullingState.frontFace = frontFace;
  14298. }
  14299. };
  14300. /**
  14301. * Set the z offset to apply to current rendering
  14302. * @param value defines the offset to apply
  14303. */
  14304. Engine.prototype.setZOffset = function (value) {
  14305. this._depthCullingState.zOffset = value;
  14306. };
  14307. /**
  14308. * Gets the current value of the zOffset
  14309. * @returns the current zOffset state
  14310. */
  14311. Engine.prototype.getZOffset = function () {
  14312. return this._depthCullingState.zOffset;
  14313. };
  14314. /**
  14315. * Enable or disable depth buffering
  14316. * @param enable defines the state to set
  14317. */
  14318. Engine.prototype.setDepthBuffer = function (enable) {
  14319. this._depthCullingState.depthTest = enable;
  14320. };
  14321. /**
  14322. * Gets a boolean indicating if depth writing is enabled
  14323. * @returns the current depth writing state
  14324. */
  14325. Engine.prototype.getDepthWrite = function () {
  14326. return this._depthCullingState.depthMask;
  14327. };
  14328. /**
  14329. * Enable or disable depth writing
  14330. * @param enable defines the state to set
  14331. */
  14332. Engine.prototype.setDepthWrite = function (enable) {
  14333. this._depthCullingState.depthMask = enable;
  14334. };
  14335. /**
  14336. * Enable or disable color writing
  14337. * @param enable defines the state to set
  14338. */
  14339. Engine.prototype.setColorWrite = function (enable) {
  14340. this._gl.colorMask(enable, enable, enable, enable);
  14341. this._colorWrite = enable;
  14342. };
  14343. /**
  14344. * Gets a boolean indicating if color writing is enabled
  14345. * @returns the current color writing state
  14346. */
  14347. Engine.prototype.getColorWrite = function () {
  14348. return this._colorWrite;
  14349. };
  14350. /**
  14351. * Sets alpha constants used by some alpha blending modes
  14352. * @param r defines the red component
  14353. * @param g defines the green component
  14354. * @param b defines the blue component
  14355. * @param a defines the alpha component
  14356. */
  14357. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14358. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14359. };
  14360. /**
  14361. * Sets the current alpha mode
  14362. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14363. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14364. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14365. */
  14366. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14367. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14368. if (this._alphaMode === mode) {
  14369. return;
  14370. }
  14371. switch (mode) {
  14372. case Engine.ALPHA_DISABLE:
  14373. this._alphaState.alphaBlend = false;
  14374. break;
  14375. case Engine.ALPHA_PREMULTIPLIED:
  14376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14377. this._alphaState.alphaBlend = true;
  14378. break;
  14379. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14381. this._alphaState.alphaBlend = true;
  14382. break;
  14383. case Engine.ALPHA_COMBINE:
  14384. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14385. this._alphaState.alphaBlend = true;
  14386. break;
  14387. case Engine.ALPHA_ONEONE:
  14388. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14389. this._alphaState.alphaBlend = true;
  14390. break;
  14391. case Engine.ALPHA_ADD:
  14392. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14393. this._alphaState.alphaBlend = true;
  14394. break;
  14395. case Engine.ALPHA_SUBTRACT:
  14396. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14397. this._alphaState.alphaBlend = true;
  14398. break;
  14399. case Engine.ALPHA_MULTIPLY:
  14400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14401. this._alphaState.alphaBlend = true;
  14402. break;
  14403. case Engine.ALPHA_MAXIMIZED:
  14404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14405. this._alphaState.alphaBlend = true;
  14406. break;
  14407. case Engine.ALPHA_INTERPOLATE:
  14408. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14409. this._alphaState.alphaBlend = true;
  14410. break;
  14411. case Engine.ALPHA_SCREENMODE:
  14412. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14413. this._alphaState.alphaBlend = true;
  14414. break;
  14415. }
  14416. if (!noDepthWriteChange) {
  14417. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14418. }
  14419. this._alphaMode = mode;
  14420. };
  14421. /**
  14422. * Gets the current alpha mode
  14423. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14424. * @returns the current alpha mode
  14425. */
  14426. Engine.prototype.getAlphaMode = function () {
  14427. return this._alphaMode;
  14428. };
  14429. // Textures
  14430. /**
  14431. * Clears the list of texture accessible through engine.
  14432. * This can help preventing texture load conflict due to name collision.
  14433. */
  14434. Engine.prototype.clearInternalTexturesCache = function () {
  14435. this._internalTexturesCache = [];
  14436. };
  14437. /**
  14438. * Force the entire cache to be cleared
  14439. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14440. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14441. */
  14442. Engine.prototype.wipeCaches = function (bruteForce) {
  14443. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14444. return;
  14445. }
  14446. this._currentEffect = null;
  14447. this._viewportCached.x = 0;
  14448. this._viewportCached.y = 0;
  14449. this._viewportCached.z = 0;
  14450. this._viewportCached.w = 0;
  14451. if (bruteForce) {
  14452. this.resetTextureCache();
  14453. this._currentProgram = null;
  14454. this._stencilState.reset();
  14455. this._depthCullingState.reset();
  14456. this.setDepthFunctionToLessOrEqual();
  14457. this._alphaState.reset();
  14458. this._unpackFlipYCached = null;
  14459. }
  14460. this._resetVertexBufferBinding();
  14461. this._cachedIndexBuffer = null;
  14462. this._cachedEffectForVertexBuffers = null;
  14463. this._unbindVertexArrayObject();
  14464. this.bindIndexBuffer(null);
  14465. };
  14466. /**
  14467. * Set the compressed texture format to use, based on the formats you have, and the formats
  14468. * supported by the hardware / browser.
  14469. *
  14470. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14471. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14472. * to API arguments needed to compressed textures. This puts the burden on the container
  14473. * generator to house the arcane code for determining these for current & future formats.
  14474. *
  14475. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14476. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14477. *
  14478. * Note: The result of this call is not taken into account when a texture is base64.
  14479. *
  14480. * @param formatsAvailable defines the list of those format families you have created
  14481. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14482. *
  14483. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14484. * @returns The extension selected.
  14485. */
  14486. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14487. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14488. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14489. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14490. return this._textureFormatInUse = this._texturesSupported[i];
  14491. }
  14492. }
  14493. }
  14494. // actively set format to nothing, to allow this to be called more than once
  14495. // and possibly fail the 2nd time
  14496. this._textureFormatInUse = null;
  14497. return null;
  14498. };
  14499. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14500. var gl = this._gl;
  14501. var magFilter = gl.NEAREST;
  14502. var minFilter = gl.NEAREST;
  14503. switch (samplingMode) {
  14504. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14505. magFilter = gl.LINEAR;
  14506. if (generateMipMaps) {
  14507. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14508. }
  14509. else {
  14510. minFilter = gl.LINEAR;
  14511. }
  14512. break;
  14513. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14514. magFilter = gl.LINEAR;
  14515. if (generateMipMaps) {
  14516. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14517. }
  14518. else {
  14519. minFilter = gl.LINEAR;
  14520. }
  14521. break;
  14522. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14523. magFilter = gl.NEAREST;
  14524. if (generateMipMaps) {
  14525. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14526. }
  14527. else {
  14528. minFilter = gl.NEAREST;
  14529. }
  14530. break;
  14531. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14532. magFilter = gl.NEAREST;
  14533. if (generateMipMaps) {
  14534. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14535. }
  14536. else {
  14537. minFilter = gl.NEAREST;
  14538. }
  14539. break;
  14540. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14541. magFilter = gl.NEAREST;
  14542. if (generateMipMaps) {
  14543. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14544. }
  14545. else {
  14546. minFilter = gl.LINEAR;
  14547. }
  14548. break;
  14549. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14550. magFilter = gl.NEAREST;
  14551. if (generateMipMaps) {
  14552. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14553. }
  14554. else {
  14555. minFilter = gl.LINEAR;
  14556. }
  14557. break;
  14558. case Engine.TEXTURE_NEAREST_LINEAR:
  14559. magFilter = gl.NEAREST;
  14560. minFilter = gl.LINEAR;
  14561. break;
  14562. case Engine.TEXTURE_NEAREST_NEAREST:
  14563. magFilter = gl.NEAREST;
  14564. minFilter = gl.NEAREST;
  14565. break;
  14566. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14567. magFilter = gl.LINEAR;
  14568. if (generateMipMaps) {
  14569. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14570. }
  14571. else {
  14572. minFilter = gl.NEAREST;
  14573. }
  14574. break;
  14575. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14576. magFilter = gl.LINEAR;
  14577. if (generateMipMaps) {
  14578. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14579. }
  14580. else {
  14581. minFilter = gl.NEAREST;
  14582. }
  14583. break;
  14584. case Engine.TEXTURE_LINEAR_LINEAR:
  14585. magFilter = gl.LINEAR;
  14586. minFilter = gl.LINEAR;
  14587. break;
  14588. case Engine.TEXTURE_LINEAR_NEAREST:
  14589. magFilter = gl.LINEAR;
  14590. minFilter = gl.NEAREST;
  14591. break;
  14592. }
  14593. return {
  14594. min: minFilter,
  14595. mag: magFilter
  14596. };
  14597. };
  14598. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14599. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14600. var img;
  14601. var onload = function () {
  14602. loadedImages[index] = img;
  14603. loadedImages._internalCount++;
  14604. if (scene) {
  14605. scene._removePendingData(img);
  14606. }
  14607. if (loadedImages._internalCount === 6) {
  14608. onfinish(loadedImages);
  14609. }
  14610. };
  14611. var onerror = function (message, exception) {
  14612. if (scene) {
  14613. scene._removePendingData(img);
  14614. }
  14615. if (onErrorCallBack) {
  14616. onErrorCallBack(message, exception);
  14617. }
  14618. };
  14619. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14620. if (scene) {
  14621. scene._addPendingData(img);
  14622. }
  14623. };
  14624. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14625. if (onError === void 0) { onError = null; }
  14626. var loadedImages = [];
  14627. loadedImages._internalCount = 0;
  14628. for (var index = 0; index < 6; index++) {
  14629. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14630. }
  14631. };
  14632. ;
  14633. /** @hidden */
  14634. Engine.prototype._createTexture = function () {
  14635. var texture = this._gl.createTexture();
  14636. if (!texture) {
  14637. throw new Error("Unable to create texture");
  14638. }
  14639. return texture;
  14640. };
  14641. /**
  14642. * Usually called from BABYLON.Texture.ts.
  14643. * Passed information to create a WebGLTexture
  14644. * @param urlArg defines a value which contains one of the following:
  14645. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14646. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14647. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14648. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14649. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14650. * @param scene needed for loading to the correct scene
  14651. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14652. * @param onLoad optional callback to be called upon successful completion
  14653. * @param onError optional callback to be called upon failure
  14654. * @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
  14655. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14656. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14657. * @param forcedExtension defines the extension to use to pick the right loader
  14658. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14659. */
  14660. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14661. var _this = this;
  14662. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14663. if (onLoad === void 0) { onLoad = null; }
  14664. if (onError === void 0) { onError = null; }
  14665. if (buffer === void 0) { buffer = null; }
  14666. if (fallback === void 0) { fallback = null; }
  14667. if (format === void 0) { format = null; }
  14668. if (forcedExtension === void 0) { forcedExtension = null; }
  14669. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14670. var fromData = url.substr(0, 5) === "data:";
  14671. var fromBlob = url.substr(0, 5) === "blob:";
  14672. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14673. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14674. // establish the file extension, if possible
  14675. var lastDot = url.lastIndexOf('.');
  14676. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14677. var loader = null;
  14678. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14679. var availableLoader = _a[_i];
  14680. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14681. loader = availableLoader;
  14682. break;
  14683. }
  14684. }
  14685. if (loader) {
  14686. url = loader.transformUrl(url, this._textureFormatInUse);
  14687. }
  14688. if (scene) {
  14689. scene._addPendingData(texture);
  14690. }
  14691. texture.url = url;
  14692. texture.generateMipMaps = !noMipmap;
  14693. texture.samplingMode = samplingMode;
  14694. texture.invertY = invertY;
  14695. if (!this._doNotHandleContextLost) {
  14696. // Keep a link to the buffer only if we plan to handle context lost
  14697. texture._buffer = buffer;
  14698. }
  14699. var onLoadObserver = null;
  14700. if (onLoad && !fallback) {
  14701. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14702. }
  14703. if (!fallback)
  14704. this._internalTexturesCache.push(texture);
  14705. var onInternalError = function (message, exception) {
  14706. if (scene) {
  14707. scene._removePendingData(texture);
  14708. }
  14709. var customFallback = false;
  14710. if (loader) {
  14711. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14712. if (fallbackUrl) {
  14713. // Add Back
  14714. customFallback = true;
  14715. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14716. }
  14717. }
  14718. if (!customFallback) {
  14719. if (onLoadObserver) {
  14720. texture.onLoadedObservable.remove(onLoadObserver);
  14721. }
  14722. if (BABYLON.Tools.UseFallbackTexture) {
  14723. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14724. }
  14725. }
  14726. if (onError) {
  14727. onError(message || "Unknown error", exception);
  14728. }
  14729. };
  14730. // processing for non-image formats
  14731. if (loader) {
  14732. var callback = function (data) {
  14733. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14734. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14735. done();
  14736. return false;
  14737. }, samplingMode);
  14738. });
  14739. };
  14740. if (!buffer) {
  14741. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14742. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14743. });
  14744. }
  14745. else {
  14746. callback(buffer);
  14747. }
  14748. }
  14749. else {
  14750. var onload = function (img) {
  14751. if (fromBlob && !_this._doNotHandleContextLost) {
  14752. // We need to store the image if we need to rebuild the texture
  14753. // in case of a webgl context lost
  14754. texture._buffer = img;
  14755. }
  14756. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14757. var gl = _this._gl;
  14758. var isPot = (img.width === potWidth && img.height === potHeight);
  14759. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14760. if (isPot) {
  14761. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14762. return false;
  14763. }
  14764. var maxTextureSize = _this._caps.maxTextureSize;
  14765. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14766. _this._prepareWorkingCanvas();
  14767. if (!_this._workingCanvas || !_this._workingContext) {
  14768. return false;
  14769. }
  14770. _this._workingCanvas.width = potWidth;
  14771. _this._workingCanvas.height = potHeight;
  14772. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14773. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14774. texture.width = potWidth;
  14775. texture.height = potHeight;
  14776. return false;
  14777. }
  14778. else {
  14779. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14780. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14781. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14782. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14783. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14784. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14787. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14788. _this._releaseTexture(source_1);
  14789. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14790. continuationCallback();
  14791. });
  14792. }
  14793. return true;
  14794. }, samplingMode);
  14795. };
  14796. if (!fromData || isBase64) {
  14797. if (buffer instanceof HTMLImageElement) {
  14798. onload(buffer);
  14799. }
  14800. else {
  14801. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14802. }
  14803. }
  14804. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14805. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14806. }
  14807. else {
  14808. onload(buffer);
  14809. }
  14810. }
  14811. return texture;
  14812. };
  14813. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14814. var _this = this;
  14815. var rtt = this.createRenderTargetTexture({
  14816. width: destination.width,
  14817. height: destination.height,
  14818. }, {
  14819. generateMipMaps: false,
  14820. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14821. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14822. generateDepthBuffer: false,
  14823. generateStencilBuffer: false
  14824. });
  14825. if (!this._rescalePostProcess) {
  14826. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14827. }
  14828. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14829. _this._rescalePostProcess.onApply = function (effect) {
  14830. effect._bindTexture("textureSampler", source);
  14831. };
  14832. var hostingScene = scene;
  14833. if (!hostingScene) {
  14834. hostingScene = _this.scenes[_this.scenes.length - 1];
  14835. }
  14836. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14837. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14838. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14839. _this.unBindFramebuffer(rtt);
  14840. _this._releaseTexture(rtt);
  14841. if (onComplete) {
  14842. onComplete();
  14843. }
  14844. });
  14845. };
  14846. /**
  14847. * Update a raw texture
  14848. * @param texture defines the texture to update
  14849. * @param data defines the data to store in the texture
  14850. * @param format defines the format of the data
  14851. * @param invertY defines if data must be stored with Y axis inverted
  14852. * @param compression defines the compression used (null by default)
  14853. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14854. */
  14855. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14856. if (compression === void 0) { compression = null; }
  14857. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14858. if (!texture) {
  14859. return;
  14860. }
  14861. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14862. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14863. // babylon's internalFormat but gl's texImage2D format
  14864. var internalFormat = this._getInternalFormat(format);
  14865. var textureType = this._getWebGLTextureType(type);
  14866. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14867. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14868. if (!this._doNotHandleContextLost) {
  14869. texture._bufferView = data;
  14870. texture.format = format;
  14871. texture.type = type;
  14872. texture.invertY = invertY;
  14873. texture._compression = compression;
  14874. }
  14875. if (texture.width % 4 !== 0) {
  14876. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14877. }
  14878. if (compression && data) {
  14879. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14880. }
  14881. else {
  14882. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14883. }
  14884. if (texture.generateMipMaps) {
  14885. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14888. // this.resetTextureCache();
  14889. texture.isReady = true;
  14890. };
  14891. /**
  14892. * Creates a raw texture
  14893. * @param data defines the data to store in the texture
  14894. * @param width defines the width of the texture
  14895. * @param height defines the height of the texture
  14896. * @param format defines the format of the data
  14897. * @param generateMipMaps defines if the engine should generate the mip levels
  14898. * @param invertY defines if data must be stored with Y axis inverted
  14899. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14900. * @param compression defines the compression used (null by default)
  14901. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14902. * @returns the raw texture inside an InternalTexture
  14903. */
  14904. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14905. if (compression === void 0) { compression = null; }
  14906. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14907. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14908. texture.baseWidth = width;
  14909. texture.baseHeight = height;
  14910. texture.width = width;
  14911. texture.height = height;
  14912. texture.format = format;
  14913. texture.generateMipMaps = generateMipMaps;
  14914. texture.samplingMode = samplingMode;
  14915. texture.invertY = invertY;
  14916. texture._compression = compression;
  14917. texture.type = type;
  14918. if (!this._doNotHandleContextLost) {
  14919. texture._bufferView = data;
  14920. }
  14921. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14922. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14923. // Filters
  14924. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14925. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14927. if (generateMipMaps) {
  14928. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14929. }
  14930. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14931. this._internalTexturesCache.push(texture);
  14932. return texture;
  14933. };
  14934. /** @hidden */
  14935. Engine.prototype._unpackFlipY = function (value) {
  14936. if (this._unpackFlipYCached !== value) {
  14937. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14938. if (this.enableUnpackFlipYCached) {
  14939. this._unpackFlipYCached = value;
  14940. }
  14941. }
  14942. };
  14943. /** @hidden */
  14944. Engine.prototype._getUnpackAlignement = function () {
  14945. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14946. };
  14947. /**
  14948. * Creates a dynamic texture
  14949. * @param width defines the width of the texture
  14950. * @param height defines the height of the texture
  14951. * @param generateMipMaps defines if the engine should generate the mip levels
  14952. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14953. * @returns the dynamic texture inside an InternalTexture
  14954. */
  14955. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14956. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14957. texture.baseWidth = width;
  14958. texture.baseHeight = height;
  14959. if (generateMipMaps) {
  14960. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14961. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14962. }
  14963. // this.resetTextureCache();
  14964. texture.width = width;
  14965. texture.height = height;
  14966. texture.isReady = false;
  14967. texture.generateMipMaps = generateMipMaps;
  14968. texture.samplingMode = samplingMode;
  14969. this.updateTextureSamplingMode(samplingMode, texture);
  14970. this._internalTexturesCache.push(texture);
  14971. return texture;
  14972. };
  14973. /**
  14974. * Update the sampling mode of a given texture
  14975. * @param samplingMode defines the required sampling mode
  14976. * @param texture defines the texture to update
  14977. */
  14978. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14979. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14980. if (texture.isCube) {
  14981. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14982. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14983. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14984. }
  14985. else if (texture.is3D) {
  14986. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14987. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14988. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14989. }
  14990. else {
  14991. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14992. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14993. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14994. }
  14995. texture.samplingMode = samplingMode;
  14996. };
  14997. /**
  14998. * Update the content of a dynamic texture
  14999. * @param texture defines the texture to update
  15000. * @param canvas defines the canvas containing the source
  15001. * @param invertY defines if data must be stored with Y axis inverted
  15002. * @param premulAlpha defines if alpha is stored as premultiplied
  15003. * @param format defines the format of the data
  15004. */
  15005. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15006. if (premulAlpha === void 0) { premulAlpha = false; }
  15007. if (!texture) {
  15008. return;
  15009. }
  15010. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15011. this._unpackFlipY(invertY);
  15012. if (premulAlpha) {
  15013. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15014. }
  15015. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15016. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15017. if (texture.generateMipMaps) {
  15018. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15019. }
  15020. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15021. if (premulAlpha) {
  15022. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15023. }
  15024. texture.isReady = true;
  15025. };
  15026. /**
  15027. * Update a video texture
  15028. * @param texture defines the texture to update
  15029. * @param video defines the video element to use
  15030. * @param invertY defines if data must be stored with Y axis inverted
  15031. */
  15032. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15033. if (!texture || texture._isDisabled) {
  15034. return;
  15035. }
  15036. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15037. this._unpackFlipY(!invertY); // Video are upside down by default
  15038. try {
  15039. // Testing video texture support
  15040. if (this._videoTextureSupported === undefined) {
  15041. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15042. if (this._gl.getError() !== 0) {
  15043. this._videoTextureSupported = false;
  15044. }
  15045. else {
  15046. this._videoTextureSupported = true;
  15047. }
  15048. }
  15049. // Copy video through the current working canvas if video texture is not supported
  15050. if (!this._videoTextureSupported) {
  15051. if (!texture._workingCanvas) {
  15052. texture._workingCanvas = document.createElement("canvas");
  15053. var context = texture._workingCanvas.getContext("2d");
  15054. if (!context) {
  15055. throw new Error("Unable to get 2d context");
  15056. }
  15057. texture._workingContext = context;
  15058. texture._workingCanvas.width = texture.width;
  15059. texture._workingCanvas.height = texture.height;
  15060. }
  15061. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15062. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15063. }
  15064. else {
  15065. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15066. }
  15067. if (texture.generateMipMaps) {
  15068. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15069. }
  15070. if (!wasPreviouslyBound) {
  15071. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15072. }
  15073. // this.resetTextureCache();
  15074. texture.isReady = true;
  15075. }
  15076. catch (ex) {
  15077. // Something unexpected
  15078. // Let's disable the texture
  15079. texture._isDisabled = true;
  15080. }
  15081. };
  15082. /**
  15083. * Updates a depth texture Comparison Mode and Function.
  15084. * If the comparison Function is equal to 0, the mode will be set to none.
  15085. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15086. * @param texture The texture to set the comparison function for
  15087. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15088. */
  15089. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15090. if (this.webGLVersion === 1) {
  15091. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15092. return;
  15093. }
  15094. var gl = this._gl;
  15095. if (texture.isCube) {
  15096. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15097. if (comparisonFunction === 0) {
  15098. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15100. }
  15101. else {
  15102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15104. }
  15105. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15106. }
  15107. else {
  15108. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15109. if (comparisonFunction === 0) {
  15110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15112. }
  15113. else {
  15114. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15115. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15116. }
  15117. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15118. }
  15119. texture._comparisonFunction = comparisonFunction;
  15120. };
  15121. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15122. var width = size.width || size;
  15123. var height = size.height || size;
  15124. internalTexture.baseWidth = width;
  15125. internalTexture.baseHeight = height;
  15126. internalTexture.width = width;
  15127. internalTexture.height = height;
  15128. internalTexture.isReady = true;
  15129. internalTexture.samples = 1;
  15130. internalTexture.generateMipMaps = false;
  15131. internalTexture._generateDepthBuffer = true;
  15132. internalTexture._generateStencilBuffer = generateStencil;
  15133. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15134. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15135. internalTexture._comparisonFunction = comparisonFunction;
  15136. var gl = this._gl;
  15137. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15138. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15139. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15140. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15141. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15142. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15143. if (comparisonFunction === 0) {
  15144. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15145. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15146. }
  15147. else {
  15148. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15149. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15150. }
  15151. };
  15152. /**
  15153. * Creates a depth stencil texture.
  15154. * This is only available in WebGL 2 or with the depth texture extension available.
  15155. * @param size The size of face edge in the texture.
  15156. * @param options The options defining the texture.
  15157. * @returns The texture
  15158. */
  15159. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15160. if (options.isCube) {
  15161. var width = size.width || size;
  15162. return this._createDepthStencilCubeTexture(width, options);
  15163. }
  15164. else {
  15165. return this._createDepthStencilTexture(size, options);
  15166. }
  15167. };
  15168. /**
  15169. * Creates a depth stencil texture.
  15170. * This is only available in WebGL 2 or with the depth texture extension available.
  15171. * @param size The size of face edge in the texture.
  15172. * @param options The options defining the texture.
  15173. * @returns The texture
  15174. */
  15175. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15176. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15177. if (!this._caps.depthTextureExtension) {
  15178. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15179. return internalTexture;
  15180. }
  15181. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15182. var gl = this._gl;
  15183. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15184. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15185. if (this.webGLVersion > 1) {
  15186. if (internalOptions.generateStencil) {
  15187. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15188. }
  15189. else {
  15190. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15191. }
  15192. }
  15193. else {
  15194. if (internalOptions.generateStencil) {
  15195. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15196. }
  15197. else {
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15199. }
  15200. }
  15201. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15202. return internalTexture;
  15203. };
  15204. /**
  15205. * Creates a depth stencil cube texture.
  15206. * This is only available in WebGL 2.
  15207. * @param size The size of face edge in the cube texture.
  15208. * @param options The options defining the cube texture.
  15209. * @returns The cube texture
  15210. */
  15211. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15212. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15213. internalTexture.isCube = true;
  15214. if (this.webGLVersion === 1) {
  15215. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15216. return internalTexture;
  15217. }
  15218. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15219. var gl = this._gl;
  15220. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15221. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15222. // Create the depth/stencil buffer
  15223. for (var face = 0; face < 6; face++) {
  15224. if (internalOptions.generateStencil) {
  15225. 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);
  15226. }
  15227. else {
  15228. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15229. }
  15230. }
  15231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15232. return internalTexture;
  15233. };
  15234. /**
  15235. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15236. * @param renderTarget The render target to set the frame buffer for
  15237. */
  15238. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15239. // Create the framebuffer
  15240. var internalTexture = renderTarget.getInternalTexture();
  15241. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15242. return;
  15243. }
  15244. var gl = this._gl;
  15245. var depthStencilTexture = renderTarget.depthStencilTexture;
  15246. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15247. if (depthStencilTexture.isCube) {
  15248. if (depthStencilTexture._generateStencilBuffer) {
  15249. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15250. }
  15251. else {
  15252. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15253. }
  15254. }
  15255. else {
  15256. if (depthStencilTexture._generateStencilBuffer) {
  15257. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15258. }
  15259. else {
  15260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15261. }
  15262. }
  15263. this.bindUnboundFramebuffer(null);
  15264. };
  15265. /**
  15266. * Creates a new render target texture
  15267. * @param size defines the size of the texture
  15268. * @param options defines the options used to create the texture
  15269. * @returns a new render target texture stored in an InternalTexture
  15270. */
  15271. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15272. var fullOptions = new RenderTargetCreationOptions();
  15273. if (options !== undefined && typeof options === "object") {
  15274. fullOptions.generateMipMaps = options.generateMipMaps;
  15275. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15276. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15277. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15278. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15279. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15280. }
  15281. else {
  15282. fullOptions.generateMipMaps = options;
  15283. fullOptions.generateDepthBuffer = true;
  15284. fullOptions.generateStencilBuffer = false;
  15285. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15286. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15287. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15288. }
  15289. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15290. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15291. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15292. }
  15293. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15294. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15295. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15296. }
  15297. var gl = this._gl;
  15298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15299. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15300. var width = size.width || size;
  15301. var height = size.height || size;
  15302. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15303. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15304. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15305. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15306. }
  15307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15311. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15312. // Create the framebuffer
  15313. var currentFrameBuffer = this._currentFramebuffer;
  15314. var framebuffer = gl.createFramebuffer();
  15315. this.bindUnboundFramebuffer(framebuffer);
  15316. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15317. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15318. if (fullOptions.generateMipMaps) {
  15319. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15320. }
  15321. // Unbind
  15322. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15323. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15324. this.bindUnboundFramebuffer(currentFrameBuffer);
  15325. texture._framebuffer = framebuffer;
  15326. texture.baseWidth = width;
  15327. texture.baseHeight = height;
  15328. texture.width = width;
  15329. texture.height = height;
  15330. texture.isReady = true;
  15331. texture.samples = 1;
  15332. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15333. texture.samplingMode = fullOptions.samplingMode;
  15334. texture.type = fullOptions.type;
  15335. texture.format = fullOptions.format;
  15336. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15337. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15338. // this.resetTextureCache();
  15339. this._internalTexturesCache.push(texture);
  15340. return texture;
  15341. };
  15342. /**
  15343. * Create a multi render target texture
  15344. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15345. * @param size defines the size of the texture
  15346. * @param options defines the creation options
  15347. * @returns the cube texture as an InternalTexture
  15348. */
  15349. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15350. var generateMipMaps = false;
  15351. var generateDepthBuffer = true;
  15352. var generateStencilBuffer = false;
  15353. var generateDepthTexture = false;
  15354. var textureCount = 1;
  15355. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15356. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15357. var types = new Array();
  15358. var samplingModes = new Array();
  15359. if (options !== undefined) {
  15360. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15361. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15362. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15363. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15364. textureCount = options.textureCount || 1;
  15365. if (options.types) {
  15366. types = options.types;
  15367. }
  15368. if (options.samplingModes) {
  15369. samplingModes = options.samplingModes;
  15370. }
  15371. }
  15372. var gl = this._gl;
  15373. // Create the framebuffer
  15374. var framebuffer = gl.createFramebuffer();
  15375. this.bindUnboundFramebuffer(framebuffer);
  15376. var width = size.width || size;
  15377. var height = size.height || size;
  15378. var textures = [];
  15379. var attachments = [];
  15380. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15381. for (var i = 0; i < textureCount; i++) {
  15382. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15383. var type = types[i] || defaultType;
  15384. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15385. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15386. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15387. }
  15388. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15389. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15390. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15391. }
  15392. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15393. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15394. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15395. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15396. }
  15397. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15398. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15399. textures.push(texture);
  15400. attachments.push(attachment);
  15401. gl.activeTexture(gl["TEXTURE" + i]);
  15402. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15403. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15407. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15408. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15409. if (generateMipMaps) {
  15410. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15411. }
  15412. // Unbind
  15413. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15414. texture._framebuffer = framebuffer;
  15415. texture._depthStencilBuffer = depthStencilBuffer;
  15416. texture.baseWidth = width;
  15417. texture.baseHeight = height;
  15418. texture.width = width;
  15419. texture.height = height;
  15420. texture.isReady = true;
  15421. texture.samples = 1;
  15422. texture.generateMipMaps = generateMipMaps;
  15423. texture.samplingMode = samplingMode;
  15424. texture.type = type;
  15425. texture._generateDepthBuffer = generateDepthBuffer;
  15426. texture._generateStencilBuffer = generateStencilBuffer;
  15427. texture._attachments = attachments;
  15428. this._internalTexturesCache.push(texture);
  15429. }
  15430. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15431. // Depth texture
  15432. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15433. gl.activeTexture(gl.TEXTURE0);
  15434. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15439. 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);
  15440. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15441. depthTexture._framebuffer = framebuffer;
  15442. depthTexture.baseWidth = width;
  15443. depthTexture.baseHeight = height;
  15444. depthTexture.width = width;
  15445. depthTexture.height = height;
  15446. depthTexture.isReady = true;
  15447. depthTexture.samples = 1;
  15448. depthTexture.generateMipMaps = generateMipMaps;
  15449. depthTexture.samplingMode = gl.NEAREST;
  15450. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15451. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15452. textures.push(depthTexture);
  15453. this._internalTexturesCache.push(depthTexture);
  15454. }
  15455. gl.drawBuffers(attachments);
  15456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15457. this.bindUnboundFramebuffer(null);
  15458. this.resetTextureCache();
  15459. return textures;
  15460. };
  15461. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15462. if (samples === void 0) { samples = 1; }
  15463. var depthStencilBuffer = null;
  15464. var gl = this._gl;
  15465. // Create the depth/stencil buffer
  15466. if (generateStencilBuffer) {
  15467. depthStencilBuffer = gl.createRenderbuffer();
  15468. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15469. if (samples > 1) {
  15470. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15471. }
  15472. else {
  15473. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15474. }
  15475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15476. }
  15477. else if (generateDepthBuffer) {
  15478. depthStencilBuffer = gl.createRenderbuffer();
  15479. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15480. if (samples > 1) {
  15481. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15482. }
  15483. else {
  15484. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15485. }
  15486. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15487. }
  15488. return depthStencilBuffer;
  15489. };
  15490. /**
  15491. * Updates the sample count of a render target texture
  15492. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15493. * @param texture defines the texture to update
  15494. * @param samples defines the sample count to set
  15495. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15496. */
  15497. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15498. if (this.webGLVersion < 2 || !texture) {
  15499. return 1;
  15500. }
  15501. if (texture.samples === samples) {
  15502. return samples;
  15503. }
  15504. var gl = this._gl;
  15505. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15506. // Dispose previous render buffers
  15507. if (texture._depthStencilBuffer) {
  15508. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15509. texture._depthStencilBuffer = null;
  15510. }
  15511. if (texture._MSAAFramebuffer) {
  15512. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15513. texture._MSAAFramebuffer = null;
  15514. }
  15515. if (texture._MSAARenderBuffer) {
  15516. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15517. texture._MSAARenderBuffer = null;
  15518. }
  15519. if (samples > 1) {
  15520. var framebuffer = gl.createFramebuffer();
  15521. if (!framebuffer) {
  15522. throw new Error("Unable to create multi sampled framebuffer");
  15523. }
  15524. texture._MSAAFramebuffer = framebuffer;
  15525. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15526. var colorRenderbuffer = gl.createRenderbuffer();
  15527. if (!colorRenderbuffer) {
  15528. throw new Error("Unable to create multi sampled framebuffer");
  15529. }
  15530. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15531. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15532. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15533. texture._MSAARenderBuffer = colorRenderbuffer;
  15534. }
  15535. else {
  15536. this.bindUnboundFramebuffer(texture._framebuffer);
  15537. }
  15538. texture.samples = samples;
  15539. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15540. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15541. this.bindUnboundFramebuffer(null);
  15542. return samples;
  15543. };
  15544. /**
  15545. * Update the sample count for a given multiple render target texture
  15546. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15547. * @param textures defines the textures to update
  15548. * @param samples defines the sample count to set
  15549. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15550. */
  15551. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15552. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15553. return 1;
  15554. }
  15555. if (textures[0].samples === samples) {
  15556. return samples;
  15557. }
  15558. var gl = this._gl;
  15559. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15560. // Dispose previous render buffers
  15561. if (textures[0]._depthStencilBuffer) {
  15562. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15563. textures[0]._depthStencilBuffer = null;
  15564. }
  15565. if (textures[0]._MSAAFramebuffer) {
  15566. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15567. textures[0]._MSAAFramebuffer = null;
  15568. }
  15569. for (var i = 0; i < textures.length; i++) {
  15570. if (textures[i]._MSAARenderBuffer) {
  15571. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15572. textures[i]._MSAARenderBuffer = null;
  15573. }
  15574. }
  15575. if (samples > 1) {
  15576. var framebuffer = gl.createFramebuffer();
  15577. if (!framebuffer) {
  15578. throw new Error("Unable to create multi sampled framebuffer");
  15579. }
  15580. this.bindUnboundFramebuffer(framebuffer);
  15581. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15582. var attachments = [];
  15583. for (var i = 0; i < textures.length; i++) {
  15584. var texture = textures[i];
  15585. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15586. var colorRenderbuffer = gl.createRenderbuffer();
  15587. if (!colorRenderbuffer) {
  15588. throw new Error("Unable to create multi sampled framebuffer");
  15589. }
  15590. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15591. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15592. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15593. texture._MSAAFramebuffer = framebuffer;
  15594. texture._MSAARenderBuffer = colorRenderbuffer;
  15595. texture.samples = samples;
  15596. texture._depthStencilBuffer = depthStencilBuffer;
  15597. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15598. attachments.push(attachment);
  15599. }
  15600. gl.drawBuffers(attachments);
  15601. }
  15602. else {
  15603. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15604. }
  15605. this.bindUnboundFramebuffer(null);
  15606. return samples;
  15607. };
  15608. /** @hidden */
  15609. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15610. if (faceIndex === void 0) { faceIndex = 0; }
  15611. if (lod === void 0) { lod = 0; }
  15612. var gl = this._gl;
  15613. var target = gl.TEXTURE_2D;
  15614. if (texture.isCube) {
  15615. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15616. }
  15617. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15618. };
  15619. /** @hidden */
  15620. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15621. if (faceIndex === void 0) { faceIndex = 0; }
  15622. if (lod === void 0) { lod = 0; }
  15623. var gl = this._gl;
  15624. var textureType = this._getWebGLTextureType(texture.type);
  15625. var format = this._getInternalFormat(texture.format);
  15626. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15627. this._unpackFlipY(texture.invertY);
  15628. var target = gl.TEXTURE_2D;
  15629. if (texture.isCube) {
  15630. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15631. }
  15632. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15633. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15634. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15635. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15636. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15637. };
  15638. /** @hidden */
  15639. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15640. if (faceIndex === void 0) { faceIndex = 0; }
  15641. if (lod === void 0) { lod = 0; }
  15642. var gl = this._gl;
  15643. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15644. this._bindTextureDirectly(bindTarget, texture, true);
  15645. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15646. this._bindTextureDirectly(bindTarget, null, true);
  15647. };
  15648. /** @hidden */
  15649. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15650. if (faceIndex === void 0) { faceIndex = 0; }
  15651. if (lod === void 0) { lod = 0; }
  15652. var gl = this._gl;
  15653. var textureType = this._getWebGLTextureType(texture.type);
  15654. var format = this._getInternalFormat(texture.format);
  15655. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15656. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15657. this._bindTextureDirectly(bindTarget, texture, true);
  15658. this._unpackFlipY(texture.invertY);
  15659. var target = gl.TEXTURE_2D;
  15660. if (texture.isCube) {
  15661. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15662. }
  15663. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15664. this._bindTextureDirectly(bindTarget, null, true);
  15665. };
  15666. /**
  15667. * Creates a new render target cube texture
  15668. * @param size defines the size of the texture
  15669. * @param options defines the options used to create the texture
  15670. * @returns a new render target cube texture stored in an InternalTexture
  15671. */
  15672. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15673. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15674. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15675. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15676. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15677. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15678. }
  15679. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15680. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15681. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15682. }
  15683. var gl = this._gl;
  15684. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15685. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15686. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15687. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15688. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15689. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15690. }
  15691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15695. for (var face = 0; face < 6; face++) {
  15696. 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);
  15697. }
  15698. // Create the framebuffer
  15699. var framebuffer = gl.createFramebuffer();
  15700. this.bindUnboundFramebuffer(framebuffer);
  15701. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15702. // MipMaps
  15703. if (fullOptions.generateMipMaps) {
  15704. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15705. }
  15706. // Unbind
  15707. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15708. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15709. this.bindUnboundFramebuffer(null);
  15710. texture._framebuffer = framebuffer;
  15711. texture.width = size;
  15712. texture.height = size;
  15713. texture.isReady = true;
  15714. texture.isCube = true;
  15715. texture.samples = 1;
  15716. texture.generateMipMaps = fullOptions.generateMipMaps;
  15717. texture.samplingMode = fullOptions.samplingMode;
  15718. texture.type = fullOptions.type;
  15719. texture.format = fullOptions.format;
  15720. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15721. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15722. this._internalTexturesCache.push(texture);
  15723. return texture;
  15724. };
  15725. /**
  15726. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15727. * @param rootUrl defines the url where the file to load is located
  15728. * @param scene defines the current scene
  15729. * @param lodScale defines scale to apply to the mip map selection
  15730. * @param lodOffset defines offset to apply to the mip map selection
  15731. * @param onLoad defines an optional callback raised when the texture is loaded
  15732. * @param onError defines an optional callback raised if there is an issue to load the texture
  15733. * @param format defines the format of the data
  15734. * @param forcedExtension defines the extension to use to pick the right loader
  15735. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15736. * @returns the cube texture as an InternalTexture
  15737. */
  15738. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15739. var _this = this;
  15740. if (onLoad === void 0) { onLoad = null; }
  15741. if (onError === void 0) { onError = null; }
  15742. if (forcedExtension === void 0) { forcedExtension = null; }
  15743. if (createPolynomials === void 0) { createPolynomials = true; }
  15744. var callback = function (loadData) {
  15745. if (!loadData) {
  15746. if (onLoad) {
  15747. onLoad(null);
  15748. }
  15749. return;
  15750. }
  15751. var texture = loadData.texture;
  15752. if (!createPolynomials) {
  15753. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15754. }
  15755. else if (loadData.info.sphericalPolynomial) {
  15756. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15757. }
  15758. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15759. if (_this._caps.textureLOD) {
  15760. // Do not add extra process if texture lod is supported.
  15761. if (onLoad) {
  15762. onLoad(texture);
  15763. }
  15764. return;
  15765. }
  15766. var mipSlices = 3;
  15767. var gl = _this._gl;
  15768. var width = loadData.width;
  15769. if (!width) {
  15770. return;
  15771. }
  15772. var textures = [];
  15773. for (var i = 0; i < mipSlices; i++) {
  15774. //compute LOD from even spacing in smoothness (matching shader calculation)
  15775. var smoothness = i / (mipSlices - 1);
  15776. var roughness = 1 - smoothness;
  15777. var minLODIndex = lodOffset; // roughness = 0
  15778. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15779. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15780. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15781. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15782. glTextureFromLod.type = texture.type;
  15783. glTextureFromLod.format = texture.format;
  15784. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15785. glTextureFromLod.height = glTextureFromLod.width;
  15786. glTextureFromLod.isCube = true;
  15787. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15792. if (loadData.isDDS) {
  15793. var info = loadData.info;
  15794. var data = loadData.data;
  15795. _this._unpackFlipY(info.isCompressed);
  15796. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15797. }
  15798. else {
  15799. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15800. }
  15801. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15802. // Wrap in a base texture for easy binding.
  15803. var lodTexture = new BABYLON.BaseTexture(scene);
  15804. lodTexture.isCube = true;
  15805. lodTexture._texture = glTextureFromLod;
  15806. glTextureFromLod.isReady = true;
  15807. textures.push(lodTexture);
  15808. }
  15809. texture._lodTextureHigh = textures[2];
  15810. texture._lodTextureMid = textures[1];
  15811. texture._lodTextureLow = textures[0];
  15812. if (onLoad) {
  15813. onLoad(texture);
  15814. }
  15815. };
  15816. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15817. };
  15818. /**
  15819. * Creates a cube texture
  15820. * @param rootUrl defines the url where the files to load is located
  15821. * @param scene defines the current scene
  15822. * @param files defines the list of files to load (1 per face)
  15823. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15824. * @param onLoad defines an optional callback raised when the texture is loaded
  15825. * @param onError defines an optional callback raised if there is an issue to load the texture
  15826. * @param format defines the format of the data
  15827. * @param forcedExtension defines the extension to use to pick the right loader
  15828. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15829. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15830. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15831. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15832. * @returns the cube texture as an InternalTexture
  15833. */
  15834. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15835. var _this = this;
  15836. if (onLoad === void 0) { onLoad = null; }
  15837. if (onError === void 0) { onError = null; }
  15838. if (forcedExtension === void 0) { forcedExtension = null; }
  15839. if (createPolynomials === void 0) { createPolynomials = false; }
  15840. if (lodScale === void 0) { lodScale = 0; }
  15841. if (lodOffset === void 0) { lodOffset = 0; }
  15842. if (fallback === void 0) { fallback = null; }
  15843. var gl = this._gl;
  15844. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15845. texture.isCube = true;
  15846. texture.url = rootUrl;
  15847. texture.generateMipMaps = !noMipmap;
  15848. texture._lodGenerationScale = lodScale;
  15849. texture._lodGenerationOffset = lodOffset;
  15850. if (!this._doNotHandleContextLost) {
  15851. texture._extension = forcedExtension;
  15852. texture._files = files;
  15853. }
  15854. var lastDot = rootUrl.lastIndexOf('.');
  15855. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15856. var loader = null;
  15857. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15858. var availableLoader = _a[_i];
  15859. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15860. loader = availableLoader;
  15861. break;
  15862. }
  15863. }
  15864. var onInternalError = function (request, exception) {
  15865. if (loader) {
  15866. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15867. if (fallbackUrl) {
  15868. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15869. }
  15870. }
  15871. if (onError && request) {
  15872. onError(request.status + " " + request.statusText, exception);
  15873. }
  15874. };
  15875. if (loader) {
  15876. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15877. var onloaddata = function (data) {
  15878. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15879. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15880. };
  15881. if (files && files.length === 6) {
  15882. if (loader.supportCascades) {
  15883. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15884. }
  15885. else if (onError) {
  15886. onError("Textures type does not support cascades.");
  15887. }
  15888. }
  15889. else {
  15890. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15891. }
  15892. }
  15893. else {
  15894. if (!files) {
  15895. throw new Error("Cannot load cubemap because files were not defined");
  15896. }
  15897. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15898. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15899. var height = width;
  15900. _this._prepareWorkingCanvas();
  15901. if (!_this._workingCanvas || !_this._workingContext) {
  15902. return;
  15903. }
  15904. _this._workingCanvas.width = width;
  15905. _this._workingCanvas.height = height;
  15906. var faces = [
  15907. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15908. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15909. ];
  15910. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15911. _this._unpackFlipY(false);
  15912. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15913. for (var index = 0; index < faces.length; index++) {
  15914. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15915. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15916. }
  15917. if (!noMipmap) {
  15918. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15919. }
  15920. _this._setCubeMapTextureParams(!noMipmap);
  15921. texture.width = width;
  15922. texture.height = height;
  15923. texture.isReady = true;
  15924. if (format) {
  15925. texture.format = format;
  15926. }
  15927. texture.onLoadedObservable.notifyObservers(texture);
  15928. texture.onLoadedObservable.clear();
  15929. if (onLoad) {
  15930. onLoad();
  15931. }
  15932. }, files, onError);
  15933. }
  15934. this._internalTexturesCache.push(texture);
  15935. return texture;
  15936. };
  15937. /**
  15938. * @hidden
  15939. */
  15940. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15941. var gl = this._gl;
  15942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15946. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15947. // this.resetTextureCache();
  15948. };
  15949. /**
  15950. * Update a raw cube texture
  15951. * @param texture defines the texture to udpdate
  15952. * @param data defines the data to store
  15953. * @param format defines the data format
  15954. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15955. * @param invertY defines if data must be stored with Y axis inverted
  15956. * @param compression defines the compression used (null by default)
  15957. * @param level defines which level of the texture to update
  15958. */
  15959. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15960. if (compression === void 0) { compression = null; }
  15961. if (level === void 0) { level = 0; }
  15962. texture._bufferViewArray = data;
  15963. texture.format = format;
  15964. texture.type = type;
  15965. texture.invertY = invertY;
  15966. texture._compression = compression;
  15967. var gl = this._gl;
  15968. var textureType = this._getWebGLTextureType(type);
  15969. var internalFormat = this._getInternalFormat(format);
  15970. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15971. var needConversion = false;
  15972. if (internalFormat === gl.RGB) {
  15973. internalFormat = gl.RGBA;
  15974. needConversion = true;
  15975. }
  15976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15977. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15978. if (texture.width % 4 !== 0) {
  15979. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15980. }
  15981. // Data are known to be in +X +Y +Z -X -Y -Z
  15982. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15983. var faceData = data[faceIndex];
  15984. if (compression) {
  15985. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15986. }
  15987. else {
  15988. if (needConversion) {
  15989. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15990. }
  15991. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15992. }
  15993. }
  15994. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15995. if (isPot && texture.generateMipMaps && level === 0) {
  15996. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15997. }
  15998. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15999. // this.resetTextureCache();
  16000. texture.isReady = true;
  16001. };
  16002. /**
  16003. * Creates a new raw cube texture
  16004. * @param data defines the array of data to use to create each face
  16005. * @param size defines the size of the textures
  16006. * @param format defines the format of the data
  16007. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16008. * @param generateMipMaps defines if the engine should generate the mip levels
  16009. * @param invertY defines if data must be stored with Y axis inverted
  16010. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16011. * @param compression defines the compression used (null by default)
  16012. * @returns the cube texture as an InternalTexture
  16013. */
  16014. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16015. if (compression === void 0) { compression = null; }
  16016. var gl = this._gl;
  16017. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16018. texture.isCube = true;
  16019. texture.format = format;
  16020. texture.type = type;
  16021. if (!this._doNotHandleContextLost) {
  16022. texture._bufferViewArray = data;
  16023. }
  16024. var textureType = this._getWebGLTextureType(type);
  16025. var internalFormat = this._getInternalFormat(format);
  16026. if (internalFormat === gl.RGB) {
  16027. internalFormat = gl.RGBA;
  16028. }
  16029. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16030. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16031. generateMipMaps = false;
  16032. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16033. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16034. }
  16035. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16036. generateMipMaps = false;
  16037. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16038. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16039. }
  16040. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16041. generateMipMaps = false;
  16042. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16043. }
  16044. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16045. generateMipMaps = false;
  16046. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16047. }
  16048. var width = size;
  16049. var height = width;
  16050. texture.width = width;
  16051. texture.height = height;
  16052. // Double check on POT to generate Mips.
  16053. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16054. if (!isPot) {
  16055. generateMipMaps = false;
  16056. }
  16057. // Upload data if needed. The texture won't be ready until then.
  16058. if (data) {
  16059. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16060. }
  16061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16062. // Filters
  16063. if (data && generateMipMaps) {
  16064. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16065. }
  16066. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16071. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16072. texture.generateMipMaps = generateMipMaps;
  16073. return texture;
  16074. };
  16075. /**
  16076. * Creates a new raw cube texture from a specified url
  16077. * @param url defines the url where the data is located
  16078. * @param scene defines the current scene
  16079. * @param size defines the size of the textures
  16080. * @param format defines the format of the data
  16081. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16082. * @param noMipmap defines if the engine should avoid generating the mip levels
  16083. * @param callback defines a callback used to extract texture data from loaded data
  16084. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16085. * @param onLoad defines a callback called when texture is loaded
  16086. * @param onError defines a callback called if there is an error
  16087. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16088. * @param invertY defines if data must be stored with Y axis inverted
  16089. * @returns the cube texture as an InternalTexture
  16090. */
  16091. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16092. var _this = this;
  16093. if (onLoad === void 0) { onLoad = null; }
  16094. if (onError === void 0) { onError = null; }
  16095. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16096. if (invertY === void 0) { invertY = false; }
  16097. var gl = this._gl;
  16098. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16099. scene._addPendingData(texture);
  16100. texture.url = url;
  16101. this._internalTexturesCache.push(texture);
  16102. var onerror = function (request, exception) {
  16103. scene._removePendingData(texture);
  16104. if (onError && request) {
  16105. onError(request.status + " " + request.statusText, exception);
  16106. }
  16107. };
  16108. var internalCallback = function (data) {
  16109. var width = texture.width;
  16110. var faceDataArrays = callback(data);
  16111. if (!faceDataArrays) {
  16112. return;
  16113. }
  16114. if (mipmapGenerator) {
  16115. var textureType = _this._getWebGLTextureType(type);
  16116. var internalFormat = _this._getInternalFormat(format);
  16117. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16118. var needConversion = false;
  16119. if (internalFormat === gl.RGB) {
  16120. internalFormat = gl.RGBA;
  16121. needConversion = true;
  16122. }
  16123. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16124. _this._unpackFlipY(false);
  16125. var mipData = mipmapGenerator(faceDataArrays);
  16126. for (var level = 0; level < mipData.length; level++) {
  16127. var mipSize = width >> level;
  16128. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16129. var mipFaceData = mipData[level][faceIndex];
  16130. if (needConversion) {
  16131. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16132. }
  16133. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16134. }
  16135. }
  16136. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16137. }
  16138. else {
  16139. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16140. }
  16141. texture.isReady = true;
  16142. // this.resetTextureCache();
  16143. scene._removePendingData(texture);
  16144. if (onLoad) {
  16145. onLoad();
  16146. }
  16147. };
  16148. this._loadFile(url, function (data) {
  16149. internalCallback(data);
  16150. }, undefined, scene.database, true, onerror);
  16151. return texture;
  16152. };
  16153. ;
  16154. /**
  16155. * Update a raw 3D texture
  16156. * @param texture defines the texture to update
  16157. * @param data defines the data to store
  16158. * @param format defines the data format
  16159. * @param invertY defines if data must be stored with Y axis inverted
  16160. * @param compression defines the used compression (can be null)
  16161. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16162. */
  16163. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16164. if (compression === void 0) { compression = null; }
  16165. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16166. var internalType = this._getWebGLTextureType(textureType);
  16167. var internalFormat = this._getInternalFormat(format);
  16168. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16169. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16170. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16171. if (!this._doNotHandleContextLost) {
  16172. texture._bufferView = data;
  16173. texture.format = format;
  16174. texture.invertY = invertY;
  16175. texture._compression = compression;
  16176. }
  16177. if (texture.width % 4 !== 0) {
  16178. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16179. }
  16180. if (compression && data) {
  16181. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16182. }
  16183. else {
  16184. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16185. }
  16186. if (texture.generateMipMaps) {
  16187. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16188. }
  16189. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16190. // this.resetTextureCache();
  16191. texture.isReady = true;
  16192. };
  16193. /**
  16194. * Creates a new raw 3D texture
  16195. * @param data defines the data used to create the texture
  16196. * @param width defines the width of the texture
  16197. * @param height defines the height of the texture
  16198. * @param depth defines the depth of the texture
  16199. * @param format defines the format of the texture
  16200. * @param generateMipMaps defines if the engine must generate mip levels
  16201. * @param invertY defines if data must be stored with Y axis inverted
  16202. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16203. * @param compression defines the compressed used (can be null)
  16204. * @param textureType defines the compressed used (can be null)
  16205. * @returns a new raw 3D texture (stored in an InternalTexture)
  16206. */
  16207. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16208. if (compression === void 0) { compression = null; }
  16209. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16210. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16211. texture.baseWidth = width;
  16212. texture.baseHeight = height;
  16213. texture.baseDepth = depth;
  16214. texture.width = width;
  16215. texture.height = height;
  16216. texture.depth = depth;
  16217. texture.format = format;
  16218. texture.type = textureType;
  16219. texture.generateMipMaps = generateMipMaps;
  16220. texture.samplingMode = samplingMode;
  16221. texture.is3D = true;
  16222. if (!this._doNotHandleContextLost) {
  16223. texture._bufferView = data;
  16224. }
  16225. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16226. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16227. // Filters
  16228. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16229. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16230. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16231. if (generateMipMaps) {
  16232. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16233. }
  16234. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16235. this._internalTexturesCache.push(texture);
  16236. return texture;
  16237. };
  16238. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16239. var gl = this._gl;
  16240. if (!gl) {
  16241. return;
  16242. }
  16243. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16246. if (!noMipmap && !isCompressed) {
  16247. gl.generateMipmap(gl.TEXTURE_2D);
  16248. }
  16249. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16250. // this.resetTextureCache();
  16251. if (scene) {
  16252. scene._removePendingData(texture);
  16253. }
  16254. texture.onLoadedObservable.notifyObservers(texture);
  16255. texture.onLoadedObservable.clear();
  16256. };
  16257. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16258. var _this = this;
  16259. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16260. var maxTextureSize = this.getCaps().maxTextureSize;
  16261. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16262. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16263. var gl = this._gl;
  16264. if (!gl) {
  16265. return;
  16266. }
  16267. if (!texture._webGLTexture) {
  16268. // this.resetTextureCache();
  16269. if (scene) {
  16270. scene._removePendingData(texture);
  16271. }
  16272. return;
  16273. }
  16274. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16275. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16276. texture.baseWidth = width;
  16277. texture.baseHeight = height;
  16278. texture.width = potWidth;
  16279. texture.height = potHeight;
  16280. texture.isReady = true;
  16281. if (processFunction(potWidth, potHeight, function () {
  16282. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16283. })) {
  16284. // Returning as texture needs extra async steps
  16285. return;
  16286. }
  16287. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16288. };
  16289. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16290. // Create new RGBA data container.
  16291. var rgbaData;
  16292. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16293. rgbaData = new Float32Array(width * height * 4);
  16294. }
  16295. else {
  16296. rgbaData = new Uint32Array(width * height * 4);
  16297. }
  16298. // Convert each pixel.
  16299. for (var x = 0; x < width; x++) {
  16300. for (var y = 0; y < height; y++) {
  16301. var index = (y * width + x) * 3;
  16302. var newIndex = (y * width + x) * 4;
  16303. // Map Old Value to new value.
  16304. rgbaData[newIndex + 0] = rgbData[index + 0];
  16305. rgbaData[newIndex + 1] = rgbData[index + 1];
  16306. rgbaData[newIndex + 2] = rgbData[index + 2];
  16307. // Add fully opaque alpha channel.
  16308. rgbaData[newIndex + 3] = 1;
  16309. }
  16310. }
  16311. return rgbaData;
  16312. };
  16313. /** @hidden */
  16314. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16315. var gl = this._gl;
  16316. if (texture._framebuffer) {
  16317. gl.deleteFramebuffer(texture._framebuffer);
  16318. texture._framebuffer = null;
  16319. }
  16320. if (texture._depthStencilBuffer) {
  16321. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16322. texture._depthStencilBuffer = null;
  16323. }
  16324. if (texture._MSAAFramebuffer) {
  16325. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16326. texture._MSAAFramebuffer = null;
  16327. }
  16328. if (texture._MSAARenderBuffer) {
  16329. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16330. texture._MSAARenderBuffer = null;
  16331. }
  16332. };
  16333. /** @hidden */
  16334. Engine.prototype._releaseTexture = function (texture) {
  16335. var gl = this._gl;
  16336. this._releaseFramebufferObjects(texture);
  16337. gl.deleteTexture(texture._webGLTexture);
  16338. // Unbind channels
  16339. this.unbindAllTextures();
  16340. var index = this._internalTexturesCache.indexOf(texture);
  16341. if (index !== -1) {
  16342. this._internalTexturesCache.splice(index, 1);
  16343. }
  16344. // Integrated fixed lod samplers.
  16345. if (texture._lodTextureHigh) {
  16346. texture._lodTextureHigh.dispose();
  16347. }
  16348. if (texture._lodTextureMid) {
  16349. texture._lodTextureMid.dispose();
  16350. }
  16351. if (texture._lodTextureLow) {
  16352. texture._lodTextureLow.dispose();
  16353. }
  16354. // Set output texture of post process to null if the texture has been released/disposed
  16355. this.scenes.forEach(function (scene) {
  16356. scene.postProcesses.forEach(function (postProcess) {
  16357. if (postProcess._outputTexture == texture) {
  16358. postProcess._outputTexture = null;
  16359. }
  16360. });
  16361. scene.cameras.forEach(function (camera) {
  16362. camera._postProcesses.forEach(function (postProcess) {
  16363. if (postProcess) {
  16364. if (postProcess._outputTexture == texture) {
  16365. postProcess._outputTexture = null;
  16366. }
  16367. }
  16368. });
  16369. });
  16370. });
  16371. };
  16372. Engine.prototype.setProgram = function (program) {
  16373. if (this._currentProgram !== program) {
  16374. this._gl.useProgram(program);
  16375. this._currentProgram = program;
  16376. }
  16377. };
  16378. /**
  16379. * Binds an effect to the webGL context
  16380. * @param effect defines the effect to bind
  16381. */
  16382. Engine.prototype.bindSamplers = function (effect) {
  16383. this.setProgram(effect.getProgram());
  16384. var samplers = effect.getSamplers();
  16385. for (var index = 0; index < samplers.length; index++) {
  16386. var uniform = effect.getUniform(samplers[index]);
  16387. if (uniform) {
  16388. this._boundUniforms[index] = uniform;
  16389. }
  16390. }
  16391. this._currentEffect = null;
  16392. };
  16393. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16394. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16395. return;
  16396. }
  16397. // Remove
  16398. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16399. // Bind last to it
  16400. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16401. // Bind to dummy
  16402. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16403. };
  16404. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16405. if (!internalTexture) {
  16406. return -1;
  16407. }
  16408. internalTexture._initialSlot = channel;
  16409. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16410. if (channel !== internalTexture._designatedSlot) {
  16411. this._textureCollisions.addCount(1, false);
  16412. }
  16413. }
  16414. else {
  16415. if (channel !== internalTexture._designatedSlot) {
  16416. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16417. return internalTexture._designatedSlot;
  16418. }
  16419. else {
  16420. // No slot for this texture, let's pick a new one (if we find a free slot)
  16421. if (this._nextFreeTextureSlots.length) {
  16422. return this._nextFreeTextureSlots[0];
  16423. }
  16424. // We need to recycle the oldest bound texture, sorry.
  16425. this._textureCollisions.addCount(1, false);
  16426. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16427. }
  16428. }
  16429. }
  16430. return channel;
  16431. };
  16432. Engine.prototype._linkTrackers = function (previous, next) {
  16433. previous.next = next;
  16434. next.previous = previous;
  16435. };
  16436. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16437. var currentSlot = internalTexture._designatedSlot;
  16438. if (currentSlot === -1) {
  16439. return -1;
  16440. }
  16441. internalTexture._designatedSlot = -1;
  16442. if (this.disableTextureBindingOptimization) {
  16443. return -1;
  16444. }
  16445. // Remove from bound list
  16446. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16447. // Free the slot
  16448. this._boundTexturesCache[currentSlot] = null;
  16449. this._nextFreeTextureSlots.push(currentSlot);
  16450. return currentSlot;
  16451. };
  16452. Engine.prototype._activateCurrentTexture = function () {
  16453. if (this._currentTextureChannel !== this._activeChannel) {
  16454. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16455. this._currentTextureChannel = this._activeChannel;
  16456. }
  16457. };
  16458. /** @hidden */
  16459. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16460. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16461. if (force === void 0) { force = false; }
  16462. var wasPreviouslyBound = false;
  16463. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16464. this._activeChannel = texture._designatedSlot;
  16465. }
  16466. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16467. var isTextureForRendering = texture && texture._initialSlot > -1;
  16468. if (currentTextureBound !== texture || force) {
  16469. if (currentTextureBound) {
  16470. this._removeDesignatedSlot(currentTextureBound);
  16471. }
  16472. this._activateCurrentTexture();
  16473. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16474. this._boundTexturesCache[this._activeChannel] = texture;
  16475. if (texture) {
  16476. if (!this.disableTextureBindingOptimization) {
  16477. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16478. if (slotIndex > -1) {
  16479. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16480. }
  16481. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16482. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16483. }
  16484. texture._designatedSlot = this._activeChannel;
  16485. }
  16486. }
  16487. else if (forTextureDataUpdate) {
  16488. wasPreviouslyBound = true;
  16489. this._activateCurrentTexture();
  16490. }
  16491. if (isTextureForRendering && !forTextureDataUpdate) {
  16492. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16493. }
  16494. return wasPreviouslyBound;
  16495. };
  16496. /** @hidden */
  16497. Engine.prototype._bindTexture = function (channel, texture) {
  16498. if (channel < 0) {
  16499. return;
  16500. }
  16501. if (texture) {
  16502. channel = this._getCorrectTextureChannel(channel, texture);
  16503. }
  16504. this._activeChannel = channel;
  16505. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16506. };
  16507. /**
  16508. * Sets a texture to the webGL context from a postprocess
  16509. * @param channel defines the channel to use
  16510. * @param postProcess defines the source postprocess
  16511. */
  16512. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16513. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16514. };
  16515. /**
  16516. * Binds the output of the passed in post process to the texture channel specified
  16517. * @param channel The channel the texture should be bound to
  16518. * @param postProcess The post process which's output should be bound
  16519. */
  16520. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16521. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16522. };
  16523. /**
  16524. * Unbind all textures from the webGL context
  16525. */
  16526. Engine.prototype.unbindAllTextures = function () {
  16527. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16528. this._activeChannel = channel;
  16529. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16530. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16531. if (this.webGLVersion > 1) {
  16532. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16533. }
  16534. }
  16535. };
  16536. /**
  16537. * Sets a texture to the according uniform.
  16538. * @param channel The texture channel
  16539. * @param uniform The uniform to set
  16540. * @param texture The texture to apply
  16541. */
  16542. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16543. if (channel < 0) {
  16544. return;
  16545. }
  16546. if (uniform) {
  16547. this._boundUniforms[channel] = uniform;
  16548. }
  16549. this._setTexture(channel, texture);
  16550. };
  16551. /**
  16552. * Sets a depth stencil texture from a render target to the according uniform.
  16553. * @param channel The texture channel
  16554. * @param uniform The uniform to set
  16555. * @param texture The render target texture containing the depth stencil texture to apply
  16556. */
  16557. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16558. if (channel < 0) {
  16559. return;
  16560. }
  16561. if (uniform) {
  16562. this._boundUniforms[channel] = uniform;
  16563. }
  16564. if (!texture || !texture.depthStencilTexture) {
  16565. this._setTexture(channel, null);
  16566. }
  16567. else {
  16568. this._setTexture(channel, texture, false, true);
  16569. }
  16570. };
  16571. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16572. var uniform = this._boundUniforms[sourceSlot];
  16573. if (uniform._currentState === destination) {
  16574. return;
  16575. }
  16576. this._gl.uniform1i(uniform, destination);
  16577. uniform._currentState = destination;
  16578. };
  16579. Engine.prototype._getTextureWrapMode = function (mode) {
  16580. switch (mode) {
  16581. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16582. return this._gl.REPEAT;
  16583. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16584. return this._gl.CLAMP_TO_EDGE;
  16585. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16586. return this._gl.MIRRORED_REPEAT;
  16587. }
  16588. return this._gl.REPEAT;
  16589. };
  16590. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16591. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16592. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16593. // Not ready?
  16594. if (!texture) {
  16595. if (this._boundTexturesCache[channel] != null) {
  16596. this._activeChannel = channel;
  16597. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16598. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16599. if (this.webGLVersion > 1) {
  16600. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16601. }
  16602. }
  16603. return false;
  16604. }
  16605. // Video
  16606. if (texture.video) {
  16607. this._activeChannel = channel;
  16608. texture.update();
  16609. }
  16610. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16611. texture.delayLoad();
  16612. return false;
  16613. }
  16614. var internalTexture;
  16615. if (depthStencilTexture) {
  16616. internalTexture = texture.depthStencilTexture;
  16617. }
  16618. else if (texture.isReady()) {
  16619. internalTexture = texture.getInternalTexture();
  16620. }
  16621. else if (texture.isCube) {
  16622. internalTexture = this.emptyCubeTexture;
  16623. }
  16624. else if (texture.is3D) {
  16625. internalTexture = this.emptyTexture3D;
  16626. }
  16627. else {
  16628. internalTexture = this.emptyTexture;
  16629. }
  16630. if (!isPartOfTextureArray) {
  16631. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16632. }
  16633. var needToBind = true;
  16634. if (this._boundTexturesCache[channel] === internalTexture) {
  16635. this._moveBoundTextureOnTop(internalTexture);
  16636. if (!isPartOfTextureArray) {
  16637. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16638. }
  16639. needToBind = false;
  16640. }
  16641. this._activeChannel = channel;
  16642. if (internalTexture && internalTexture.is3D) {
  16643. if (needToBind) {
  16644. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16645. }
  16646. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16647. internalTexture._cachedWrapU = texture.wrapU;
  16648. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16649. }
  16650. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16651. internalTexture._cachedWrapV = texture.wrapV;
  16652. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16653. }
  16654. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16655. internalTexture._cachedWrapR = texture.wrapR;
  16656. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16657. }
  16658. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16659. }
  16660. else if (internalTexture && internalTexture.isCube) {
  16661. if (needToBind) {
  16662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16663. }
  16664. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16665. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16666. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16667. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16668. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16669. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16670. }
  16671. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16672. }
  16673. else {
  16674. if (needToBind) {
  16675. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16676. }
  16677. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16678. internalTexture._cachedWrapU = texture.wrapU;
  16679. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16680. }
  16681. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16682. internalTexture._cachedWrapV = texture.wrapV;
  16683. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16684. }
  16685. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16686. }
  16687. return true;
  16688. };
  16689. /**
  16690. * Sets an array of texture to the webGL context
  16691. * @param channel defines the channel where the texture array must be set
  16692. * @param uniform defines the associated uniform location
  16693. * @param textures defines the array of textures to bind
  16694. */
  16695. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16696. if (channel < 0 || !uniform) {
  16697. return;
  16698. }
  16699. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16700. this._textureUnits = new Int32Array(textures.length);
  16701. }
  16702. for (var i = 0; i < textures.length; i++) {
  16703. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16704. }
  16705. this._gl.uniform1iv(uniform, this._textureUnits);
  16706. for (var index = 0; index < textures.length; index++) {
  16707. this._setTexture(this._textureUnits[index], textures[index], true);
  16708. }
  16709. };
  16710. /** @hidden */
  16711. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16712. var internalTexture = texture.getInternalTexture();
  16713. if (!internalTexture) {
  16714. return;
  16715. }
  16716. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16717. var value = texture.anisotropicFilteringLevel;
  16718. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16719. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16720. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16721. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16722. }
  16723. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16724. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16725. internalTexture._cachedAnisotropicFilteringLevel = value;
  16726. }
  16727. };
  16728. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16729. this._bindTextureDirectly(target, texture, true, true);
  16730. this._gl.texParameterf(target, parameter, value);
  16731. };
  16732. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16733. if (texture) {
  16734. this._bindTextureDirectly(target, texture, true, true);
  16735. }
  16736. this._gl.texParameteri(target, parameter, value);
  16737. };
  16738. /**
  16739. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16740. * @param x defines the x coordinate of the rectangle where pixels must be read
  16741. * @param y defines the y coordinate of the rectangle where pixels must be read
  16742. * @param width defines the width of the rectangle where pixels must be read
  16743. * @param height defines the height of the rectangle where pixels must be read
  16744. * @returns a Uint8Array containing RGBA colors
  16745. */
  16746. Engine.prototype.readPixels = function (x, y, width, height) {
  16747. var data = new Uint8Array(height * width * 4);
  16748. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16749. return data;
  16750. };
  16751. /**
  16752. * Add an externaly attached data from its key.
  16753. * This method call will fail and return false, if such key already exists.
  16754. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16755. * @param key the unique key that identifies the data
  16756. * @param data the data object to associate to the key for this Engine instance
  16757. * @return true if no such key were already present and the data was added successfully, false otherwise
  16758. */
  16759. Engine.prototype.addExternalData = function (key, data) {
  16760. if (!this._externalData) {
  16761. this._externalData = new BABYLON.StringDictionary();
  16762. }
  16763. return this._externalData.add(key, data);
  16764. };
  16765. /**
  16766. * Get an externaly attached data from its key
  16767. * @param key the unique key that identifies the data
  16768. * @return the associated data, if present (can be null), or undefined if not present
  16769. */
  16770. Engine.prototype.getExternalData = function (key) {
  16771. if (!this._externalData) {
  16772. this._externalData = new BABYLON.StringDictionary();
  16773. }
  16774. return this._externalData.get(key);
  16775. };
  16776. /**
  16777. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16778. * @param key the unique key that identifies the data
  16779. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16780. * @return the associated data, can be null if the factory returned null.
  16781. */
  16782. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16783. if (!this._externalData) {
  16784. this._externalData = new BABYLON.StringDictionary();
  16785. }
  16786. return this._externalData.getOrAddWithFactory(key, factory);
  16787. };
  16788. /**
  16789. * Remove an externaly attached data from the Engine instance
  16790. * @param key the unique key that identifies the data
  16791. * @return true if the data was successfully removed, false if it doesn't exist
  16792. */
  16793. Engine.prototype.removeExternalData = function (key) {
  16794. if (!this._externalData) {
  16795. this._externalData = new BABYLON.StringDictionary();
  16796. }
  16797. return this._externalData.remove(key);
  16798. };
  16799. /**
  16800. * Unbind all vertex attributes from the webGL context
  16801. */
  16802. Engine.prototype.unbindAllAttributes = function () {
  16803. if (this._mustWipeVertexAttributes) {
  16804. this._mustWipeVertexAttributes = false;
  16805. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16806. this._gl.disableVertexAttribArray(i);
  16807. this._vertexAttribArraysEnabled[i] = false;
  16808. this._currentBufferPointers[i].active = false;
  16809. }
  16810. return;
  16811. }
  16812. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16813. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16814. continue;
  16815. }
  16816. this._gl.disableVertexAttribArray(i);
  16817. this._vertexAttribArraysEnabled[i] = false;
  16818. this._currentBufferPointers[i].active = false;
  16819. }
  16820. };
  16821. /**
  16822. * 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
  16823. */
  16824. Engine.prototype.releaseEffects = function () {
  16825. for (var name in this._compiledEffects) {
  16826. this._deleteProgram(this._compiledEffects[name]._program);
  16827. }
  16828. this._compiledEffects = {};
  16829. };
  16830. /**
  16831. * Dispose and release all associated resources
  16832. */
  16833. Engine.prototype.dispose = function () {
  16834. this.hideLoadingUI();
  16835. this.stopRenderLoop();
  16836. // Release postProcesses
  16837. while (this.postProcesses.length) {
  16838. this.postProcesses[0].dispose();
  16839. }
  16840. // Empty texture
  16841. if (this._emptyTexture) {
  16842. this._releaseTexture(this._emptyTexture);
  16843. this._emptyTexture = null;
  16844. }
  16845. if (this._emptyCubeTexture) {
  16846. this._releaseTexture(this._emptyCubeTexture);
  16847. this._emptyCubeTexture = null;
  16848. }
  16849. // Rescale PP
  16850. if (this._rescalePostProcess) {
  16851. this._rescalePostProcess.dispose();
  16852. }
  16853. // Release scenes
  16854. while (this.scenes.length) {
  16855. this.scenes[0].dispose();
  16856. }
  16857. // Release audio engine
  16858. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16859. Engine.audioEngine.dispose();
  16860. }
  16861. // Release effects
  16862. this.releaseEffects();
  16863. // Unbind
  16864. this.unbindAllAttributes();
  16865. this._boundUniforms = [];
  16866. if (this._dummyFramebuffer) {
  16867. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16868. }
  16869. //WebVR
  16870. this.disableVR();
  16871. // Events
  16872. if (BABYLON.Tools.IsWindowObjectExist()) {
  16873. window.removeEventListener("blur", this._onBlur);
  16874. window.removeEventListener("focus", this._onFocus);
  16875. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16876. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16877. if (this._renderingCanvas) {
  16878. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16879. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16880. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16881. if (!this._doNotHandleContextLost) {
  16882. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16883. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16884. }
  16885. }
  16886. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16887. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16888. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16889. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16890. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16891. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16892. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16893. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16894. if (this._onVrDisplayConnect) {
  16895. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16896. if (this._onVrDisplayDisconnect) {
  16897. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16898. }
  16899. if (this._onVrDisplayPresentChange) {
  16900. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16901. }
  16902. this._onVrDisplayConnect = null;
  16903. this._onVrDisplayDisconnect = null;
  16904. }
  16905. }
  16906. // Remove from Instances
  16907. var index = Engine.Instances.indexOf(this);
  16908. if (index >= 0) {
  16909. Engine.Instances.splice(index, 1);
  16910. }
  16911. this._workingCanvas = null;
  16912. this._workingContext = null;
  16913. this._currentBufferPointers = [];
  16914. this._renderingCanvas = null;
  16915. this._currentProgram = null;
  16916. this._bindedRenderFunction = null;
  16917. this.onResizeObservable.clear();
  16918. this.onCanvasBlurObservable.clear();
  16919. this.onCanvasFocusObservable.clear();
  16920. this.onCanvasPointerOutObservable.clear();
  16921. this.onBeginFrameObservable.clear();
  16922. this.onEndFrameObservable.clear();
  16923. BABYLON.Effect.ResetCache();
  16924. // Abort active requests
  16925. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16926. var request = _a[_i];
  16927. request.abort();
  16928. }
  16929. };
  16930. // Loading screen
  16931. /**
  16932. * Display the loading screen
  16933. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16934. */
  16935. Engine.prototype.displayLoadingUI = function () {
  16936. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16937. return;
  16938. }
  16939. var loadingScreen = this.loadingScreen;
  16940. if (loadingScreen) {
  16941. loadingScreen.displayLoadingUI();
  16942. }
  16943. };
  16944. /**
  16945. * Hide the loading screen
  16946. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16947. */
  16948. Engine.prototype.hideLoadingUI = function () {
  16949. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16950. return;
  16951. }
  16952. var loadingScreen = this.loadingScreen;
  16953. if (loadingScreen) {
  16954. loadingScreen.hideLoadingUI();
  16955. }
  16956. };
  16957. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16958. /**
  16959. * Gets the current loading screen object
  16960. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16961. */
  16962. get: function () {
  16963. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16964. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16965. return this._loadingScreen;
  16966. },
  16967. /**
  16968. * Sets the current loading screen object
  16969. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16970. */
  16971. set: function (loadingScreen) {
  16972. this._loadingScreen = loadingScreen;
  16973. },
  16974. enumerable: true,
  16975. configurable: true
  16976. });
  16977. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16978. /**
  16979. * Sets the current loading screen text
  16980. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16981. */
  16982. set: function (text) {
  16983. this.loadingScreen.loadingUIText = text;
  16984. },
  16985. enumerable: true,
  16986. configurable: true
  16987. });
  16988. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16989. /**
  16990. * Sets the current loading screen background color
  16991. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16992. */
  16993. set: function (color) {
  16994. this.loadingScreen.loadingUIBackgroundColor = color;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. /**
  17000. * Attach a new callback raised when context lost event is fired
  17001. * @param callback defines the callback to call
  17002. */
  17003. Engine.prototype.attachContextLostEvent = function (callback) {
  17004. if (this._renderingCanvas) {
  17005. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17006. }
  17007. };
  17008. /**
  17009. * Attach a new callback raised when context restored event is fired
  17010. * @param callback defines the callback to call
  17011. */
  17012. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17013. if (this._renderingCanvas) {
  17014. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17015. }
  17016. };
  17017. /**
  17018. * Gets the source code of the vertex shader associated with a specific webGL program
  17019. * @param program defines the program to use
  17020. * @returns a string containing the source code of the vertex shader associated with the program
  17021. */
  17022. Engine.prototype.getVertexShaderSource = function (program) {
  17023. var shaders = this._gl.getAttachedShaders(program);
  17024. if (!shaders) {
  17025. return null;
  17026. }
  17027. return this._gl.getShaderSource(shaders[0]);
  17028. };
  17029. /**
  17030. * Gets the source code of the fragment shader associated with a specific webGL program
  17031. * @param program defines the program to use
  17032. * @returns a string containing the source code of the fragment shader associated with the program
  17033. */
  17034. Engine.prototype.getFragmentShaderSource = function (program) {
  17035. var shaders = this._gl.getAttachedShaders(program);
  17036. if (!shaders) {
  17037. return null;
  17038. }
  17039. return this._gl.getShaderSource(shaders[1]);
  17040. };
  17041. /**
  17042. * Get the current error code of the webGL context
  17043. * @returns the error code
  17044. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17045. */
  17046. Engine.prototype.getError = function () {
  17047. return this._gl.getError();
  17048. };
  17049. // FPS
  17050. /**
  17051. * Gets the current framerate
  17052. * @returns a number representing the framerate
  17053. */
  17054. Engine.prototype.getFps = function () {
  17055. return this._fps;
  17056. };
  17057. /**
  17058. * Gets the time spent between current and previous frame
  17059. * @returns a number representing the delta time in ms
  17060. */
  17061. Engine.prototype.getDeltaTime = function () {
  17062. return this._deltaTime;
  17063. };
  17064. Engine.prototype._measureFps = function () {
  17065. this._performanceMonitor.sampleFrame();
  17066. this._fps = this._performanceMonitor.averageFPS;
  17067. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17068. };
  17069. /** @hidden */
  17070. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17071. if (faceIndex === void 0) { faceIndex = -1; }
  17072. if (level === void 0) { level = 0; }
  17073. if (buffer === void 0) { buffer = null; }
  17074. var gl = this._gl;
  17075. if (!this._dummyFramebuffer) {
  17076. var dummy = gl.createFramebuffer();
  17077. if (!dummy) {
  17078. throw new Error("Unable to create dummy framebuffer");
  17079. }
  17080. this._dummyFramebuffer = dummy;
  17081. }
  17082. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17083. if (faceIndex > -1) {
  17084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17085. }
  17086. else {
  17087. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17088. }
  17089. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17090. switch (readType) {
  17091. case gl.UNSIGNED_BYTE:
  17092. if (!buffer) {
  17093. buffer = new Uint8Array(4 * width * height);
  17094. }
  17095. readType = gl.UNSIGNED_BYTE;
  17096. break;
  17097. default:
  17098. if (!buffer) {
  17099. buffer = new Float32Array(4 * width * height);
  17100. }
  17101. readType = gl.FLOAT;
  17102. break;
  17103. }
  17104. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17105. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17106. return buffer;
  17107. };
  17108. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17109. if (this._webGLVersion > 1) {
  17110. return this._caps.colorBufferFloat;
  17111. }
  17112. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17113. };
  17114. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17115. if (this._webGLVersion > 1) {
  17116. return this._caps.colorBufferFloat;
  17117. }
  17118. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17119. };
  17120. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17121. Engine.prototype._canRenderToFramebuffer = function (type) {
  17122. var gl = this._gl;
  17123. //clear existing errors
  17124. while (gl.getError() !== gl.NO_ERROR) { }
  17125. var successful = true;
  17126. var texture = gl.createTexture();
  17127. gl.bindTexture(gl.TEXTURE_2D, texture);
  17128. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17129. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17131. var fb = gl.createFramebuffer();
  17132. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17134. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17135. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17136. successful = successful && (gl.getError() === gl.NO_ERROR);
  17137. //try render by clearing frame buffer's color buffer
  17138. if (successful) {
  17139. gl.clear(gl.COLOR_BUFFER_BIT);
  17140. successful = successful && (gl.getError() === gl.NO_ERROR);
  17141. }
  17142. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17143. if (successful) {
  17144. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17145. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17146. var readFormat = gl.RGBA;
  17147. var readType = gl.UNSIGNED_BYTE;
  17148. var buffer = new Uint8Array(4);
  17149. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17150. successful = successful && (gl.getError() === gl.NO_ERROR);
  17151. }
  17152. //clean up
  17153. gl.deleteTexture(texture);
  17154. gl.deleteFramebuffer(fb);
  17155. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17156. //clear accumulated errors
  17157. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17158. return successful;
  17159. };
  17160. /** @hidden */
  17161. Engine.prototype._getWebGLTextureType = function (type) {
  17162. if (this._webGLVersion === 1) {
  17163. switch (type) {
  17164. case Engine.TEXTURETYPE_FLOAT:
  17165. return this._gl.FLOAT;
  17166. case Engine.TEXTURETYPE_HALF_FLOAT:
  17167. return this._gl.HALF_FLOAT_OES;
  17168. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17169. return this._gl.UNSIGNED_BYTE;
  17170. }
  17171. return this._gl.UNSIGNED_BYTE;
  17172. }
  17173. switch (type) {
  17174. case Engine.TEXTURETYPE_BYTE:
  17175. return this._gl.BYTE;
  17176. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17177. return this._gl.UNSIGNED_BYTE;
  17178. case Engine.TEXTURETYPE_SHORT:
  17179. return this._gl.SHORT;
  17180. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17181. return this._gl.UNSIGNED_SHORT;
  17182. case Engine.TEXTURETYPE_INT:
  17183. return this._gl.INT;
  17184. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17185. return this._gl.UNSIGNED_INT;
  17186. case Engine.TEXTURETYPE_FLOAT:
  17187. return this._gl.FLOAT;
  17188. case Engine.TEXTURETYPE_HALF_FLOAT:
  17189. return this._gl.HALF_FLOAT;
  17190. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17191. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17192. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17193. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17194. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17195. return this._gl.UNSIGNED_SHORT_5_6_5;
  17196. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17197. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17198. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17199. return this._gl.UNSIGNED_INT_24_8;
  17200. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17201. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17202. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17203. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17204. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17205. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17206. }
  17207. return this._gl.UNSIGNED_BYTE;
  17208. };
  17209. ;
  17210. Engine.prototype._getInternalFormat = function (format) {
  17211. var internalFormat = this._gl.RGBA;
  17212. switch (format) {
  17213. case Engine.TEXTUREFORMAT_ALPHA:
  17214. internalFormat = this._gl.ALPHA;
  17215. break;
  17216. case Engine.TEXTUREFORMAT_LUMINANCE:
  17217. internalFormat = this._gl.LUMINANCE;
  17218. break;
  17219. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17220. internalFormat = this._gl.LUMINANCE_ALPHA;
  17221. break;
  17222. case Engine.TEXTUREFORMAT_RED:
  17223. internalFormat = this._gl.RED;
  17224. break;
  17225. case Engine.TEXTUREFORMAT_RG:
  17226. internalFormat = this._gl.RG;
  17227. break;
  17228. case Engine.TEXTUREFORMAT_RGB:
  17229. internalFormat = this._gl.RGB;
  17230. break;
  17231. case Engine.TEXTUREFORMAT_RGBA:
  17232. internalFormat = this._gl.RGBA;
  17233. break;
  17234. }
  17235. if (this._webGLVersion > 1) {
  17236. switch (format) {
  17237. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17238. internalFormat = this._gl.RED_INTEGER;
  17239. break;
  17240. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17241. internalFormat = this._gl.RG_INTEGER;
  17242. break;
  17243. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17244. internalFormat = this._gl.RGB_INTEGER;
  17245. break;
  17246. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17247. internalFormat = this._gl.RGBA_INTEGER;
  17248. break;
  17249. }
  17250. }
  17251. return internalFormat;
  17252. };
  17253. /** @hidden */
  17254. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17255. if (this._webGLVersion === 1) {
  17256. if (format !== undefined) {
  17257. switch (format) {
  17258. case Engine.TEXTUREFORMAT_ALPHA:
  17259. return this._gl.ALPHA;
  17260. case Engine.TEXTUREFORMAT_LUMINANCE:
  17261. return this._gl.LUMINANCE;
  17262. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17263. return this._gl.LUMINANCE_ALPHA;
  17264. }
  17265. }
  17266. return this._gl.RGBA;
  17267. }
  17268. switch (type) {
  17269. case Engine.TEXTURETYPE_BYTE:
  17270. switch (format) {
  17271. case Engine.TEXTUREFORMAT_RED:
  17272. return this._gl.R8_SNORM;
  17273. case Engine.TEXTUREFORMAT_RG:
  17274. return this._gl.RG8_SNORM;
  17275. case Engine.TEXTUREFORMAT_RGB:
  17276. return this._gl.RGB8_SNORM;
  17277. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17278. return this._gl.R8I;
  17279. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17280. return this._gl.RG8I;
  17281. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17282. return this._gl.RGB8I;
  17283. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17284. return this._gl.RGBA8I;
  17285. default:
  17286. return this._gl.RGBA8_SNORM;
  17287. }
  17288. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17289. switch (format) {
  17290. case Engine.TEXTUREFORMAT_RED:
  17291. return this._gl.R8;
  17292. case Engine.TEXTUREFORMAT_RG:
  17293. return this._gl.RG8;
  17294. case Engine.TEXTUREFORMAT_RGB:
  17295. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17296. case Engine.TEXTUREFORMAT_RGBA:
  17297. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17298. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17299. return this._gl.R8UI;
  17300. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17301. return this._gl.RG8UI;
  17302. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17303. return this._gl.RGB8UI;
  17304. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17305. return this._gl.RGBA8UI;
  17306. default:
  17307. return this._gl.RGBA8;
  17308. }
  17309. case Engine.TEXTURETYPE_SHORT:
  17310. switch (format) {
  17311. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17312. return this._gl.R16I;
  17313. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17314. return this._gl.RG16I;
  17315. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17316. return this._gl.RGB16I;
  17317. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17318. return this._gl.RGBA16I;
  17319. default:
  17320. return this._gl.RGBA16I;
  17321. }
  17322. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17323. switch (format) {
  17324. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17325. return this._gl.R16UI;
  17326. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17327. return this._gl.RG16UI;
  17328. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17329. return this._gl.RGB16UI;
  17330. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17331. return this._gl.RGBA16UI;
  17332. default:
  17333. return this._gl.RGBA16UI;
  17334. }
  17335. case Engine.TEXTURETYPE_INT:
  17336. switch (format) {
  17337. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17338. return this._gl.R32I;
  17339. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17340. return this._gl.RG32I;
  17341. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17342. return this._gl.RGB32I;
  17343. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17344. return this._gl.RGBA32I;
  17345. default:
  17346. return this._gl.RGBA32I;
  17347. }
  17348. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17349. switch (format) {
  17350. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17351. return this._gl.R32UI;
  17352. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17353. return this._gl.RG32UI;
  17354. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17355. return this._gl.RGB32UI;
  17356. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17357. return this._gl.RGBA32UI;
  17358. default:
  17359. return this._gl.RGBA32UI;
  17360. }
  17361. case Engine.TEXTURETYPE_FLOAT:
  17362. switch (format) {
  17363. case Engine.TEXTUREFORMAT_RED:
  17364. return this._gl.R32F; // By default. Other possibility is R16F.
  17365. case Engine.TEXTUREFORMAT_RG:
  17366. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17367. case Engine.TEXTUREFORMAT_RGB:
  17368. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17369. case Engine.TEXTUREFORMAT_RGBA:
  17370. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17371. default:
  17372. return this._gl.RGBA32F;
  17373. }
  17374. case Engine.TEXTURETYPE_HALF_FLOAT:
  17375. switch (format) {
  17376. case Engine.TEXTUREFORMAT_RED:
  17377. return this._gl.R16F;
  17378. case Engine.TEXTUREFORMAT_RG:
  17379. return this._gl.RG16F;
  17380. case Engine.TEXTUREFORMAT_RGB:
  17381. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17382. case Engine.TEXTUREFORMAT_RGBA:
  17383. return this._gl.RGBA16F;
  17384. default:
  17385. return this._gl.RGBA16F;
  17386. }
  17387. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17388. return this._gl.RGB565;
  17389. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17390. return this._gl.R11F_G11F_B10F;
  17391. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17392. return this._gl.RGB9_E5;
  17393. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17394. return this._gl.RGBA4;
  17395. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17396. return this._gl.RGB5_A1;
  17397. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17398. switch (format) {
  17399. case Engine.TEXTUREFORMAT_RGBA:
  17400. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17401. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17402. return this._gl.RGB10_A2UI;
  17403. default:
  17404. return this._gl.RGB10_A2;
  17405. }
  17406. }
  17407. return this._gl.RGBA8;
  17408. };
  17409. ;
  17410. /** @hidden */
  17411. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17412. if (type === Engine.TEXTURETYPE_FLOAT) {
  17413. return this._gl.RGBA32F;
  17414. }
  17415. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17416. return this._gl.RGBA16F;
  17417. }
  17418. return this._gl.RGBA8;
  17419. };
  17420. ;
  17421. /** @hidden */
  17422. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17423. var _this = this;
  17424. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17425. this._activeRequests.push(request);
  17426. request.onCompleteObservable.add(function (request) {
  17427. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17428. });
  17429. return request;
  17430. };
  17431. /** @hidden */
  17432. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17433. var _this = this;
  17434. return new Promise(function (resolve, reject) {
  17435. _this._loadFile(url, function (data) {
  17436. resolve(data);
  17437. }, undefined, database, useArrayBuffer, function (request, exception) {
  17438. reject(exception);
  17439. });
  17440. });
  17441. };
  17442. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17443. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17444. var onload = function (data) {
  17445. loadedFiles[index] = data;
  17446. loadedFiles._internalCount++;
  17447. if (loadedFiles._internalCount === 6) {
  17448. onfinish(loadedFiles);
  17449. }
  17450. };
  17451. var onerror = function (request, exception) {
  17452. if (onErrorCallBack && request) {
  17453. onErrorCallBack(request.status + " " + request.statusText, exception);
  17454. }
  17455. };
  17456. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17457. };
  17458. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17459. if (onError === void 0) { onError = null; }
  17460. var loadedFiles = [];
  17461. loadedFiles._internalCount = 0;
  17462. for (var index = 0; index < 6; index++) {
  17463. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17464. }
  17465. };
  17466. // Statics
  17467. /**
  17468. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17469. * @returns true if the engine can be created
  17470. * @ignorenaming
  17471. */
  17472. Engine.isSupported = function () {
  17473. try {
  17474. var tempcanvas = document.createElement("canvas");
  17475. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17476. return gl != null && !!window.WebGLRenderingContext;
  17477. }
  17478. catch (e) {
  17479. return false;
  17480. }
  17481. };
  17482. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17483. Engine.ExceptionList = [
  17484. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17485. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17486. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17487. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17488. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17489. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17490. ];
  17491. /** Gets the list of created engines */
  17492. Engine.Instances = new Array();
  17493. /**
  17494. * Hidden
  17495. */
  17496. Engine._TextureLoaders = [];
  17497. // Const statics
  17498. /** Defines that alpha blending is disabled */
  17499. Engine.ALPHA_DISABLE = 0;
  17500. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17501. Engine.ALPHA_ADD = 1;
  17502. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17503. Engine.ALPHA_COMBINE = 2;
  17504. /** Defines that alpha blending to DEST - SRC * DEST */
  17505. Engine.ALPHA_SUBTRACT = 3;
  17506. /** Defines that alpha blending to SRC * DEST */
  17507. Engine.ALPHA_MULTIPLY = 4;
  17508. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17509. Engine.ALPHA_MAXIMIZED = 5;
  17510. /** Defines that alpha blending to SRC + DEST */
  17511. Engine.ALPHA_ONEONE = 6;
  17512. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17513. Engine.ALPHA_PREMULTIPLIED = 7;
  17514. /**
  17515. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17516. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17517. */
  17518. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17519. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17520. Engine.ALPHA_INTERPOLATE = 9;
  17521. /**
  17522. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17523. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17524. */
  17525. Engine.ALPHA_SCREENMODE = 10;
  17526. /** Defines that the ressource is not delayed*/
  17527. Engine.DELAYLOADSTATE_NONE = 0;
  17528. /** Defines that the ressource was successfully delay loaded */
  17529. Engine.DELAYLOADSTATE_LOADED = 1;
  17530. /** Defines that the ressource is currently delay loading */
  17531. Engine.DELAYLOADSTATE_LOADING = 2;
  17532. /** Defines that the ressource is delayed and has not started loading */
  17533. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17534. // Depht or Stencil test Constants.
  17535. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17536. Engine.NEVER = 0x0200;
  17537. /** 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 */
  17538. Engine.ALWAYS = 0x0207;
  17539. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17540. Engine.LESS = 0x0201;
  17541. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17542. Engine.EQUAL = 0x0202;
  17543. /** 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 */
  17544. Engine.LEQUAL = 0x0203;
  17545. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17546. Engine.GREATER = 0x0204;
  17547. /** 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 */
  17548. Engine.GEQUAL = 0x0206;
  17549. /** 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 */
  17550. Engine.NOTEQUAL = 0x0205;
  17551. // Stencil Actions Constants.
  17552. /** Passed to stencilOperation to specify that stencil value must be kept */
  17553. Engine.KEEP = 0x1E00;
  17554. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17555. Engine.REPLACE = 0x1E01;
  17556. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17557. Engine.INCR = 0x1E02;
  17558. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17559. Engine.DECR = 0x1E03;
  17560. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17561. Engine.INVERT = 0x150A;
  17562. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17563. Engine.INCR_WRAP = 0x8507;
  17564. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17565. Engine.DECR_WRAP = 0x8508;
  17566. /** Texture is not repeating outside of 0..1 UVs */
  17567. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17568. /** Texture is repeating outside of 0..1 UVs */
  17569. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17570. /** Texture is repeating and mirrored */
  17571. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17572. /** ALPHA */
  17573. Engine.TEXTUREFORMAT_ALPHA = 0;
  17574. /** LUMINANCE */
  17575. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17576. /** LUMINANCE_ALPHA */
  17577. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17578. /** RGB */
  17579. Engine.TEXTUREFORMAT_RGB = 4;
  17580. /** RGBA */
  17581. Engine.TEXTUREFORMAT_RGBA = 5;
  17582. /** RED */
  17583. Engine.TEXTUREFORMAT_RED = 6;
  17584. /** RED (2nd reference) */
  17585. Engine.TEXTUREFORMAT_R = 6;
  17586. /** RG */
  17587. Engine.TEXTUREFORMAT_RG = 7;
  17588. /** RED_INTEGER */
  17589. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17590. /** RED_INTEGER (2nd reference) */
  17591. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17592. /** RG_INTEGER */
  17593. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17594. /** RGB_INTEGER */
  17595. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17596. /** RGBA_INTEGER */
  17597. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17598. /** UNSIGNED_BYTE */
  17599. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17600. /** UNSIGNED_BYTE (2nd reference) */
  17601. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17602. /** FLOAT */
  17603. Engine.TEXTURETYPE_FLOAT = 1;
  17604. /** HALF_FLOAT */
  17605. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17606. /** BYTE */
  17607. Engine.TEXTURETYPE_BYTE = 3;
  17608. /** SHORT */
  17609. Engine.TEXTURETYPE_SHORT = 4;
  17610. /** UNSIGNED_SHORT */
  17611. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17612. /** INT */
  17613. Engine.TEXTURETYPE_INT = 6;
  17614. /** UNSIGNED_INT */
  17615. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17616. /** UNSIGNED_SHORT_4_4_4_4 */
  17617. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17618. /** UNSIGNED_SHORT_5_5_5_1 */
  17619. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17620. /** UNSIGNED_SHORT_5_6_5 */
  17621. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17622. /** UNSIGNED_INT_2_10_10_10_REV */
  17623. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17624. /** UNSIGNED_INT_24_8 */
  17625. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17626. /** UNSIGNED_INT_10F_11F_11F_REV */
  17627. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17628. /** UNSIGNED_INT_5_9_9_9_REV */
  17629. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17630. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17631. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17632. /** nearest is mag = nearest and min = nearest and mip = linear */
  17633. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17634. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17635. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17636. /** Trilinear is mag = linear and min = linear and mip = linear */
  17637. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17638. /** nearest is mag = nearest and min = nearest and mip = linear */
  17639. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17640. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17641. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17642. /** Trilinear is mag = linear and min = linear and mip = linear */
  17643. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17644. /** mag = nearest and min = nearest and mip = nearest */
  17645. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17646. /** mag = nearest and min = linear and mip = nearest */
  17647. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17648. /** mag = nearest and min = linear and mip = linear */
  17649. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17650. /** mag = nearest and min = linear and mip = none */
  17651. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17652. /** mag = nearest and min = nearest and mip = none */
  17653. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17654. /** mag = linear and min = nearest and mip = nearest */
  17655. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17656. /** mag = linear and min = nearest and mip = linear */
  17657. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17658. /** mag = linear and min = linear and mip = none */
  17659. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17660. /** mag = linear and min = nearest and mip = none */
  17661. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17662. /** Explicit coordinates mode */
  17663. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17664. /** Spherical coordinates mode */
  17665. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17666. /** Planar coordinates mode */
  17667. Engine.TEXTURE_PLANAR_MODE = 2;
  17668. /** Cubic coordinates mode */
  17669. Engine.TEXTURE_CUBIC_MODE = 3;
  17670. /** Projection coordinates mode */
  17671. Engine.TEXTURE_PROJECTION_MODE = 4;
  17672. /** Skybox coordinates mode */
  17673. Engine.TEXTURE_SKYBOX_MODE = 5;
  17674. /** Inverse Cubic coordinates mode */
  17675. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17676. /** Equirectangular coordinates mode */
  17677. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17678. /** Equirectangular Fixed coordinates mode */
  17679. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17680. /** Equirectangular Fixed Mirrored coordinates mode */
  17681. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17682. // Texture rescaling mode
  17683. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17684. Engine.SCALEMODE_FLOOR = 1;
  17685. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17686. Engine.SCALEMODE_NEAREST = 2;
  17687. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17688. Engine.SCALEMODE_CEILING = 3;
  17689. // Updatable statics so stick with vars here
  17690. /**
  17691. * Gets or sets the epsilon value used by collision engine
  17692. */
  17693. Engine.CollisionsEpsilon = 0.001;
  17694. /**
  17695. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17696. */
  17697. Engine.CodeRepository = "src/";
  17698. /**
  17699. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17700. */
  17701. Engine.ShadersRepository = "src/Shaders/";
  17702. return Engine;
  17703. }());
  17704. BABYLON.Engine = Engine;
  17705. })(BABYLON || (BABYLON = {}));
  17706. //# sourceMappingURL=babylon.engine.js.map
  17707. var BABYLON;
  17708. (function (BABYLON) {
  17709. /**
  17710. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17711. */
  17712. var Node = /** @class */ (function () {
  17713. /**
  17714. * Creates a new Node
  17715. * @param {string} name - the name and id to be given to this node
  17716. * @param {BABYLON.Scene} the scene this node will be added to
  17717. */
  17718. function Node(name, scene) {
  17719. if (scene === void 0) { scene = null; }
  17720. /**
  17721. * Gets or sets a string used to store user defined state for the node
  17722. */
  17723. this.state = "";
  17724. /**
  17725. * Gets or sets an object used to store user defined information for the node
  17726. */
  17727. this.metadata = null;
  17728. /**
  17729. * Gets or sets a boolean used to define if the node must be serialized
  17730. */
  17731. this.doNotSerialize = false;
  17732. /** @hidden */
  17733. this._isDisposed = false;
  17734. /**
  17735. * Gets a list of Animations associated with the node
  17736. */
  17737. this.animations = new Array();
  17738. this._ranges = {};
  17739. this._isEnabled = true;
  17740. this._isParentEnabled = true;
  17741. this._isReady = true;
  17742. /** @hidden */
  17743. this._currentRenderId = -1;
  17744. this._parentRenderId = -1;
  17745. this._childRenderId = -1;
  17746. /** @hidden */
  17747. this._worldMatrix = BABYLON.Matrix.Identity();
  17748. /** @hidden */
  17749. this._worldMatrixDeterminant = 0;
  17750. this._animationPropertiesOverride = null;
  17751. /**
  17752. * An event triggered when the mesh is disposed
  17753. */
  17754. this.onDisposeObservable = new BABYLON.Observable();
  17755. // Behaviors
  17756. this._behaviors = new Array();
  17757. this.name = name;
  17758. this.id = name;
  17759. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17760. this.uniqueId = this._scene.getUniqueId();
  17761. this._initCache();
  17762. this._scene.rootNodes.push(this);
  17763. }
  17764. /**
  17765. * Add a new node constructor
  17766. * @param type defines the type name of the node to construct
  17767. * @param constructorFunc defines the constructor function
  17768. */
  17769. Node.AddNodeConstructor = function (type, constructorFunc) {
  17770. this._NodeConstructors[type] = constructorFunc;
  17771. };
  17772. /**
  17773. * Returns a node constructor based on type name
  17774. * @param type defines the type name
  17775. * @param name defines the new node name
  17776. * @param scene defines the hosting scene
  17777. * @param options defines optional options to transmit to constructors
  17778. * @returns the new constructor or null
  17779. */
  17780. Node.Construct = function (type, name, scene, options) {
  17781. var constructorFunc = this._NodeConstructors[type];
  17782. if (!constructorFunc) {
  17783. return null;
  17784. }
  17785. return constructorFunc(name, scene, options);
  17786. };
  17787. /**
  17788. * Gets a boolean indicating if the node has been disposed
  17789. * @returns true if the node was disposed
  17790. */
  17791. Node.prototype.isDisposed = function () {
  17792. return this._isDisposed;
  17793. };
  17794. Object.defineProperty(Node.prototype, "parent", {
  17795. get: function () {
  17796. return this._parentNode;
  17797. },
  17798. /**
  17799. * Gets or sets the parent of the node
  17800. */
  17801. set: function (parent) {
  17802. if (this._parentNode === parent) {
  17803. return;
  17804. }
  17805. var previousParentNode = this._parentNode;
  17806. // Remove self from list of children of parent
  17807. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17808. var index = this._parentNode._children.indexOf(this);
  17809. if (index !== -1) {
  17810. this._parentNode._children.splice(index, 1);
  17811. }
  17812. if (!parent) {
  17813. // Need to add this node to the rootNodes
  17814. this._scene.rootNodes.push(this);
  17815. }
  17816. }
  17817. // Store new parent
  17818. this._parentNode = parent;
  17819. // Add as child to new parent
  17820. if (this._parentNode) {
  17821. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17822. this._parentNode._children = new Array();
  17823. }
  17824. this._parentNode._children.push(this);
  17825. if (!previousParentNode) {
  17826. // Need to remove from rootNodes
  17827. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17828. if (rootNodeIndex > -1) {
  17829. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17830. }
  17831. }
  17832. }
  17833. // Enabled state
  17834. this._syncParentEnabledState();
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17840. /**
  17841. * Gets or sets the animation properties override
  17842. */
  17843. get: function () {
  17844. if (!this._animationPropertiesOverride) {
  17845. return this._scene.animationPropertiesOverride;
  17846. }
  17847. return this._animationPropertiesOverride;
  17848. },
  17849. set: function (value) {
  17850. this._animationPropertiesOverride = value;
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. /**
  17856. * Gets a string idenfifying the name of the class
  17857. * @returns "Node" string
  17858. */
  17859. Node.prototype.getClassName = function () {
  17860. return "Node";
  17861. };
  17862. Object.defineProperty(Node.prototype, "onDispose", {
  17863. /**
  17864. * Sets a callback that will be raised when the node will be disposed
  17865. */
  17866. set: function (callback) {
  17867. if (this._onDisposeObserver) {
  17868. this.onDisposeObservable.remove(this._onDisposeObserver);
  17869. }
  17870. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. /**
  17876. * Gets the scene of the node
  17877. * @returns a {BABYLON.Scene}
  17878. */
  17879. Node.prototype.getScene = function () {
  17880. return this._scene;
  17881. };
  17882. /**
  17883. * Gets the engine of the node
  17884. * @returns a {BABYLON.Engine}
  17885. */
  17886. Node.prototype.getEngine = function () {
  17887. return this._scene.getEngine();
  17888. };
  17889. /**
  17890. * Attach a behavior to the node
  17891. * @see http://doc.babylonjs.com/features/behaviour
  17892. * @param behavior defines the behavior to attach
  17893. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  17894. * @returns the current Node
  17895. */
  17896. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  17897. var _this = this;
  17898. if (attachImmediately === void 0) { attachImmediately = false; }
  17899. var index = this._behaviors.indexOf(behavior);
  17900. if (index !== -1) {
  17901. return this;
  17902. }
  17903. behavior.init();
  17904. if (this._scene.isLoading && !attachImmediately) {
  17905. // We defer the attach when the scene will be loaded
  17906. this._scene.onDataLoadedObservable.addOnce(function () {
  17907. behavior.attach(_this);
  17908. });
  17909. }
  17910. else {
  17911. behavior.attach(this);
  17912. }
  17913. this._behaviors.push(behavior);
  17914. return this;
  17915. };
  17916. /**
  17917. * Remove an attached behavior
  17918. * @see http://doc.babylonjs.com/features/behaviour
  17919. * @param behavior defines the behavior to attach
  17920. * @returns the current Node
  17921. */
  17922. Node.prototype.removeBehavior = function (behavior) {
  17923. var index = this._behaviors.indexOf(behavior);
  17924. if (index === -1) {
  17925. return this;
  17926. }
  17927. this._behaviors[index].detach();
  17928. this._behaviors.splice(index, 1);
  17929. return this;
  17930. };
  17931. Object.defineProperty(Node.prototype, "behaviors", {
  17932. /**
  17933. * Gets the list of attached behaviors
  17934. * @see http://doc.babylonjs.com/features/behaviour
  17935. */
  17936. get: function () {
  17937. return this._behaviors;
  17938. },
  17939. enumerable: true,
  17940. configurable: true
  17941. });
  17942. /**
  17943. * Gets an attached behavior by name
  17944. * @param name defines the name of the behavior to look for
  17945. * @see http://doc.babylonjs.com/features/behaviour
  17946. * @returns null if behavior was not found else the requested behavior
  17947. */
  17948. Node.prototype.getBehaviorByName = function (name) {
  17949. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17950. var behavior = _a[_i];
  17951. if (behavior.name === name) {
  17952. return behavior;
  17953. }
  17954. }
  17955. return null;
  17956. };
  17957. /**
  17958. * Returns the latest update of the World matrix
  17959. * @returns a Matrix
  17960. */
  17961. Node.prototype.getWorldMatrix = function () {
  17962. if (this._currentRenderId !== this._scene.getRenderId()) {
  17963. this.computeWorldMatrix();
  17964. }
  17965. return this._worldMatrix;
  17966. };
  17967. /** @hidden */
  17968. Node.prototype._getWorldMatrixDeterminant = function () {
  17969. return this._worldMatrixDeterminant;
  17970. };
  17971. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17972. /**
  17973. * Returns directly the latest state of the mesh World matrix.
  17974. * A Matrix is returned.
  17975. */
  17976. get: function () {
  17977. return this._worldMatrix;
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. // override it in derived class if you add new variables to the cache
  17983. // and call the parent class method
  17984. /** @hidden */
  17985. Node.prototype._initCache = function () {
  17986. this._cache = {};
  17987. this._cache.parent = undefined;
  17988. };
  17989. /** @hidden */
  17990. Node.prototype.updateCache = function (force) {
  17991. if (!force && this.isSynchronized())
  17992. return;
  17993. this._cache.parent = this.parent;
  17994. this._updateCache();
  17995. };
  17996. // override it in derived class if you add new variables to the cache
  17997. // and call the parent class method if !ignoreParentClass
  17998. /** @hidden */
  17999. Node.prototype._updateCache = function (ignoreParentClass) {
  18000. };
  18001. // override it in derived class if you add new variables to the cache
  18002. /** @hidden */
  18003. Node.prototype._isSynchronized = function () {
  18004. return true;
  18005. };
  18006. /** @hidden */
  18007. Node.prototype._markSyncedWithParent = function () {
  18008. if (this._parentNode) {
  18009. this._parentRenderId = this._parentNode._childRenderId;
  18010. }
  18011. };
  18012. /** @hidden */
  18013. Node.prototype.isSynchronizedWithParent = function () {
  18014. if (!this._parentNode) {
  18015. return true;
  18016. }
  18017. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18018. return false;
  18019. }
  18020. return this._parentNode.isSynchronized();
  18021. };
  18022. /** @hidden */
  18023. Node.prototype.isSynchronized = function () {
  18024. if (this._cache.parent != this._parentNode) {
  18025. this._cache.parent = this._parentNode;
  18026. return false;
  18027. }
  18028. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18029. return false;
  18030. }
  18031. return this._isSynchronized();
  18032. };
  18033. /**
  18034. * Is this node ready to be used/rendered
  18035. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18036. * @return true if the node is ready
  18037. */
  18038. Node.prototype.isReady = function (completeCheck) {
  18039. if (completeCheck === void 0) { completeCheck = false; }
  18040. return this._isReady;
  18041. };
  18042. /**
  18043. * Is this node enabled?
  18044. * 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
  18045. * @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
  18046. * @return whether this node (and its parent) is enabled
  18047. */
  18048. Node.prototype.isEnabled = function (checkAncestors) {
  18049. if (checkAncestors === void 0) { checkAncestors = true; }
  18050. if (checkAncestors === false) {
  18051. return this._isEnabled;
  18052. }
  18053. if (!this._isEnabled) {
  18054. return false;
  18055. }
  18056. return this._isParentEnabled;
  18057. };
  18058. /** @hidden */
  18059. Node.prototype._syncParentEnabledState = function () {
  18060. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18061. if (this._children) {
  18062. this._children.forEach(function (c) {
  18063. c._syncParentEnabledState(); // Force children to update accordingly
  18064. });
  18065. }
  18066. };
  18067. /**
  18068. * Set the enabled state of this node
  18069. * @param value defines the new enabled state
  18070. */
  18071. Node.prototype.setEnabled = function (value) {
  18072. this._isEnabled = value;
  18073. this._syncParentEnabledState();
  18074. };
  18075. /**
  18076. * Is this node a descendant of the given node?
  18077. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18078. * @param ancestor defines the parent node to inspect
  18079. * @returns a boolean indicating if this node is a descendant of the given node
  18080. */
  18081. Node.prototype.isDescendantOf = function (ancestor) {
  18082. if (this.parent) {
  18083. if (this.parent === ancestor) {
  18084. return true;
  18085. }
  18086. return this.parent.isDescendantOf(ancestor);
  18087. }
  18088. return false;
  18089. };
  18090. /** @hidden */
  18091. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18092. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18093. if (!this._children) {
  18094. return;
  18095. }
  18096. for (var index = 0; index < this._children.length; index++) {
  18097. var item = this._children[index];
  18098. if (!predicate || predicate(item)) {
  18099. results.push(item);
  18100. }
  18101. if (!directDescendantsOnly) {
  18102. item._getDescendants(results, false, predicate);
  18103. }
  18104. }
  18105. };
  18106. /**
  18107. * Will return all nodes that have this node as ascendant
  18108. * @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
  18109. * @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
  18110. * @return all children nodes of all types
  18111. */
  18112. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18113. var results = new Array();
  18114. this._getDescendants(results, directDescendantsOnly, predicate);
  18115. return results;
  18116. };
  18117. /**
  18118. * Get all child-meshes of this node
  18119. * @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
  18120. * @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
  18121. * @returns an array of {BABYLON.AbstractMesh}
  18122. */
  18123. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18124. var results = [];
  18125. this._getDescendants(results, directDescendantsOnly, function (node) {
  18126. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18127. });
  18128. return results;
  18129. };
  18130. /**
  18131. * Get all child-transformNodes of this node
  18132. * @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
  18133. * @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
  18134. * @returns an array of {BABYLON.TransformNode}
  18135. */
  18136. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18137. var results = [];
  18138. this._getDescendants(results, directDescendantsOnly, function (node) {
  18139. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18140. });
  18141. return results;
  18142. };
  18143. /**
  18144. * Get all direct children of this node
  18145. * @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
  18146. * @returns an array of {BABYLON.Node}
  18147. */
  18148. Node.prototype.getChildren = function (predicate) {
  18149. return this.getDescendants(true, predicate);
  18150. };
  18151. /** @hidden */
  18152. Node.prototype._setReady = function (state) {
  18153. if (state === this._isReady) {
  18154. return;
  18155. }
  18156. if (!state) {
  18157. this._isReady = false;
  18158. return;
  18159. }
  18160. if (this.onReady) {
  18161. this.onReady(this);
  18162. }
  18163. this._isReady = true;
  18164. };
  18165. /**
  18166. * Get an animation by name
  18167. * @param name defines the name of the animation to look for
  18168. * @returns null if not found else the requested animation
  18169. */
  18170. Node.prototype.getAnimationByName = function (name) {
  18171. for (var i = 0; i < this.animations.length; i++) {
  18172. var animation = this.animations[i];
  18173. if (animation.name === name) {
  18174. return animation;
  18175. }
  18176. }
  18177. return null;
  18178. };
  18179. /**
  18180. * Creates an animation range for this node
  18181. * @param name defines the name of the range
  18182. * @param from defines the starting key
  18183. * @param to defines the end key
  18184. */
  18185. Node.prototype.createAnimationRange = function (name, from, to) {
  18186. // check name not already in use
  18187. if (!this._ranges[name]) {
  18188. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18189. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18190. if (this.animations[i]) {
  18191. this.animations[i].createRange(name, from, to);
  18192. }
  18193. }
  18194. }
  18195. };
  18196. /**
  18197. * Delete a specific animation range
  18198. * @param name defines the name of the range to delete
  18199. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18200. */
  18201. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18202. if (deleteFrames === void 0) { deleteFrames = true; }
  18203. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18204. if (this.animations[i]) {
  18205. this.animations[i].deleteRange(name, deleteFrames);
  18206. }
  18207. }
  18208. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18209. };
  18210. /**
  18211. * Get an animation range by name
  18212. * @param name defines the name of the animation range to look for
  18213. * @returns null if not found else the requested animation range
  18214. */
  18215. Node.prototype.getAnimationRange = function (name) {
  18216. return this._ranges[name];
  18217. };
  18218. /**
  18219. * Will start the animation sequence
  18220. * @param name defines the range frames for animation sequence
  18221. * @param loop defines if the animation should loop (false by default)
  18222. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18223. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18224. * @returns the object created for this animation. If range does not exist, it will return null
  18225. */
  18226. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18227. var range = this.getAnimationRange(name);
  18228. if (!range) {
  18229. return null;
  18230. }
  18231. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18232. };
  18233. /**
  18234. * Serialize animation ranges into a JSON compatible object
  18235. * @returns serialization object
  18236. */
  18237. Node.prototype.serializeAnimationRanges = function () {
  18238. var serializationRanges = [];
  18239. for (var name in this._ranges) {
  18240. var localRange = this._ranges[name];
  18241. if (!localRange) {
  18242. continue;
  18243. }
  18244. var range = {};
  18245. range.name = name;
  18246. range.from = localRange.from;
  18247. range.to = localRange.to;
  18248. serializationRanges.push(range);
  18249. }
  18250. return serializationRanges;
  18251. };
  18252. /**
  18253. * Computes the world matrix of the node
  18254. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18255. * @returns the world matrix
  18256. */
  18257. Node.prototype.computeWorldMatrix = function (force) {
  18258. if (!this._worldMatrix) {
  18259. this._worldMatrix = BABYLON.Matrix.Identity();
  18260. }
  18261. return this._worldMatrix;
  18262. };
  18263. /**
  18264. * Releases resources associated with this node.
  18265. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18266. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18267. */
  18268. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18269. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18270. if (!doNotRecurse) {
  18271. var nodes = this.getDescendants(true);
  18272. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18273. var node = nodes_1[_i];
  18274. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18275. }
  18276. }
  18277. else {
  18278. var transformNodes = this.getChildTransformNodes(true);
  18279. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18280. var transformNode = transformNodes_1[_a];
  18281. transformNode.parent = null;
  18282. transformNode.computeWorldMatrix(true);
  18283. }
  18284. }
  18285. if (!this.parent) {
  18286. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18287. if (rootNodeIndex > -1) {
  18288. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18289. }
  18290. }
  18291. else {
  18292. this.parent = null;
  18293. }
  18294. // Callback
  18295. this.onDisposeObservable.notifyObservers(this);
  18296. this.onDisposeObservable.clear();
  18297. // Behaviors
  18298. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18299. var behavior = _c[_b];
  18300. behavior.detach();
  18301. }
  18302. this._behaviors = [];
  18303. this._isDisposed = true;
  18304. };
  18305. /**
  18306. * Parse animation range data from a serialization object and store them into a given node
  18307. * @param node defines where to store the animation ranges
  18308. * @param parsedNode defines the serialization object to read data from
  18309. * @param scene defines the hosting scene
  18310. */
  18311. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18312. if (parsedNode.ranges) {
  18313. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18314. var data = parsedNode.ranges[index];
  18315. node.createAnimationRange(data.name, data.from, data.to);
  18316. }
  18317. }
  18318. };
  18319. Node._NodeConstructors = {};
  18320. __decorate([
  18321. BABYLON.serialize()
  18322. ], Node.prototype, "name", void 0);
  18323. __decorate([
  18324. BABYLON.serialize()
  18325. ], Node.prototype, "id", void 0);
  18326. __decorate([
  18327. BABYLON.serialize()
  18328. ], Node.prototype, "uniqueId", void 0);
  18329. __decorate([
  18330. BABYLON.serialize()
  18331. ], Node.prototype, "state", void 0);
  18332. __decorate([
  18333. BABYLON.serialize()
  18334. ], Node.prototype, "metadata", void 0);
  18335. return Node;
  18336. }());
  18337. BABYLON.Node = Node;
  18338. })(BABYLON || (BABYLON = {}));
  18339. //# sourceMappingURL=babylon.node.js.map
  18340. var BABYLON;
  18341. (function (BABYLON) {
  18342. // This matrix is used as a value to reset the bounding box.
  18343. var _identityMatrix = BABYLON.Matrix.Identity();
  18344. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18345. var BoundingSphere = /** @class */ (function () {
  18346. /**
  18347. * Creates a new bounding sphere
  18348. * @param min defines the minimum vector (in local space)
  18349. * @param max defines the maximum vector (in local space)
  18350. */
  18351. function BoundingSphere(min, max) {
  18352. this.center = BABYLON.Vector3.Zero();
  18353. this.centerWorld = BABYLON.Vector3.Zero();
  18354. this.reConstruct(min, max);
  18355. }
  18356. /**
  18357. * Recreates the entire bounding sphere from scratch
  18358. * @param min defines the new minimum vector (in local space)
  18359. * @param max defines the new maximum vector (in local space)
  18360. */
  18361. BoundingSphere.prototype.reConstruct = function (min, max) {
  18362. this.minimum = min.clone();
  18363. this.maximum = max.clone();
  18364. var distance = BABYLON.Vector3.Distance(min, max);
  18365. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18366. this.radius = distance * 0.5;
  18367. this.centerWorld.set(0, 0, 0);
  18368. this._update(_identityMatrix);
  18369. };
  18370. /**
  18371. * Scale the current bounding sphere by applying a scale factor
  18372. * @param factor defines the scale factor to apply
  18373. * @returns the current bounding box
  18374. */
  18375. BoundingSphere.prototype.scale = function (factor) {
  18376. var newRadius = this.radius * factor;
  18377. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18378. var min = this.center.subtract(_tempRadiusVector);
  18379. var max = this.center.add(_tempRadiusVector);
  18380. this.reConstruct(min, max);
  18381. return this;
  18382. };
  18383. // Methods
  18384. /** @hidden */
  18385. BoundingSphere.prototype._update = function (world) {
  18386. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18387. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18388. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18389. };
  18390. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18391. for (var i = 0; i < 6; i++) {
  18392. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18393. return false;
  18394. }
  18395. return true;
  18396. };
  18397. BoundingSphere.prototype.intersectsPoint = function (point) {
  18398. var x = this.centerWorld.x - point.x;
  18399. var y = this.centerWorld.y - point.y;
  18400. var z = this.centerWorld.z - point.z;
  18401. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18402. if (this.radiusWorld < distance)
  18403. return false;
  18404. return true;
  18405. };
  18406. // Statics
  18407. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18408. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18409. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18410. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18411. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18412. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18413. return false;
  18414. return true;
  18415. };
  18416. return BoundingSphere;
  18417. }());
  18418. BABYLON.BoundingSphere = BoundingSphere;
  18419. })(BABYLON || (BABYLON = {}));
  18420. //# sourceMappingURL=babylon.boundingSphere.js.map
  18421. var BABYLON;
  18422. (function (BABYLON) {
  18423. /**
  18424. * Class used to store bounding box information
  18425. */
  18426. var BoundingBox = /** @class */ (function () {
  18427. /**
  18428. * Creates a new bounding box
  18429. * @param min defines the minimum vector (in local space)
  18430. * @param max defines the maximum vector (in local space)
  18431. */
  18432. function BoundingBox(min, max) {
  18433. /**
  18434. * Gets the 8 vectors representing the bounding box in world space
  18435. */
  18436. this.vectorsWorld = new Array();
  18437. this.reConstruct(min, max);
  18438. }
  18439. // Methods
  18440. /**
  18441. * Recreates the entire bounding box from scratch
  18442. * @param min defines the new minimum vector (in local space)
  18443. * @param max defines the new maximum vector (in local space)
  18444. */
  18445. BoundingBox.prototype.reConstruct = function (min, max) {
  18446. this.minimum = min.clone();
  18447. this.maximum = max.clone();
  18448. // Bounding vectors
  18449. this.vectors = [
  18450. this.minimum.clone(),
  18451. this.maximum.clone(),
  18452. this.minimum.clone(),
  18453. this.minimum.clone(),
  18454. this.minimum.clone(),
  18455. this.maximum.clone(),
  18456. this.maximum.clone(),
  18457. this.maximum.clone()
  18458. ];
  18459. this.vectors[2].x = this.maximum.x;
  18460. this.vectors[3].y = this.maximum.y;
  18461. this.vectors[4].z = this.maximum.z;
  18462. this.vectors[5].z = this.minimum.z;
  18463. this.vectors[6].x = this.minimum.x;
  18464. this.vectors[7].y = this.minimum.y;
  18465. // OBB
  18466. this.center = this.maximum.add(this.minimum).scale(0.5);
  18467. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18468. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18469. // World
  18470. for (var index = 0; index < this.vectors.length; index++) {
  18471. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18472. }
  18473. this.minimumWorld = BABYLON.Vector3.Zero();
  18474. this.maximumWorld = BABYLON.Vector3.Zero();
  18475. this.centerWorld = BABYLON.Vector3.Zero();
  18476. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18477. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18478. };
  18479. /**
  18480. * Scale the current bounding box by applying a scale factor
  18481. * @param factor defines the scale factor to apply
  18482. * @returns the current bounding box
  18483. */
  18484. BoundingBox.prototype.scale = function (factor) {
  18485. var diff = this.maximum.subtract(this.minimum);
  18486. var distance = diff.length() * factor;
  18487. diff.normalize();
  18488. var newRadius = diff.scale(distance / 2);
  18489. var min = this.center.subtract(newRadius);
  18490. var max = this.center.add(newRadius);
  18491. this.reConstruct(min, max);
  18492. return this;
  18493. };
  18494. /**
  18495. * Gets the world matrix of the bounding box
  18496. * @returns a matrix
  18497. */
  18498. BoundingBox.prototype.getWorldMatrix = function () {
  18499. return this._worldMatrix;
  18500. };
  18501. /**
  18502. * Sets the world matrix stored in the bounding box
  18503. * @param matrix defines the matrix to store
  18504. * @returns current bounding box
  18505. */
  18506. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18507. this._worldMatrix.copyFrom(matrix);
  18508. return this;
  18509. };
  18510. /** @hidden */
  18511. BoundingBox.prototype._update = function (world) {
  18512. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18513. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18514. for (var index = 0; index < this.vectors.length; index++) {
  18515. var v = this.vectorsWorld[index];
  18516. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18517. if (v.x < this.minimumWorld.x)
  18518. this.minimumWorld.x = v.x;
  18519. if (v.y < this.minimumWorld.y)
  18520. this.minimumWorld.y = v.y;
  18521. if (v.z < this.minimumWorld.z)
  18522. this.minimumWorld.z = v.z;
  18523. if (v.x > this.maximumWorld.x)
  18524. this.maximumWorld.x = v.x;
  18525. if (v.y > this.maximumWorld.y)
  18526. this.maximumWorld.y = v.y;
  18527. if (v.z > this.maximumWorld.z)
  18528. this.maximumWorld.z = v.z;
  18529. }
  18530. // Extend
  18531. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18532. this.extendSizeWorld.scaleInPlace(0.5);
  18533. // OBB
  18534. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18535. this.centerWorld.scaleInPlace(0.5);
  18536. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18537. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18538. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18539. this._worldMatrix = world;
  18540. };
  18541. /**
  18542. * Tests if the bounding box is intersecting the frustum planes
  18543. * @param frustumPlanes defines the frustum planes to test
  18544. * @returns true if there is an intersection
  18545. */
  18546. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18547. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18548. };
  18549. /**
  18550. * Tests if the bounding box is entirely inside the frustum planes
  18551. * @param frustumPlanes defines the frustum planes to test
  18552. * @returns true if there is an inclusion
  18553. */
  18554. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18555. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18556. };
  18557. /**
  18558. * Tests if a point is inside the bounding box
  18559. * @param point defines the point to test
  18560. * @returns true if the point is inside the bounding box
  18561. */
  18562. BoundingBox.prototype.intersectsPoint = function (point) {
  18563. var delta = -BABYLON.Epsilon;
  18564. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18565. return false;
  18566. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18567. return false;
  18568. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18569. return false;
  18570. return true;
  18571. };
  18572. /**
  18573. * Tests if the bounding box intersects with a bounding sphere
  18574. * @param sphere defines the sphere to test
  18575. * @returns true if there is an intersection
  18576. */
  18577. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18578. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18579. };
  18580. /**
  18581. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18582. * @param min defines the min vector to use
  18583. * @param max defines the max vector to use
  18584. * @returns true if there is an intersection
  18585. */
  18586. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18587. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18588. return false;
  18589. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18590. return false;
  18591. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18592. return false;
  18593. return true;
  18594. };
  18595. // Statics
  18596. /**
  18597. * Tests if two bounding boxes are intersections
  18598. * @param box0 defines the first box to test
  18599. * @param box1 defines the second box to test
  18600. * @returns true if there is an intersection
  18601. */
  18602. BoundingBox.Intersects = function (box0, box1) {
  18603. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18604. return false;
  18605. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18606. return false;
  18607. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18608. return false;
  18609. return true;
  18610. };
  18611. /**
  18612. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18613. * @param minPoint defines the minimum vector of the bounding box
  18614. * @param maxPoint defines the maximum vector of the bounding box
  18615. * @param sphereCenter defines the sphere center
  18616. * @param sphereRadius defines the sphere radius
  18617. * @returns true if there is an intersection
  18618. */
  18619. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18620. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18621. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18622. return (num <= (sphereRadius * sphereRadius));
  18623. };
  18624. /**
  18625. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18626. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18627. * @param frustumPlanes defines the frustum planes to test
  18628. * @return true if there is an inclusion
  18629. */
  18630. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18631. for (var p = 0; p < 6; p++) {
  18632. for (var i = 0; i < 8; i++) {
  18633. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18634. return false;
  18635. }
  18636. }
  18637. }
  18638. return true;
  18639. };
  18640. /**
  18641. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18642. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18643. * @param frustumPlanes defines the frustum planes to test
  18644. * @return true if there is an intersection
  18645. */
  18646. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18647. for (var p = 0; p < 6; p++) {
  18648. var inCount = 8;
  18649. for (var i = 0; i < 8; i++) {
  18650. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18651. --inCount;
  18652. }
  18653. else {
  18654. break;
  18655. }
  18656. }
  18657. if (inCount === 0)
  18658. return false;
  18659. }
  18660. return true;
  18661. };
  18662. return BoundingBox;
  18663. }());
  18664. BABYLON.BoundingBox = BoundingBox;
  18665. })(BABYLON || (BABYLON = {}));
  18666. //# sourceMappingURL=babylon.boundingBox.js.map
  18667. var BABYLON;
  18668. (function (BABYLON) {
  18669. var computeBoxExtents = function (axis, box) {
  18670. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18671. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18672. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18673. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18674. var r = r0 + r1 + r2;
  18675. return {
  18676. min: p - r,
  18677. max: p + r
  18678. };
  18679. };
  18680. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18681. var axisOverlap = function (axis, box0, box1) {
  18682. var result0 = computeBoxExtents(axis, box0);
  18683. var result1 = computeBoxExtents(axis, box1);
  18684. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18685. };
  18686. var BoundingInfo = /** @class */ (function () {
  18687. function BoundingInfo(minimum, maximum) {
  18688. this.minimum = minimum;
  18689. this.maximum = maximum;
  18690. this._isLocked = false;
  18691. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18692. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18693. }
  18694. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18695. get: function () {
  18696. return this._isLocked;
  18697. },
  18698. set: function (value) {
  18699. this._isLocked = value;
  18700. },
  18701. enumerable: true,
  18702. configurable: true
  18703. });
  18704. // Methods
  18705. BoundingInfo.prototype.update = function (world) {
  18706. if (this._isLocked) {
  18707. return;
  18708. }
  18709. this.boundingBox._update(world);
  18710. this.boundingSphere._update(world);
  18711. };
  18712. /**
  18713. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18714. * @param center New center of the bounding info
  18715. * @param extend New extend of the bounding info
  18716. */
  18717. BoundingInfo.prototype.centerOn = function (center, extend) {
  18718. this.minimum = center.subtract(extend);
  18719. this.maximum = center.add(extend);
  18720. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18721. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18722. return this;
  18723. };
  18724. /**
  18725. * Scale the current bounding info by applying a scale factor
  18726. * @param factor defines the scale factor to apply
  18727. * @returns the current bounding info
  18728. */
  18729. BoundingInfo.prototype.scale = function (factor) {
  18730. this.boundingBox.scale(factor);
  18731. this.boundingSphere.scale(factor);
  18732. return this;
  18733. };
  18734. /**
  18735. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18736. * @param frustumPlanes defines the frustum to test
  18737. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18738. * @returns true if the bounding info is in the frustum planes
  18739. */
  18740. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18741. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18742. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18743. return false;
  18744. }
  18745. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18746. return true;
  18747. }
  18748. return this.boundingBox.isInFrustum(frustumPlanes);
  18749. };
  18750. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18751. /**
  18752. * Gets the world distance between the min and max points of the bounding box
  18753. */
  18754. get: function () {
  18755. var boundingBox = this.boundingBox;
  18756. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18757. return size.length();
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18763. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18764. };
  18765. /** @hidden */
  18766. BoundingInfo.prototype._checkCollision = function (collider) {
  18767. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18768. };
  18769. BoundingInfo.prototype.intersectsPoint = function (point) {
  18770. if (!this.boundingSphere.centerWorld) {
  18771. return false;
  18772. }
  18773. if (!this.boundingSphere.intersectsPoint(point)) {
  18774. return false;
  18775. }
  18776. if (!this.boundingBox.intersectsPoint(point)) {
  18777. return false;
  18778. }
  18779. return true;
  18780. };
  18781. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18782. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18783. return false;
  18784. }
  18785. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18786. return false;
  18787. }
  18788. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18789. return false;
  18790. }
  18791. if (!precise) {
  18792. return true;
  18793. }
  18794. var box0 = this.boundingBox;
  18795. var box1 = boundingInfo.boundingBox;
  18796. if (!axisOverlap(box0.directions[0], box0, box1))
  18797. return false;
  18798. if (!axisOverlap(box0.directions[1], box0, box1))
  18799. return false;
  18800. if (!axisOverlap(box0.directions[2], box0, box1))
  18801. return false;
  18802. if (!axisOverlap(box1.directions[0], box0, box1))
  18803. return false;
  18804. if (!axisOverlap(box1.directions[1], box0, box1))
  18805. return false;
  18806. if (!axisOverlap(box1.directions[2], box0, box1))
  18807. return false;
  18808. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18809. return false;
  18810. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18811. return false;
  18812. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18813. return false;
  18814. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18815. return false;
  18816. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18817. return false;
  18818. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18819. return false;
  18820. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18821. return false;
  18822. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18823. return false;
  18824. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18825. return false;
  18826. return true;
  18827. };
  18828. return BoundingInfo;
  18829. }());
  18830. BABYLON.BoundingInfo = BoundingInfo;
  18831. })(BABYLON || (BABYLON = {}));
  18832. //# sourceMappingURL=babylon.boundingInfo.js.map
  18833. var BABYLON;
  18834. (function (BABYLON) {
  18835. var TransformNode = /** @class */ (function (_super) {
  18836. __extends(TransformNode, _super);
  18837. function TransformNode(name, scene, isPure) {
  18838. if (scene === void 0) { scene = null; }
  18839. if (isPure === void 0) { isPure = true; }
  18840. var _this = _super.call(this, name, scene) || this;
  18841. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18842. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18843. _this._up = new BABYLON.Vector3(0, 1, 0);
  18844. _this._right = new BABYLON.Vector3(1, 0, 0);
  18845. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18846. // Properties
  18847. _this._position = BABYLON.Vector3.Zero();
  18848. _this._rotation = BABYLON.Vector3.Zero();
  18849. _this._scaling = BABYLON.Vector3.One();
  18850. _this._isDirty = false;
  18851. /**
  18852. * Set the billboard mode. Default is 0.
  18853. *
  18854. * | Value | Type | Description |
  18855. * | --- | --- | --- |
  18856. * | 0 | BILLBOARDMODE_NONE | |
  18857. * | 1 | BILLBOARDMODE_X | |
  18858. * | 2 | BILLBOARDMODE_Y | |
  18859. * | 4 | BILLBOARDMODE_Z | |
  18860. * | 7 | BILLBOARDMODE_ALL | |
  18861. *
  18862. */
  18863. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18864. _this.scalingDeterminant = 1;
  18865. _this.infiniteDistance = false;
  18866. /**
  18867. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18868. * By default the system will update normals to compensate
  18869. */
  18870. _this.ignoreNonUniformScaling = false;
  18871. _this._localWorld = BABYLON.Matrix.Zero();
  18872. _this._absolutePosition = BABYLON.Vector3.Zero();
  18873. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18874. _this._postMultiplyPivotMatrix = false;
  18875. _this._isWorldMatrixFrozen = false;
  18876. /**
  18877. * An event triggered after the world matrix is updated
  18878. */
  18879. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18880. _this._nonUniformScaling = false;
  18881. if (isPure) {
  18882. _this.getScene().addTransformNode(_this);
  18883. }
  18884. return _this;
  18885. }
  18886. /**
  18887. * Gets a string identifying the name of the class
  18888. * @returns "TransformNode" string
  18889. */
  18890. TransformNode.prototype.getClassName = function () {
  18891. return "TransformNode";
  18892. };
  18893. Object.defineProperty(TransformNode.prototype, "position", {
  18894. /**
  18895. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18896. */
  18897. get: function () {
  18898. return this._position;
  18899. },
  18900. set: function (newPosition) {
  18901. this._position = newPosition;
  18902. this._isDirty = true;
  18903. },
  18904. enumerable: true,
  18905. configurable: true
  18906. });
  18907. Object.defineProperty(TransformNode.prototype, "rotation", {
  18908. /**
  18909. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18910. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18911. */
  18912. get: function () {
  18913. return this._rotation;
  18914. },
  18915. set: function (newRotation) {
  18916. this._rotation = newRotation;
  18917. this._isDirty = true;
  18918. },
  18919. enumerable: true,
  18920. configurable: true
  18921. });
  18922. Object.defineProperty(TransformNode.prototype, "scaling", {
  18923. /**
  18924. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18925. */
  18926. get: function () {
  18927. return this._scaling;
  18928. },
  18929. set: function (newScaling) {
  18930. this._scaling = newScaling;
  18931. this._isDirty = true;
  18932. },
  18933. enumerable: true,
  18934. configurable: true
  18935. });
  18936. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18937. /**
  18938. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18939. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18940. */
  18941. get: function () {
  18942. return this._rotationQuaternion;
  18943. },
  18944. set: function (quaternion) {
  18945. this._rotationQuaternion = quaternion;
  18946. //reset the rotation vector.
  18947. if (quaternion && this.rotation.length()) {
  18948. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18949. }
  18950. },
  18951. enumerable: true,
  18952. configurable: true
  18953. });
  18954. Object.defineProperty(TransformNode.prototype, "forward", {
  18955. /**
  18956. * The forward direction of that transform in world space.
  18957. */
  18958. get: function () {
  18959. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18960. },
  18961. enumerable: true,
  18962. configurable: true
  18963. });
  18964. Object.defineProperty(TransformNode.prototype, "up", {
  18965. /**
  18966. * The up direction of that transform in world space.
  18967. */
  18968. get: function () {
  18969. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18970. },
  18971. enumerable: true,
  18972. configurable: true
  18973. });
  18974. Object.defineProperty(TransformNode.prototype, "right", {
  18975. /**
  18976. * The right direction of that transform in world space.
  18977. */
  18978. get: function () {
  18979. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18980. },
  18981. enumerable: true,
  18982. configurable: true
  18983. });
  18984. /**
  18985. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18986. * Returns the TransformNode.
  18987. */
  18988. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18989. this._poseMatrix.copyFrom(matrix);
  18990. return this;
  18991. };
  18992. /**
  18993. * Returns the mesh Pose matrix.
  18994. * Returned object : Matrix
  18995. */
  18996. TransformNode.prototype.getPoseMatrix = function () {
  18997. return this._poseMatrix;
  18998. };
  18999. /** @hidden */
  19000. TransformNode.prototype._isSynchronized = function () {
  19001. if (this._isDirty) {
  19002. return false;
  19003. }
  19004. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19005. return false;
  19006. if (this._cache.pivotMatrixUpdated) {
  19007. return false;
  19008. }
  19009. if (this.infiniteDistance) {
  19010. return false;
  19011. }
  19012. if (!this._cache.position.equals(this._position))
  19013. return false;
  19014. if (this._rotationQuaternion) {
  19015. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19016. return false;
  19017. }
  19018. if (!this._cache.rotation.equals(this._rotation))
  19019. return false;
  19020. if (!this._cache.scaling.equals(this._scaling))
  19021. return false;
  19022. return true;
  19023. };
  19024. /** @hidden */
  19025. TransformNode.prototype._initCache = function () {
  19026. _super.prototype._initCache.call(this);
  19027. this._cache.localMatrixUpdated = false;
  19028. this._cache.position = BABYLON.Vector3.Zero();
  19029. this._cache.scaling = BABYLON.Vector3.Zero();
  19030. this._cache.rotation = BABYLON.Vector3.Zero();
  19031. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19032. this._cache.billboardMode = -1;
  19033. };
  19034. TransformNode.prototype.markAsDirty = function (property) {
  19035. if (property === "rotation") {
  19036. this.rotationQuaternion = null;
  19037. }
  19038. this._currentRenderId = Number.MAX_VALUE;
  19039. this._isDirty = true;
  19040. return this;
  19041. };
  19042. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19043. /**
  19044. * Returns the current mesh absolute position.
  19045. * Returns a Vector3.
  19046. */
  19047. get: function () {
  19048. return this._absolutePosition;
  19049. },
  19050. enumerable: true,
  19051. configurable: true
  19052. });
  19053. /**
  19054. * Sets a new matrix to apply before all other transformation
  19055. * @param matrix defines the transform matrix
  19056. * @returns the current TransformNode
  19057. */
  19058. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19059. return this.setPivotMatrix(matrix, false);
  19060. };
  19061. /**
  19062. * Sets a new pivot matrix to the current node
  19063. * @param matrix defines the new pivot matrix to use
  19064. * @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
  19065. * @returns the current TransformNode
  19066. */
  19067. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19068. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19069. this._pivotMatrix = matrix.clone();
  19070. this._cache.pivotMatrixUpdated = true;
  19071. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19072. if (this._postMultiplyPivotMatrix) {
  19073. if (!this._pivotMatrixInverse) {
  19074. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19075. }
  19076. else {
  19077. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19078. }
  19079. }
  19080. return this;
  19081. };
  19082. /**
  19083. * Returns the mesh pivot matrix.
  19084. * Default : Identity.
  19085. * A Matrix is returned.
  19086. */
  19087. TransformNode.prototype.getPivotMatrix = function () {
  19088. return this._pivotMatrix;
  19089. };
  19090. /**
  19091. * Prevents the World matrix to be computed any longer.
  19092. * Returns the TransformNode.
  19093. */
  19094. TransformNode.prototype.freezeWorldMatrix = function () {
  19095. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19096. this.computeWorldMatrix(true);
  19097. this._isWorldMatrixFrozen = true;
  19098. return this;
  19099. };
  19100. /**
  19101. * Allows back the World matrix computation.
  19102. * Returns the TransformNode.
  19103. */
  19104. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19105. this._isWorldMatrixFrozen = false;
  19106. this.computeWorldMatrix(true);
  19107. return this;
  19108. };
  19109. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19110. /**
  19111. * True if the World matrix has been frozen.
  19112. * Returns a boolean.
  19113. */
  19114. get: function () {
  19115. return this._isWorldMatrixFrozen;
  19116. },
  19117. enumerable: true,
  19118. configurable: true
  19119. });
  19120. /**
  19121. * Retuns the mesh absolute position in the World.
  19122. * Returns a Vector3.
  19123. */
  19124. TransformNode.prototype.getAbsolutePosition = function () {
  19125. this.computeWorldMatrix();
  19126. return this._absolutePosition;
  19127. };
  19128. /**
  19129. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19130. * Returns the TransformNode.
  19131. */
  19132. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19133. if (!absolutePosition) {
  19134. return this;
  19135. }
  19136. var absolutePositionX;
  19137. var absolutePositionY;
  19138. var absolutePositionZ;
  19139. if (absolutePosition.x === undefined) {
  19140. if (arguments.length < 3) {
  19141. return this;
  19142. }
  19143. absolutePositionX = arguments[0];
  19144. absolutePositionY = arguments[1];
  19145. absolutePositionZ = arguments[2];
  19146. }
  19147. else {
  19148. absolutePositionX = absolutePosition.x;
  19149. absolutePositionY = absolutePosition.y;
  19150. absolutePositionZ = absolutePosition.z;
  19151. }
  19152. if (this.parent) {
  19153. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19154. invertParentWorldMatrix.invert();
  19155. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19156. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19157. }
  19158. else {
  19159. this.position.x = absolutePositionX;
  19160. this.position.y = absolutePositionY;
  19161. this.position.z = absolutePositionZ;
  19162. }
  19163. return this;
  19164. };
  19165. /**
  19166. * Sets the mesh position in its local space.
  19167. * Returns the TransformNode.
  19168. */
  19169. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19170. this.computeWorldMatrix();
  19171. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19172. return this;
  19173. };
  19174. /**
  19175. * Returns the mesh position in the local space from the current World matrix values.
  19176. * Returns a new Vector3.
  19177. */
  19178. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19179. this.computeWorldMatrix();
  19180. var invLocalWorldMatrix = this._localWorld.clone();
  19181. invLocalWorldMatrix.invert();
  19182. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19183. };
  19184. /**
  19185. * Translates the mesh along the passed Vector3 in its local space.
  19186. * Returns the TransformNode.
  19187. */
  19188. TransformNode.prototype.locallyTranslate = function (vector3) {
  19189. this.computeWorldMatrix(true);
  19190. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19191. return this;
  19192. };
  19193. /**
  19194. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19195. * @param targetPoint the position (must be in same space as current mesh) to look at
  19196. * @param yawCor optional yaw (y-axis) correction in radians
  19197. * @param pitchCor optional pitch (x-axis) correction in radians
  19198. * @param rollCor optional roll (z-axis) correction in radians
  19199. * @param space the choosen space of the target
  19200. * @returns the TransformNode.
  19201. */
  19202. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19203. if (yawCor === void 0) { yawCor = 0; }
  19204. if (pitchCor === void 0) { pitchCor = 0; }
  19205. if (rollCor === void 0) { rollCor = 0; }
  19206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19207. var dv = TransformNode._lookAtVectorCache;
  19208. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19209. targetPoint.subtractToRef(pos, dv);
  19210. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19211. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19212. var pitch = Math.atan2(dv.y, len);
  19213. if (this.rotationQuaternion) {
  19214. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19215. }
  19216. else {
  19217. this.rotation.x = pitch + pitchCor;
  19218. this.rotation.y = yaw + yawCor;
  19219. this.rotation.z = rollCor;
  19220. }
  19221. return this;
  19222. };
  19223. /**
  19224. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19225. * This Vector3 is expressed in the World space.
  19226. */
  19227. TransformNode.prototype.getDirection = function (localAxis) {
  19228. var result = BABYLON.Vector3.Zero();
  19229. this.getDirectionToRef(localAxis, result);
  19230. return result;
  19231. };
  19232. /**
  19233. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19234. * localAxis is expressed in the mesh local space.
  19235. * result is computed in the Wordl space from the mesh World matrix.
  19236. * Returns the TransformNode.
  19237. */
  19238. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19239. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19240. return this;
  19241. };
  19242. /**
  19243. * Sets a new pivot point to the current node
  19244. * @param point defines the new pivot point to use
  19245. * @param space defines if the point is in world or local space (local by default)
  19246. * @returns the current TransformNode
  19247. */
  19248. TransformNode.prototype.setPivotPoint = function (point, space) {
  19249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19250. if (this.getScene().getRenderId() == 0) {
  19251. this.computeWorldMatrix(true);
  19252. }
  19253. var wm = this.getWorldMatrix();
  19254. if (space == BABYLON.Space.WORLD) {
  19255. var tmat = BABYLON.Tmp.Matrix[0];
  19256. wm.invertToRef(tmat);
  19257. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19258. }
  19259. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19260. };
  19261. /**
  19262. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19263. */
  19264. TransformNode.prototype.getPivotPoint = function () {
  19265. var point = BABYLON.Vector3.Zero();
  19266. this.getPivotPointToRef(point);
  19267. return point;
  19268. };
  19269. /**
  19270. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19271. * Returns the TransformNode.
  19272. */
  19273. TransformNode.prototype.getPivotPointToRef = function (result) {
  19274. result.x = -this._pivotMatrix.m[12];
  19275. result.y = -this._pivotMatrix.m[13];
  19276. result.z = -this._pivotMatrix.m[14];
  19277. return this;
  19278. };
  19279. /**
  19280. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19281. */
  19282. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19283. var point = BABYLON.Vector3.Zero();
  19284. this.getAbsolutePivotPointToRef(point);
  19285. return point;
  19286. };
  19287. /**
  19288. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19289. * Returns the TransformNode.
  19290. */
  19291. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19292. result.x = this._pivotMatrix.m[12];
  19293. result.y = this._pivotMatrix.m[13];
  19294. result.z = this._pivotMatrix.m[14];
  19295. this.getPivotPointToRef(result);
  19296. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19297. return this;
  19298. };
  19299. /**
  19300. * Defines the passed node as the parent of the current node.
  19301. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19302. * Returns the TransformNode.
  19303. */
  19304. TransformNode.prototype.setParent = function (node) {
  19305. if (!node && !this.parent) {
  19306. return this;
  19307. }
  19308. if (!node) {
  19309. var rotation = BABYLON.Tmp.Quaternion[0];
  19310. var position = BABYLON.Tmp.Vector3[0];
  19311. var scale = BABYLON.Tmp.Vector3[1];
  19312. if (this.parent && this.parent.computeWorldMatrix) {
  19313. this.parent.computeWorldMatrix(true);
  19314. }
  19315. this.computeWorldMatrix(true);
  19316. this.getWorldMatrix().decompose(scale, rotation, position);
  19317. if (this.rotationQuaternion) {
  19318. this.rotationQuaternion.copyFrom(rotation);
  19319. }
  19320. else {
  19321. rotation.toEulerAnglesToRef(this.rotation);
  19322. }
  19323. this.scaling.x = scale.x;
  19324. this.scaling.y = scale.y;
  19325. this.scaling.z = scale.z;
  19326. this.position.x = position.x;
  19327. this.position.y = position.y;
  19328. this.position.z = position.z;
  19329. }
  19330. else {
  19331. var rotation = BABYLON.Tmp.Quaternion[0];
  19332. var position = BABYLON.Tmp.Vector3[0];
  19333. var scale = BABYLON.Tmp.Vector3[1];
  19334. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19335. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19336. this.computeWorldMatrix(true);
  19337. node.computeWorldMatrix(true);
  19338. node.getWorldMatrix().invertToRef(invParentMatrix);
  19339. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19340. diffMatrix.decompose(scale, rotation, position);
  19341. if (this.rotationQuaternion) {
  19342. this.rotationQuaternion.copyFrom(rotation);
  19343. }
  19344. else {
  19345. rotation.toEulerAnglesToRef(this.rotation);
  19346. }
  19347. this.position.x = position.x;
  19348. this.position.y = position.y;
  19349. this.position.z = position.z;
  19350. this.scaling.x = scale.x;
  19351. this.scaling.y = scale.y;
  19352. this.scaling.z = scale.z;
  19353. }
  19354. this.parent = node;
  19355. return this;
  19356. };
  19357. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19358. get: function () {
  19359. return this._nonUniformScaling;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. /** @hidden */
  19365. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19366. if (this._nonUniformScaling === value) {
  19367. return false;
  19368. }
  19369. this._nonUniformScaling = value;
  19370. return true;
  19371. };
  19372. /**
  19373. * Attach the current TransformNode to another TransformNode associated with a bone
  19374. * @param bone Bone affecting the TransformNode
  19375. * @param affectedTransformNode TransformNode associated with the bone
  19376. */
  19377. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19378. this._transformToBoneReferal = affectedTransformNode;
  19379. this.parent = bone;
  19380. if (bone.getWorldMatrix().determinant() < 0) {
  19381. this.scalingDeterminant *= -1;
  19382. }
  19383. return this;
  19384. };
  19385. TransformNode.prototype.detachFromBone = function () {
  19386. if (!this.parent) {
  19387. return this;
  19388. }
  19389. if (this.parent.getWorldMatrix().determinant() < 0) {
  19390. this.scalingDeterminant *= -1;
  19391. }
  19392. this._transformToBoneReferal = null;
  19393. this.parent = null;
  19394. return this;
  19395. };
  19396. /**
  19397. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19398. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19399. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19400. * The passed axis is also normalized.
  19401. * Returns the TransformNode.
  19402. */
  19403. TransformNode.prototype.rotate = function (axis, amount, space) {
  19404. axis.normalize();
  19405. if (!this.rotationQuaternion) {
  19406. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19407. this.rotation = BABYLON.Vector3.Zero();
  19408. }
  19409. var rotationQuaternion;
  19410. if (!space || space === BABYLON.Space.LOCAL) {
  19411. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19412. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19413. }
  19414. else {
  19415. if (this.parent) {
  19416. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19417. invertParentWorldMatrix.invert();
  19418. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19419. }
  19420. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19421. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19422. }
  19423. return this;
  19424. };
  19425. /**
  19426. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19427. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19428. * The passed axis is also normalized.
  19429. * Returns the TransformNode.
  19430. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19431. */
  19432. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19433. axis.normalize();
  19434. if (!this.rotationQuaternion) {
  19435. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19436. this.rotation.copyFromFloats(0, 0, 0);
  19437. }
  19438. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19439. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19440. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19441. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19442. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19443. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19444. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19445. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19446. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19447. return this;
  19448. };
  19449. /**
  19450. * Translates the mesh along the axis vector for the passed distance in the given space.
  19451. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19452. * Returns the TransformNode.
  19453. */
  19454. TransformNode.prototype.translate = function (axis, distance, space) {
  19455. var displacementVector = axis.scale(distance);
  19456. if (!space || space === BABYLON.Space.LOCAL) {
  19457. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19458. this.setPositionWithLocalVector(tempV3);
  19459. }
  19460. else {
  19461. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19462. }
  19463. return this;
  19464. };
  19465. /**
  19466. * Adds a rotation step to the mesh current rotation.
  19467. * x, y, z are Euler angles expressed in radians.
  19468. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19469. * This means this rotation is made in the mesh local space only.
  19470. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19471. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19472. * ```javascript
  19473. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19474. * ```
  19475. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19476. * 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.
  19477. * Returns the TransformNode.
  19478. */
  19479. TransformNode.prototype.addRotation = function (x, y, z) {
  19480. var rotationQuaternion;
  19481. if (this.rotationQuaternion) {
  19482. rotationQuaternion = this.rotationQuaternion;
  19483. }
  19484. else {
  19485. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19486. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19487. }
  19488. var accumulation = BABYLON.Tmp.Quaternion[0];
  19489. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19490. rotationQuaternion.multiplyInPlace(accumulation);
  19491. if (!this.rotationQuaternion) {
  19492. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19493. }
  19494. return this;
  19495. };
  19496. /**
  19497. * Computes the world matrix of the node
  19498. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19499. * @returns the world matrix
  19500. */
  19501. TransformNode.prototype.computeWorldMatrix = function (force) {
  19502. if (this._isWorldMatrixFrozen) {
  19503. return this._worldMatrix;
  19504. }
  19505. if (!force && this.isSynchronized()) {
  19506. this._currentRenderId = this.getScene().getRenderId();
  19507. return this._worldMatrix;
  19508. }
  19509. this._updateCache();
  19510. this._cache.position.copyFrom(this.position);
  19511. this._cache.scaling.copyFrom(this.scaling);
  19512. this._cache.pivotMatrixUpdated = false;
  19513. this._cache.billboardMode = this.billboardMode;
  19514. this._currentRenderId = this.getScene().getRenderId();
  19515. this._childRenderId = this.getScene().getRenderId();
  19516. this._isDirty = false;
  19517. // Scaling
  19518. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19519. // Rotation
  19520. //rotate, if quaternion is set and rotation was used
  19521. if (this.rotationQuaternion) {
  19522. var len = this.rotation.length();
  19523. if (len) {
  19524. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19525. this.rotation.copyFromFloats(0, 0, 0);
  19526. }
  19527. }
  19528. if (this.rotationQuaternion) {
  19529. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19530. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19531. }
  19532. else {
  19533. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19534. this._cache.rotation.copyFrom(this.rotation);
  19535. }
  19536. // Translation
  19537. var camera = this.getScene().activeCamera;
  19538. if (this.infiniteDistance && !this.parent && camera) {
  19539. var cameraWorldMatrix = camera.getWorldMatrix();
  19540. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19541. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19542. }
  19543. else {
  19544. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19545. }
  19546. // Composing transformations
  19547. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19548. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19549. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19550. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19551. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19552. // Need to decompose each rotation here
  19553. var currentPosition = BABYLON.Tmp.Vector3[3];
  19554. if (this.parent && this.parent.getWorldMatrix) {
  19555. if (this._transformToBoneReferal) {
  19556. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19557. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19558. }
  19559. else {
  19560. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19561. }
  19562. }
  19563. else {
  19564. currentPosition.copyFrom(this.position);
  19565. }
  19566. currentPosition.subtractInPlace(camera.globalPosition);
  19567. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19568. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19569. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19570. }
  19571. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19572. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19573. }
  19574. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19575. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19576. }
  19577. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19578. }
  19579. else {
  19580. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19581. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19582. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19583. }
  19584. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19585. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19586. }
  19587. // Post multiply inverse of pivotMatrix
  19588. if (this._postMultiplyPivotMatrix) {
  19589. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19590. }
  19591. // Local world
  19592. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19593. // Parent
  19594. if (this.parent && this.parent.getWorldMatrix) {
  19595. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19596. if (this._transformToBoneReferal) {
  19597. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19598. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19599. }
  19600. else {
  19601. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19602. }
  19603. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19604. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19605. this._worldMatrix.copyFrom(this._localWorld);
  19606. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19607. }
  19608. else {
  19609. if (this._transformToBoneReferal) {
  19610. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19611. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19612. }
  19613. else {
  19614. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19615. }
  19616. }
  19617. this._markSyncedWithParent();
  19618. }
  19619. else {
  19620. this._worldMatrix.copyFrom(this._localWorld);
  19621. }
  19622. // Normal matrix
  19623. if (!this.ignoreNonUniformScaling) {
  19624. if (this.scaling.isNonUniform) {
  19625. this._updateNonUniformScalingState(true);
  19626. }
  19627. else if (this.parent && this.parent._nonUniformScaling) {
  19628. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19629. }
  19630. else {
  19631. this._updateNonUniformScalingState(false);
  19632. }
  19633. }
  19634. else {
  19635. this._updateNonUniformScalingState(false);
  19636. }
  19637. this._afterComputeWorldMatrix();
  19638. // Absolute position
  19639. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19640. // Callbacks
  19641. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19642. if (!this._poseMatrix) {
  19643. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19644. }
  19645. // Cache the determinant
  19646. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19647. return this._worldMatrix;
  19648. };
  19649. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19650. };
  19651. /**
  19652. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19653. * @param func: callback function to add
  19654. *
  19655. * Returns the TransformNode.
  19656. */
  19657. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19658. this.onAfterWorldMatrixUpdateObservable.add(func);
  19659. return this;
  19660. };
  19661. /**
  19662. * Removes a registered callback function.
  19663. * Returns the TransformNode.
  19664. */
  19665. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19666. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19667. return this;
  19668. };
  19669. /**
  19670. * Clone the current transform node
  19671. * Returns the new transform node
  19672. * @param name Name of the new clone
  19673. * @param newParent New parent for the clone
  19674. * @param doNotCloneChildren Do not clone children hierarchy
  19675. */
  19676. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19677. var _this = this;
  19678. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19679. result.name = name;
  19680. result.id = name;
  19681. if (newParent) {
  19682. result.parent = newParent;
  19683. }
  19684. if (!doNotCloneChildren) {
  19685. // Children
  19686. var directDescendants = this.getDescendants(true);
  19687. for (var index = 0; index < directDescendants.length; index++) {
  19688. var child = directDescendants[index];
  19689. if (child.clone) {
  19690. child.clone(name + "." + child.name, result);
  19691. }
  19692. }
  19693. }
  19694. return result;
  19695. };
  19696. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19697. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19698. serializationObject.type = this.getClassName();
  19699. // Parent
  19700. if (this.parent) {
  19701. serializationObject.parentId = this.parent.id;
  19702. }
  19703. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19704. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19705. }
  19706. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19707. serializationObject.isEnabled = this.isEnabled();
  19708. // Parent
  19709. if (this.parent) {
  19710. serializationObject.parentId = this.parent.id;
  19711. }
  19712. return serializationObject;
  19713. };
  19714. // Statics
  19715. /**
  19716. * Returns a new TransformNode object parsed from the source provided.
  19717. * The parameter `parsedMesh` is the source.
  19718. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19719. */
  19720. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19721. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19722. if (BABYLON.Tags) {
  19723. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19724. }
  19725. if (parsedTransformNode.localMatrix) {
  19726. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19727. }
  19728. else if (parsedTransformNode.pivotMatrix) {
  19729. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19730. }
  19731. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19732. // Parent
  19733. if (parsedTransformNode.parentId) {
  19734. transformNode._waitingParentId = parsedTransformNode.parentId;
  19735. }
  19736. return transformNode;
  19737. };
  19738. /**
  19739. * Releases resources associated with this transform node.
  19740. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19741. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19742. */
  19743. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19744. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19745. // Animations
  19746. this.getScene().stopAnimation(this);
  19747. // Remove from scene
  19748. this.getScene().removeTransformNode(this);
  19749. this.onAfterWorldMatrixUpdateObservable.clear();
  19750. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19751. };
  19752. // Statics
  19753. TransformNode.BILLBOARDMODE_NONE = 0;
  19754. TransformNode.BILLBOARDMODE_X = 1;
  19755. TransformNode.BILLBOARDMODE_Y = 2;
  19756. TransformNode.BILLBOARDMODE_Z = 4;
  19757. TransformNode.BILLBOARDMODE_ALL = 7;
  19758. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19759. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19760. __decorate([
  19761. BABYLON.serializeAsVector3("position")
  19762. ], TransformNode.prototype, "_position", void 0);
  19763. __decorate([
  19764. BABYLON.serializeAsVector3("rotation")
  19765. ], TransformNode.prototype, "_rotation", void 0);
  19766. __decorate([
  19767. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19768. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19769. __decorate([
  19770. BABYLON.serializeAsVector3("scaling")
  19771. ], TransformNode.prototype, "_scaling", void 0);
  19772. __decorate([
  19773. BABYLON.serialize()
  19774. ], TransformNode.prototype, "billboardMode", void 0);
  19775. __decorate([
  19776. BABYLON.serialize()
  19777. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19778. __decorate([
  19779. BABYLON.serialize()
  19780. ], TransformNode.prototype, "infiniteDistance", void 0);
  19781. __decorate([
  19782. BABYLON.serialize()
  19783. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19784. return TransformNode;
  19785. }(BABYLON.Node));
  19786. BABYLON.TransformNode = TransformNode;
  19787. })(BABYLON || (BABYLON = {}));
  19788. //# sourceMappingURL=babylon.transformNode.js.map
  19789. var BABYLON;
  19790. (function (BABYLON) {
  19791. /**
  19792. * Class used to store all common mesh properties
  19793. */
  19794. var AbstractMesh = /** @class */ (function (_super) {
  19795. __extends(AbstractMesh, _super);
  19796. // Constructor
  19797. /**
  19798. * Creates a new AbstractMesh
  19799. * @param name defines the name of the mesh
  19800. * @param scene defines the hosting scene
  19801. */
  19802. function AbstractMesh(name, scene) {
  19803. if (scene === void 0) { scene = null; }
  19804. var _this = _super.call(this, name, scene, false) || this;
  19805. _this._facetNb = 0; // facet number
  19806. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19807. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19808. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19809. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19810. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19811. _this._subDiv = {
  19812. max: 1,
  19813. X: 1,
  19814. Y: 1,
  19815. Z: 1
  19816. };
  19817. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19818. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19819. /** Gets ot sets the culling strategy to use to find visible meshes */
  19820. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19821. // Events
  19822. /**
  19823. * An event triggered when this mesh collides with another one
  19824. */
  19825. _this.onCollideObservable = new BABYLON.Observable();
  19826. /**
  19827. * An event triggered when the collision's position changes
  19828. */
  19829. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19830. /**
  19831. * An event triggered when material is changed
  19832. */
  19833. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19834. // Properties
  19835. /**
  19836. * Gets or sets the orientation for POV movement & rotation
  19837. */
  19838. _this.definedFacingForward = true;
  19839. /**
  19840. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19841. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19842. * * 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.
  19843. * @see http://doc.babylonjs.com/features/occlusionquery
  19844. */
  19845. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19846. /**
  19847. * 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:
  19848. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19849. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19850. * * 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.
  19851. * @see http://doc.babylonjs.com/features/occlusionquery
  19852. */
  19853. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19854. /**
  19855. * 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.
  19856. * The default value is -1 which means don't break the query and wait till the result
  19857. * @see http://doc.babylonjs.com/features/occlusionquery
  19858. */
  19859. _this.occlusionRetryCount = -1;
  19860. /** @hidden */
  19861. _this._occlusionInternalRetryCounter = 0;
  19862. /** @hidden */
  19863. _this._isOccluded = false;
  19864. /** @hidden */
  19865. _this._isOcclusionQueryInProgress = false;
  19866. _this._visibility = 1.0;
  19867. /** Gets or sets the alpha index used to sort transparent meshes
  19868. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19869. */
  19870. _this.alphaIndex = Number.MAX_VALUE;
  19871. /**
  19872. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19873. */
  19874. _this.isVisible = true;
  19875. /**
  19876. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19877. */
  19878. _this.isPickable = true;
  19879. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19880. _this.showSubMeshesBoundingBox = false;
  19881. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19882. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19883. */
  19884. _this.isBlocker = false;
  19885. /**
  19886. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19887. */
  19888. _this.enablePointerMoveEvents = false;
  19889. /**
  19890. * Specifies the rendering group id for this mesh (0 by default)
  19891. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19892. */
  19893. _this.renderingGroupId = 0;
  19894. _this._receiveShadows = false;
  19895. /** Defines color to use when rendering outline */
  19896. _this.outlineColor = BABYLON.Color3.Red();
  19897. /** Define width to use when rendering outline */
  19898. _this.outlineWidth = 0.02;
  19899. /** Defines color to use when rendering overlay */
  19900. _this.overlayColor = BABYLON.Color3.Red();
  19901. /** Defines alpha to use when rendering overlay */
  19902. _this.overlayAlpha = 0.5;
  19903. _this._hasVertexAlpha = false;
  19904. _this._useVertexColors = true;
  19905. _this._computeBonesUsingShaders = true;
  19906. _this._numBoneInfluencers = 4;
  19907. _this._applyFog = true;
  19908. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19909. _this.useOctreeForRenderingSelection = true;
  19910. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19911. _this.useOctreeForPicking = true;
  19912. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19913. _this.useOctreeForCollisions = true;
  19914. _this._layerMask = 0x0FFFFFFF;
  19915. /**
  19916. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19917. */
  19918. _this.alwaysSelectAsActiveMesh = false;
  19919. /**
  19920. * Gets or sets the current action manager
  19921. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19922. */
  19923. _this.actionManager = null;
  19924. // Collisions
  19925. _this._checkCollisions = false;
  19926. _this._collisionMask = -1;
  19927. _this._collisionGroup = -1;
  19928. /**
  19929. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19930. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19931. */
  19932. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19933. /**
  19934. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19935. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19936. */
  19937. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19938. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19939. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19940. // Edges
  19941. /**
  19942. * Defines edge width used when edgesRenderer is enabled
  19943. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19944. */
  19945. _this.edgesWidth = 1;
  19946. /**
  19947. * Defines edge color used when edgesRenderer is enabled
  19948. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19949. */
  19950. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19951. // Cache
  19952. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19953. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19954. /** @hidden */
  19955. _this._renderId = 0;
  19956. /** @hidden */
  19957. _this._intersectionsInProgress = new Array();
  19958. /** @hidden */
  19959. _this._unIndexed = false;
  19960. /** @hidden */
  19961. _this._lightSources = new Array();
  19962. /**
  19963. * An event triggered when the mesh is rebuilt.
  19964. */
  19965. _this.onRebuildObservable = new BABYLON.Observable();
  19966. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19967. if (collidedMesh === void 0) { collidedMesh = null; }
  19968. //TODO move this to the collision coordinator!
  19969. if (_this.getScene().workerCollisions)
  19970. newPosition.multiplyInPlace(_this._collider._radius);
  19971. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19972. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19973. _this.position.addInPlace(_this._diffPositionForCollisions);
  19974. }
  19975. if (collidedMesh) {
  19976. _this.onCollideObservable.notifyObservers(collidedMesh);
  19977. }
  19978. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19979. };
  19980. _this.getScene().addMesh(_this);
  19981. _this._resyncLightSources();
  19982. return _this;
  19983. }
  19984. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19985. /**
  19986. * No billboard
  19987. */
  19988. get: function () {
  19989. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19995. /** Billboard on X axis */
  19996. get: function () {
  19997. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20003. /** Billboard on Y axis */
  20004. get: function () {
  20005. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20006. },
  20007. enumerable: true,
  20008. configurable: true
  20009. });
  20010. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20011. /** Billboard on Z axis */
  20012. get: function () {
  20013. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20014. },
  20015. enumerable: true,
  20016. configurable: true
  20017. });
  20018. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20019. /** Billboard on all axes */
  20020. get: function () {
  20021. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20022. },
  20023. enumerable: true,
  20024. configurable: true
  20025. });
  20026. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20027. /**
  20028. * Gets the number of facets in the mesh
  20029. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20030. */
  20031. get: function () {
  20032. return this._facetNb;
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20038. /**
  20039. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20040. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20041. */
  20042. get: function () {
  20043. return this._partitioningSubdivisions;
  20044. },
  20045. set: function (nb) {
  20046. this._partitioningSubdivisions = nb;
  20047. },
  20048. enumerable: true,
  20049. configurable: true
  20050. });
  20051. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20052. /**
  20053. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20054. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20055. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20056. */
  20057. get: function () {
  20058. return this._partitioningBBoxRatio;
  20059. },
  20060. set: function (ratio) {
  20061. this._partitioningBBoxRatio = ratio;
  20062. },
  20063. enumerable: true,
  20064. configurable: true
  20065. });
  20066. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20067. /**
  20068. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20069. * Works only for updatable meshes.
  20070. * Doesn't work with multi-materials
  20071. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20072. */
  20073. get: function () {
  20074. return this._facetDepthSort;
  20075. },
  20076. set: function (sort) {
  20077. this._facetDepthSort = sort;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20083. /**
  20084. * The location (Vector3) where the facet depth sort must be computed from.
  20085. * By default, the active camera position.
  20086. * Used only when facet depth sort is enabled
  20087. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20088. */
  20089. get: function () {
  20090. return this._facetDepthSortFrom;
  20091. },
  20092. set: function (location) {
  20093. this._facetDepthSortFrom = location;
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20099. /**
  20100. * gets a boolean indicating if facetData is enabled
  20101. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20102. */
  20103. get: function () {
  20104. return this._facetDataEnabled;
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. /** @hidden */
  20110. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20111. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20112. return false;
  20113. }
  20114. this._markSubMeshesAsMiscDirty();
  20115. return true;
  20116. };
  20117. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20118. /** Set a function to call when this mesh collides with another one */
  20119. set: function (callback) {
  20120. if (this._onCollideObserver) {
  20121. this.onCollideObservable.remove(this._onCollideObserver);
  20122. }
  20123. this._onCollideObserver = this.onCollideObservable.add(callback);
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20129. /** Set a function to call when the collision's position changes */
  20130. set: function (callback) {
  20131. if (this._onCollisionPositionChangeObserver) {
  20132. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20133. }
  20134. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20140. /**
  20141. * 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
  20142. * @see http://doc.babylonjs.com/features/occlusionquery
  20143. */
  20144. get: function () {
  20145. return this._isOccluded;
  20146. },
  20147. set: function (value) {
  20148. this._isOccluded = value;
  20149. },
  20150. enumerable: true,
  20151. configurable: true
  20152. });
  20153. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20154. /**
  20155. * Flag to check the progress status of the query
  20156. * @see http://doc.babylonjs.com/features/occlusionquery
  20157. */
  20158. get: function () {
  20159. return this._isOcclusionQueryInProgress;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20165. /**
  20166. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20167. */
  20168. get: function () {
  20169. return this._visibility;
  20170. },
  20171. /**
  20172. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20173. */
  20174. set: function (value) {
  20175. if (this._visibility === value) {
  20176. return;
  20177. }
  20178. this._visibility = value;
  20179. this._markSubMeshesAsMiscDirty();
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Object.defineProperty(AbstractMesh.prototype, "material", {
  20185. /** Gets or sets current material */
  20186. get: function () {
  20187. return this._material;
  20188. },
  20189. set: function (value) {
  20190. if (this._material === value) {
  20191. return;
  20192. }
  20193. this._material = value;
  20194. if (this.onMaterialChangedObservable.hasObservers) {
  20195. this.onMaterialChangedObservable.notifyObservers(this);
  20196. }
  20197. if (!this.subMeshes) {
  20198. return;
  20199. }
  20200. this._unBindEffect();
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20206. /**
  20207. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20208. * @see http://doc.babylonjs.com/babylon101/shadows
  20209. */
  20210. get: function () {
  20211. return this._receiveShadows;
  20212. },
  20213. set: function (value) {
  20214. if (this._receiveShadows === value) {
  20215. return;
  20216. }
  20217. this._receiveShadows = value;
  20218. this._markSubMeshesAsLightDirty();
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20224. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20225. get: function () {
  20226. return this._hasVertexAlpha;
  20227. },
  20228. set: function (value) {
  20229. if (this._hasVertexAlpha === value) {
  20230. return;
  20231. }
  20232. this._hasVertexAlpha = value;
  20233. this._markSubMeshesAsAttributesDirty();
  20234. this._markSubMeshesAsMiscDirty();
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20240. /** 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) */
  20241. get: function () {
  20242. return this._useVertexColors;
  20243. },
  20244. set: function (value) {
  20245. if (this._useVertexColors === value) {
  20246. return;
  20247. }
  20248. this._useVertexColors = value;
  20249. this._markSubMeshesAsAttributesDirty();
  20250. },
  20251. enumerable: true,
  20252. configurable: true
  20253. });
  20254. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20255. /**
  20256. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20257. */
  20258. get: function () {
  20259. return this._computeBonesUsingShaders;
  20260. },
  20261. set: function (value) {
  20262. if (this._computeBonesUsingShaders === value) {
  20263. return;
  20264. }
  20265. this._computeBonesUsingShaders = value;
  20266. this._markSubMeshesAsAttributesDirty();
  20267. },
  20268. enumerable: true,
  20269. configurable: true
  20270. });
  20271. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20272. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20273. get: function () {
  20274. return this._numBoneInfluencers;
  20275. },
  20276. set: function (value) {
  20277. if (this._numBoneInfluencers === value) {
  20278. return;
  20279. }
  20280. this._numBoneInfluencers = value;
  20281. this._markSubMeshesAsAttributesDirty();
  20282. },
  20283. enumerable: true,
  20284. configurable: true
  20285. });
  20286. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20287. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20288. get: function () {
  20289. return this._applyFog;
  20290. },
  20291. set: function (value) {
  20292. if (this._applyFog === value) {
  20293. return;
  20294. }
  20295. this._applyFog = value;
  20296. this._markSubMeshesAsMiscDirty();
  20297. },
  20298. enumerable: true,
  20299. configurable: true
  20300. });
  20301. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20302. /**
  20303. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20304. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20305. */
  20306. get: function () {
  20307. return this._layerMask;
  20308. },
  20309. set: function (value) {
  20310. if (value === this._layerMask) {
  20311. return;
  20312. }
  20313. this._layerMask = value;
  20314. this._resyncLightSources();
  20315. },
  20316. enumerable: true,
  20317. configurable: true
  20318. });
  20319. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20320. /**
  20321. * Gets or sets a collision mask used to mask collisions (default is -1).
  20322. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20323. */
  20324. get: function () {
  20325. return this._collisionMask;
  20326. },
  20327. set: function (mask) {
  20328. this._collisionMask = !isNaN(mask) ? mask : -1;
  20329. },
  20330. enumerable: true,
  20331. configurable: true
  20332. });
  20333. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20334. /**
  20335. * Gets or sets the current collision group mask (-1 by default).
  20336. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20337. */
  20338. get: function () {
  20339. return this._collisionGroup;
  20340. },
  20341. set: function (mask) {
  20342. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20343. },
  20344. enumerable: true,
  20345. configurable: true
  20346. });
  20347. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20348. /** @hidden */
  20349. get: function () {
  20350. return null;
  20351. },
  20352. enumerable: true,
  20353. configurable: true
  20354. });
  20355. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20356. get: function () {
  20357. return this._skeleton;
  20358. },
  20359. /**
  20360. * Gets or sets a skeleton to apply skining transformations
  20361. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20362. */
  20363. set: function (value) {
  20364. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20365. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20366. }
  20367. if (value && value.needInitialSkinMatrix) {
  20368. value._registerMeshWithPoseMatrix(this);
  20369. }
  20370. this._skeleton = value;
  20371. if (!this._skeleton) {
  20372. this._bonesTransformMatrices = null;
  20373. }
  20374. this._markSubMeshesAsAttributesDirty();
  20375. },
  20376. enumerable: true,
  20377. configurable: true
  20378. });
  20379. /**
  20380. * Returns the string "AbstractMesh"
  20381. * @returns "AbstractMesh"
  20382. */
  20383. AbstractMesh.prototype.getClassName = function () {
  20384. return "AbstractMesh";
  20385. };
  20386. /**
  20387. * Gets a string representation of the current mesh
  20388. * @param fullDetails defines a boolean indicating if full details must be included
  20389. * @returns a string representation of the current mesh
  20390. */
  20391. AbstractMesh.prototype.toString = function (fullDetails) {
  20392. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20393. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20394. if (this._skeleton) {
  20395. ret += ", skeleton: " + this._skeleton.name;
  20396. }
  20397. if (fullDetails) {
  20398. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20399. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20400. }
  20401. return ret;
  20402. };
  20403. /** @hidden */
  20404. AbstractMesh.prototype._rebuild = function () {
  20405. this.onRebuildObservable.notifyObservers(this);
  20406. if (this._occlusionQuery) {
  20407. this._occlusionQuery = null;
  20408. }
  20409. if (!this.subMeshes) {
  20410. return;
  20411. }
  20412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20413. var subMesh = _a[_i];
  20414. subMesh._rebuild();
  20415. }
  20416. };
  20417. /** @hidden */
  20418. AbstractMesh.prototype._resyncLightSources = function () {
  20419. this._lightSources.length = 0;
  20420. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20421. var light = _a[_i];
  20422. if (!light.isEnabled()) {
  20423. continue;
  20424. }
  20425. if (light.canAffectMesh(this)) {
  20426. this._lightSources.push(light);
  20427. }
  20428. }
  20429. this._markSubMeshesAsLightDirty();
  20430. };
  20431. /** @hidden */
  20432. AbstractMesh.prototype._resyncLighSource = function (light) {
  20433. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20434. var index = this._lightSources.indexOf(light);
  20435. if (index === -1) {
  20436. if (!isIn) {
  20437. return;
  20438. }
  20439. this._lightSources.push(light);
  20440. }
  20441. else {
  20442. if (isIn) {
  20443. return;
  20444. }
  20445. this._lightSources.splice(index, 1);
  20446. }
  20447. this._markSubMeshesAsLightDirty();
  20448. };
  20449. /** @hidden */
  20450. AbstractMesh.prototype._unBindEffect = function () {
  20451. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20452. var subMesh = _a[_i];
  20453. subMesh.setEffect(null);
  20454. }
  20455. };
  20456. /** @hidden */
  20457. AbstractMesh.prototype._removeLightSource = function (light) {
  20458. var index = this._lightSources.indexOf(light);
  20459. if (index === -1) {
  20460. return;
  20461. }
  20462. this._lightSources.splice(index, 1);
  20463. this._markSubMeshesAsLightDirty();
  20464. };
  20465. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20466. if (!this.subMeshes) {
  20467. return;
  20468. }
  20469. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20470. var subMesh = _a[_i];
  20471. if (subMesh._materialDefines) {
  20472. func(subMesh._materialDefines);
  20473. }
  20474. }
  20475. };
  20476. /** @hidden */
  20477. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20478. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20479. };
  20480. /** @hidden */
  20481. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20482. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20483. };
  20484. /** @hidden */
  20485. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20486. if (!this.subMeshes) {
  20487. return;
  20488. }
  20489. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20490. var subMesh = _a[_i];
  20491. var material = subMesh.getMaterial();
  20492. if (material) {
  20493. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20494. }
  20495. }
  20496. };
  20497. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20498. /**
  20499. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20500. */
  20501. get: function () {
  20502. return this._scaling;
  20503. },
  20504. set: function (newScaling) {
  20505. this._scaling = newScaling;
  20506. if (this.physicsImpostor) {
  20507. this.physicsImpostor.forceUpdate();
  20508. }
  20509. },
  20510. enumerable: true,
  20511. configurable: true
  20512. });
  20513. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20514. // Methods
  20515. /**
  20516. * Returns true if the mesh is blocked. Implemented by child classes
  20517. */
  20518. get: function () {
  20519. return false;
  20520. },
  20521. enumerable: true,
  20522. configurable: true
  20523. });
  20524. /**
  20525. * Returns the mesh itself by default. Implemented by child classes
  20526. * @param camera defines the camera to use to pick the right LOD level
  20527. * @returns the currentAbstractMesh
  20528. */
  20529. AbstractMesh.prototype.getLOD = function (camera) {
  20530. return this;
  20531. };
  20532. /**
  20533. * Returns 0 by default. Implemented by child classes
  20534. * @returns an integer
  20535. */
  20536. AbstractMesh.prototype.getTotalVertices = function () {
  20537. return 0;
  20538. };
  20539. /**
  20540. * Returns null by default. Implemented by child classes
  20541. * @returns null
  20542. */
  20543. AbstractMesh.prototype.getIndices = function () {
  20544. return null;
  20545. };
  20546. /**
  20547. * Returns the array of the requested vertex data kind. Implemented by child classes
  20548. * @param kind defines the vertex data kind to use
  20549. * @returns null
  20550. */
  20551. AbstractMesh.prototype.getVerticesData = function (kind) {
  20552. return null;
  20553. };
  20554. /**
  20555. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20556. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20557. * Note that a new underlying VertexBuffer object is created each call.
  20558. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20559. * @param kind defines vertex data kind:
  20560. * * BABYLON.VertexBuffer.PositionKind
  20561. * * BABYLON.VertexBuffer.UVKind
  20562. * * BABYLON.VertexBuffer.UV2Kind
  20563. * * BABYLON.VertexBuffer.UV3Kind
  20564. * * BABYLON.VertexBuffer.UV4Kind
  20565. * * BABYLON.VertexBuffer.UV5Kind
  20566. * * BABYLON.VertexBuffer.UV6Kind
  20567. * * BABYLON.VertexBuffer.ColorKind
  20568. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20569. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20570. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20571. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20572. * @param data defines the data source
  20573. * @param updatable defines if the data must be flagged as updatable (or static)
  20574. * @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
  20575. * @returns the current mesh
  20576. */
  20577. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20578. return this;
  20579. };
  20580. /**
  20581. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20582. * If the mesh has no geometry, it is simply returned as it is.
  20583. * @param kind defines vertex data kind:
  20584. * * BABYLON.VertexBuffer.PositionKind
  20585. * * BABYLON.VertexBuffer.UVKind
  20586. * * BABYLON.VertexBuffer.UV2Kind
  20587. * * BABYLON.VertexBuffer.UV3Kind
  20588. * * BABYLON.VertexBuffer.UV4Kind
  20589. * * BABYLON.VertexBuffer.UV5Kind
  20590. * * BABYLON.VertexBuffer.UV6Kind
  20591. * * BABYLON.VertexBuffer.ColorKind
  20592. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20593. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20594. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20595. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20596. * @param data defines the data source
  20597. * @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
  20598. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20599. * @returns the current mesh
  20600. */
  20601. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20602. return this;
  20603. };
  20604. /**
  20605. * Sets the mesh indices,
  20606. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20607. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20608. * @param totalVertices Defines the total number of vertices
  20609. * @returns the current mesh
  20610. */
  20611. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20612. return this;
  20613. };
  20614. /**
  20615. * Gets a boolean indicating if specific vertex data is present
  20616. * @param kind defines the vertex data kind to use
  20617. * @returns true is data kind is present
  20618. */
  20619. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20620. return false;
  20621. };
  20622. /**
  20623. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20624. * @returns a BoundingInfo
  20625. */
  20626. AbstractMesh.prototype.getBoundingInfo = function () {
  20627. if (this._masterMesh) {
  20628. return this._masterMesh.getBoundingInfo();
  20629. }
  20630. if (!this._boundingInfo) {
  20631. // this._boundingInfo is being created here
  20632. this._updateBoundingInfo();
  20633. }
  20634. // cannot be null.
  20635. return this._boundingInfo;
  20636. };
  20637. /**
  20638. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20639. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20640. * @returns the current mesh
  20641. */
  20642. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20643. if (includeDescendants === void 0) { includeDescendants = true; }
  20644. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20645. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20646. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20647. if (maxDimension === 0) {
  20648. return this;
  20649. }
  20650. var scale = 1 / maxDimension;
  20651. this.scaling.scaleInPlace(scale);
  20652. return this;
  20653. };
  20654. /**
  20655. * Overwrite the current bounding info
  20656. * @param boundingInfo defines the new bounding info
  20657. * @returns the current mesh
  20658. */
  20659. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20660. this._boundingInfo = boundingInfo;
  20661. return this;
  20662. };
  20663. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20664. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20665. get: function () {
  20666. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20667. },
  20668. enumerable: true,
  20669. configurable: true
  20670. });
  20671. /** @hidden */
  20672. AbstractMesh.prototype._preActivate = function () {
  20673. };
  20674. /** @hidden */
  20675. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20676. };
  20677. /** @hidden */
  20678. AbstractMesh.prototype._activate = function (renderId) {
  20679. this._renderId = renderId;
  20680. };
  20681. /**
  20682. * Gets the current world matrix
  20683. * @returns a Matrix
  20684. */
  20685. AbstractMesh.prototype.getWorldMatrix = function () {
  20686. if (this._masterMesh) {
  20687. return this._masterMesh.getWorldMatrix();
  20688. }
  20689. return _super.prototype.getWorldMatrix.call(this);
  20690. };
  20691. /** @hidden */
  20692. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20693. if (this._masterMesh) {
  20694. return this._masterMesh._getWorldMatrixDeterminant();
  20695. }
  20696. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20697. };
  20698. // ================================== Point of View Movement =================================
  20699. /**
  20700. * Perform relative position change from the point of view of behind the front of the mesh.
  20701. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20702. * Supports definition of mesh facing forward or backward
  20703. * @param amountRight defines the distance on the right axis
  20704. * @param amountUp defines the distance on the up axis
  20705. * @param amountForward defines the distance on the forward axis
  20706. * @returns the current mesh
  20707. */
  20708. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20709. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20710. return this;
  20711. };
  20712. /**
  20713. * Calculate relative position change from the point of view of behind the front of the mesh.
  20714. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20715. * Supports definition of mesh facing forward or backward
  20716. * @param amountRight defines the distance on the right axis
  20717. * @param amountUp defines the distance on the up axis
  20718. * @param amountForward defines the distance on the forward axis
  20719. * @returns the new displacement vector
  20720. */
  20721. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20722. var rotMatrix = new BABYLON.Matrix();
  20723. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20724. rotQuaternion.toRotationMatrix(rotMatrix);
  20725. var translationDelta = BABYLON.Vector3.Zero();
  20726. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20727. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20728. return translationDelta;
  20729. };
  20730. // ================================== Point of View Rotation =================================
  20731. /**
  20732. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20733. * Supports definition of mesh facing forward or backward
  20734. * @param flipBack defines the flip
  20735. * @param twirlClockwise defines the twirl
  20736. * @param tiltRight defines the tilt
  20737. * @returns the current mesh
  20738. */
  20739. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20740. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20741. return this;
  20742. };
  20743. /**
  20744. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20745. * Supports definition of mesh facing forward or backward.
  20746. * @param flipBack defines the flip
  20747. * @param twirlClockwise defines the twirl
  20748. * @param tiltRight defines the tilt
  20749. * @returns the new rotation vector
  20750. */
  20751. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20752. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20753. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20754. };
  20755. /**
  20756. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20757. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20758. * @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
  20759. * @returns the new bounding vectors
  20760. */
  20761. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20762. if (includeDescendants === void 0) { includeDescendants = true; }
  20763. if (predicate === void 0) { predicate = null; }
  20764. // Ensures that all world matrix will be recomputed.
  20765. this.getScene().incrementRenderId();
  20766. this.computeWorldMatrix(true);
  20767. var min;
  20768. var max;
  20769. var boundingInfo = this.getBoundingInfo();
  20770. if (!this.subMeshes) {
  20771. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20772. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20773. }
  20774. else {
  20775. min = boundingInfo.boundingBox.minimumWorld;
  20776. max = boundingInfo.boundingBox.maximumWorld;
  20777. }
  20778. if (includeDescendants) {
  20779. var descendants = this.getDescendants(false);
  20780. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20781. var descendant = descendants_1[_i];
  20782. var childMesh = descendant;
  20783. childMesh.computeWorldMatrix(true);
  20784. // Filters meshes based on custom predicate function.
  20785. if (predicate && !predicate(childMesh)) {
  20786. continue;
  20787. }
  20788. //make sure we have the needed params to get mix and max
  20789. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20790. continue;
  20791. }
  20792. var childBoundingInfo = childMesh.getBoundingInfo();
  20793. var boundingBox = childBoundingInfo.boundingBox;
  20794. var minBox = boundingBox.minimumWorld;
  20795. var maxBox = boundingBox.maximumWorld;
  20796. BABYLON.Tools.CheckExtends(minBox, min, max);
  20797. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20798. }
  20799. }
  20800. return {
  20801. min: min,
  20802. max: max
  20803. };
  20804. };
  20805. /** @hidden */
  20806. AbstractMesh.prototype._updateBoundingInfo = function () {
  20807. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20808. this._boundingInfo.update(this.worldMatrixFromCache);
  20809. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20810. return this;
  20811. };
  20812. /** @hidden */
  20813. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20814. if (!this.subMeshes) {
  20815. return this;
  20816. }
  20817. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20818. var subMesh = this.subMeshes[subIndex];
  20819. if (!subMesh.IsGlobal) {
  20820. subMesh.updateBoundingInfo(matrix);
  20821. }
  20822. }
  20823. return this;
  20824. };
  20825. /** @hidden */
  20826. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20827. // Bounding info
  20828. this._updateBoundingInfo();
  20829. };
  20830. /**
  20831. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20832. * A mesh is in the frustum if its bounding box intersects the frustum
  20833. * @param frustumPlanes defines the frustum to test
  20834. * @returns true if the mesh is in the frustum planes
  20835. */
  20836. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20837. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20838. };
  20839. /**
  20840. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20841. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20842. * @param frustumPlanes defines the frustum to test
  20843. * @returns true if the mesh is completely in the frustum planes
  20844. */
  20845. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20846. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20847. };
  20848. /**
  20849. * True if the mesh intersects another mesh or a SolidParticle object
  20850. * @param mesh defines a target mesh or SolidParticle to test
  20851. * @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)
  20852. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20853. * @returns true if there is an intersection
  20854. */
  20855. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20856. if (precise === void 0) { precise = false; }
  20857. if (!this._boundingInfo || !mesh._boundingInfo) {
  20858. return false;
  20859. }
  20860. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20861. return true;
  20862. }
  20863. if (includeDescendants) {
  20864. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20865. var child = _a[_i];
  20866. if (child.intersectsMesh(mesh, precise, true)) {
  20867. return true;
  20868. }
  20869. }
  20870. }
  20871. return false;
  20872. };
  20873. /**
  20874. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20875. * @param point defines the point to test
  20876. * @returns true if there is an intersection
  20877. */
  20878. AbstractMesh.prototype.intersectsPoint = function (point) {
  20879. if (!this._boundingInfo) {
  20880. return false;
  20881. }
  20882. return this._boundingInfo.intersectsPoint(point);
  20883. };
  20884. /**
  20885. * Gets the position of the current mesh in camera space
  20886. * @param camera defines the camera to use
  20887. * @returns a position
  20888. */
  20889. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20890. if (camera === void 0) { camera = null; }
  20891. if (!camera) {
  20892. camera = this.getScene().activeCamera;
  20893. }
  20894. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20895. };
  20896. /**
  20897. * Returns the distance from the mesh to the active camera
  20898. * @param camera defines the camera to use
  20899. * @returns the distance
  20900. */
  20901. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20902. if (camera === void 0) { camera = null; }
  20903. if (!camera) {
  20904. camera = this.getScene().activeCamera;
  20905. }
  20906. return this.absolutePosition.subtract(camera.position).length();
  20907. };
  20908. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20909. // Collisions
  20910. /**
  20911. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20912. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20913. */
  20914. get: function () {
  20915. return this._checkCollisions;
  20916. },
  20917. set: function (collisionEnabled) {
  20918. this._checkCollisions = collisionEnabled;
  20919. if (this.getScene().workerCollisions) {
  20920. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20921. }
  20922. },
  20923. enumerable: true,
  20924. configurable: true
  20925. });
  20926. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20927. /**
  20928. * Gets Collider object used to compute collisions (not physics)
  20929. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20930. */
  20931. get: function () {
  20932. return this._collider;
  20933. },
  20934. enumerable: true,
  20935. configurable: true
  20936. });
  20937. /**
  20938. * Move the mesh using collision engine
  20939. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20940. * @param displacement defines the requested displacement vector
  20941. * @returns the current mesh
  20942. */
  20943. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20944. var globalPosition = this.getAbsolutePosition();
  20945. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20946. if (!this._collider) {
  20947. this._collider = new BABYLON.Collider();
  20948. }
  20949. this._collider._radius = this.ellipsoid;
  20950. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20951. return this;
  20952. };
  20953. // Collisions
  20954. /** @hidden */
  20955. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20956. this._generatePointsArray();
  20957. if (!this._positions) {
  20958. return this;
  20959. }
  20960. // Transformation
  20961. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20962. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20963. subMesh._lastColliderWorldVertices = [];
  20964. subMesh._trianglePlanes = [];
  20965. var start = subMesh.verticesStart;
  20966. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20967. for (var i = start; i < end; i++) {
  20968. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20969. }
  20970. }
  20971. // Collide
  20972. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20973. if (collider.collisionFound) {
  20974. collider.collidedMesh = this;
  20975. }
  20976. return this;
  20977. };
  20978. /** @hidden */
  20979. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20980. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20981. var len = subMeshes.length;
  20982. for (var index = 0; index < len; index++) {
  20983. var subMesh = subMeshes.data[index];
  20984. // Bounding test
  20985. if (len > 1 && !subMesh._checkCollision(collider))
  20986. continue;
  20987. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20988. }
  20989. return this;
  20990. };
  20991. /** @hidden */
  20992. AbstractMesh.prototype._checkCollision = function (collider) {
  20993. // Bounding box test
  20994. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20995. return this;
  20996. // Transformation matrix
  20997. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20998. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20999. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21000. return this;
  21001. };
  21002. // Picking
  21003. /** @hidden */
  21004. AbstractMesh.prototype._generatePointsArray = function () {
  21005. return false;
  21006. };
  21007. /**
  21008. * Checks if the passed Ray intersects with the mesh
  21009. * @param ray defines the ray to use
  21010. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21011. * @returns the picking info
  21012. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21013. */
  21014. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21015. var pickingInfo = new BABYLON.PickingInfo();
  21016. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21017. return pickingInfo;
  21018. }
  21019. if (!this._generatePointsArray()) {
  21020. return pickingInfo;
  21021. }
  21022. var intersectInfo = null;
  21023. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21024. var len = subMeshes.length;
  21025. for (var index = 0; index < len; index++) {
  21026. var subMesh = subMeshes.data[index];
  21027. // Bounding test
  21028. if (len > 1 && !subMesh.canIntersects(ray))
  21029. continue;
  21030. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21031. if (currentIntersectInfo) {
  21032. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21033. intersectInfo = currentIntersectInfo;
  21034. intersectInfo.subMeshId = index;
  21035. if (fastCheck) {
  21036. break;
  21037. }
  21038. }
  21039. }
  21040. }
  21041. if (intersectInfo) {
  21042. // Get picked point
  21043. var world = this.getWorldMatrix();
  21044. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21045. var direction = ray.direction.clone();
  21046. direction = direction.scale(intersectInfo.distance);
  21047. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21048. var pickedPoint = worldOrigin.add(worldDirection);
  21049. // Return result
  21050. pickingInfo.hit = true;
  21051. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21052. pickingInfo.pickedPoint = pickedPoint;
  21053. pickingInfo.pickedMesh = this;
  21054. pickingInfo.bu = intersectInfo.bu || 0;
  21055. pickingInfo.bv = intersectInfo.bv || 0;
  21056. pickingInfo.faceId = intersectInfo.faceId;
  21057. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21058. return pickingInfo;
  21059. }
  21060. return pickingInfo;
  21061. };
  21062. /**
  21063. * Clones the current mesh
  21064. * @param name defines the mesh name
  21065. * @param newParent defines the new mesh parent
  21066. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21067. * @returns the new mesh
  21068. */
  21069. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21070. return null;
  21071. };
  21072. /**
  21073. * Disposes all the submeshes of the current meshnp
  21074. * @returns the current mesh
  21075. */
  21076. AbstractMesh.prototype.releaseSubMeshes = function () {
  21077. if (this.subMeshes) {
  21078. while (this.subMeshes.length) {
  21079. this.subMeshes[0].dispose();
  21080. }
  21081. }
  21082. else {
  21083. this.subMeshes = new Array();
  21084. }
  21085. return this;
  21086. };
  21087. /**
  21088. * Releases resources associated with this abstract mesh.
  21089. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21090. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21091. */
  21092. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21093. var _this = this;
  21094. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21095. var index;
  21096. // Smart Array Retainers.
  21097. this.getScene().freeActiveMeshes();
  21098. this.getScene().freeRenderingGroups();
  21099. // Action manager
  21100. if (this.actionManager !== undefined && this.actionManager !== null) {
  21101. this.actionManager.dispose();
  21102. this.actionManager = null;
  21103. }
  21104. // Skeleton
  21105. this._skeleton = null;
  21106. // Intersections in progress
  21107. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21108. var other = this._intersectionsInProgress[index];
  21109. var pos = other._intersectionsInProgress.indexOf(this);
  21110. other._intersectionsInProgress.splice(pos, 1);
  21111. }
  21112. this._intersectionsInProgress = [];
  21113. // Lights
  21114. var lights = this.getScene().lights;
  21115. lights.forEach(function (light) {
  21116. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21117. if (meshIndex !== -1) {
  21118. light.includedOnlyMeshes.splice(meshIndex, 1);
  21119. }
  21120. meshIndex = light.excludedMeshes.indexOf(_this);
  21121. if (meshIndex !== -1) {
  21122. light.excludedMeshes.splice(meshIndex, 1);
  21123. }
  21124. // Shadow generators
  21125. var generator = light.getShadowGenerator();
  21126. if (generator) {
  21127. var shadowMap = generator.getShadowMap();
  21128. if (shadowMap && shadowMap.renderList) {
  21129. meshIndex = shadowMap.renderList.indexOf(_this);
  21130. if (meshIndex !== -1) {
  21131. shadowMap.renderList.splice(meshIndex, 1);
  21132. }
  21133. }
  21134. }
  21135. });
  21136. // SubMeshes
  21137. if (this.getClassName() !== "InstancedMesh") {
  21138. this.releaseSubMeshes();
  21139. }
  21140. // Query
  21141. var engine = this.getScene().getEngine();
  21142. if (this._occlusionQuery) {
  21143. this._isOcclusionQueryInProgress = false;
  21144. engine.deleteQuery(this._occlusionQuery);
  21145. this._occlusionQuery = null;
  21146. }
  21147. // Engine
  21148. engine.wipeCaches();
  21149. // Remove from scene
  21150. this.getScene().removeMesh(this);
  21151. if (disposeMaterialAndTextures) {
  21152. if (this.material) {
  21153. this.material.dispose(false, true);
  21154. }
  21155. }
  21156. if (!doNotRecurse) {
  21157. // Particles
  21158. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21159. if (this.getScene().particleSystems[index].emitter === this) {
  21160. this.getScene().particleSystems[index].dispose();
  21161. index--;
  21162. }
  21163. }
  21164. }
  21165. // facet data
  21166. if (this._facetDataEnabled) {
  21167. this.disableFacetData();
  21168. }
  21169. this.onAfterWorldMatrixUpdateObservable.clear();
  21170. this.onCollideObservable.clear();
  21171. this.onCollisionPositionChangeObservable.clear();
  21172. this.onRebuildObservable.clear();
  21173. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21174. };
  21175. /**
  21176. * Adds the passed mesh as a child to the current mesh
  21177. * @param mesh defines the child mesh
  21178. * @returns the current mesh
  21179. */
  21180. AbstractMesh.prototype.addChild = function (mesh) {
  21181. mesh.setParent(this);
  21182. return this;
  21183. };
  21184. /**
  21185. * Removes the passed mesh from the current mesh children list
  21186. * @param mesh defines the child mesh
  21187. * @returns the current mesh
  21188. */
  21189. AbstractMesh.prototype.removeChild = function (mesh) {
  21190. mesh.setParent(null);
  21191. return this;
  21192. };
  21193. // Facet data
  21194. /** @hidden */
  21195. AbstractMesh.prototype._initFacetData = function () {
  21196. if (!this._facetNormals) {
  21197. this._facetNormals = new Array();
  21198. }
  21199. if (!this._facetPositions) {
  21200. this._facetPositions = new Array();
  21201. }
  21202. if (!this._facetPartitioning) {
  21203. this._facetPartitioning = new Array();
  21204. }
  21205. this._facetNb = (this.getIndices().length / 3) | 0;
  21206. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21207. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21208. for (var f = 0; f < this._facetNb; f++) {
  21209. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21210. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21211. }
  21212. this._facetDataEnabled = true;
  21213. return this;
  21214. };
  21215. /**
  21216. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21217. * This method can be called within the render loop.
  21218. * 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
  21219. * @returns the current mesh
  21220. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21221. */
  21222. AbstractMesh.prototype.updateFacetData = function () {
  21223. if (!this._facetDataEnabled) {
  21224. this._initFacetData();
  21225. }
  21226. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21227. var indices = this.getIndices();
  21228. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21229. var bInfo = this.getBoundingInfo();
  21230. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21231. // init arrays, matrix and sort function on first call
  21232. this._facetDepthSortEnabled = true;
  21233. if (indices instanceof Uint16Array) {
  21234. this._depthSortedIndices = new Uint16Array(indices);
  21235. }
  21236. else if (indices instanceof Uint32Array) {
  21237. this._depthSortedIndices = new Uint32Array(indices);
  21238. }
  21239. else {
  21240. var needs32bits = false;
  21241. for (var i = 0; i < indices.length; i++) {
  21242. if (indices[i] > 65535) {
  21243. needs32bits = true;
  21244. break;
  21245. }
  21246. }
  21247. if (needs32bits) {
  21248. this._depthSortedIndices = new Uint32Array(indices);
  21249. }
  21250. else {
  21251. this._depthSortedIndices = new Uint16Array(indices);
  21252. }
  21253. }
  21254. this._facetDepthSortFunction = function (f1, f2) {
  21255. return (f2.sqDistance - f1.sqDistance);
  21256. };
  21257. if (!this._facetDepthSortFrom) {
  21258. var camera = this.getScene().activeCamera;
  21259. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21260. }
  21261. this._depthSortedFacets = [];
  21262. for (var f = 0; f < this._facetNb; f++) {
  21263. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21264. this._depthSortedFacets.push(depthSortedFacet);
  21265. }
  21266. this._invertedMatrix = BABYLON.Matrix.Identity();
  21267. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21268. }
  21269. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21270. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21271. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21272. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21273. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21274. this._subDiv.max = this._partitioningSubdivisions;
  21275. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21276. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21277. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21278. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21279. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21280. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21281. // set the parameters for ComputeNormals()
  21282. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21283. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21284. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21285. this._facetParameters.bInfo = bInfo;
  21286. this._facetParameters.bbSize = this._bbSize;
  21287. this._facetParameters.subDiv = this._subDiv;
  21288. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21289. this._facetParameters.depthSort = this._facetDepthSort;
  21290. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21291. this.computeWorldMatrix(true);
  21292. this._worldMatrix.invertToRef(this._invertedMatrix);
  21293. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21294. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21295. }
  21296. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21297. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21298. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21299. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21300. var l = (this._depthSortedIndices.length / 3) | 0;
  21301. for (var f = 0; f < l; f++) {
  21302. var sind = this._depthSortedFacets[f].ind;
  21303. this._depthSortedIndices[f * 3] = indices[sind];
  21304. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21305. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21306. }
  21307. this.updateIndices(this._depthSortedIndices);
  21308. }
  21309. return this;
  21310. };
  21311. /**
  21312. * Returns the facetLocalNormals array.
  21313. * The normals are expressed in the mesh local spac
  21314. * @returns an array of Vector3
  21315. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21316. */
  21317. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21318. if (!this._facetNormals) {
  21319. this.updateFacetData();
  21320. }
  21321. return this._facetNormals;
  21322. };
  21323. /**
  21324. * Returns the facetLocalPositions array.
  21325. * The facet positions are expressed in the mesh local space
  21326. * @returns an array of Vector3
  21327. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21328. */
  21329. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21330. if (!this._facetPositions) {
  21331. this.updateFacetData();
  21332. }
  21333. return this._facetPositions;
  21334. };
  21335. /**
  21336. * Returns the facetLocalPartioning array
  21337. * @returns an array of array of numbers
  21338. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21339. */
  21340. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21341. if (!this._facetPartitioning) {
  21342. this.updateFacetData();
  21343. }
  21344. return this._facetPartitioning;
  21345. };
  21346. /**
  21347. * Returns the i-th facet position in the world system.
  21348. * This method allocates a new Vector3 per call
  21349. * @param i defines the facet index
  21350. * @returns a new Vector3
  21351. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21352. */
  21353. AbstractMesh.prototype.getFacetPosition = function (i) {
  21354. var pos = BABYLON.Vector3.Zero();
  21355. this.getFacetPositionToRef(i, pos);
  21356. return pos;
  21357. };
  21358. /**
  21359. * Sets the reference Vector3 with the i-th facet position in the world system
  21360. * @param i defines the facet index
  21361. * @param ref defines the target vector
  21362. * @returns the current mesh
  21363. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21364. */
  21365. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21366. var localPos = (this.getFacetLocalPositions())[i];
  21367. var world = this.getWorldMatrix();
  21368. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21369. return this;
  21370. };
  21371. /**
  21372. * Returns the i-th facet normal in the world system.
  21373. * This method allocates a new Vector3 per call
  21374. * @param i defines the facet index
  21375. * @returns a new Vector3
  21376. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21377. */
  21378. AbstractMesh.prototype.getFacetNormal = function (i) {
  21379. var norm = BABYLON.Vector3.Zero();
  21380. this.getFacetNormalToRef(i, norm);
  21381. return norm;
  21382. };
  21383. /**
  21384. * Sets the reference Vector3 with the i-th facet normal in the world system
  21385. * @param i defines the facet index
  21386. * @param ref defines the target vector
  21387. * @returns the current mesh
  21388. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21389. */
  21390. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21391. var localNorm = (this.getFacetLocalNormals())[i];
  21392. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21393. return this;
  21394. };
  21395. /**
  21396. * 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)
  21397. * @param x defines x coordinate
  21398. * @param y defines y coordinate
  21399. * @param z defines z coordinate
  21400. * @returns the array of facet indexes
  21401. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21402. */
  21403. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21404. var bInfo = this.getBoundingInfo();
  21405. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21406. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21407. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21408. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21409. return null;
  21410. }
  21411. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21412. };
  21413. /**
  21414. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21415. * @param projected sets as the (x,y,z) world projection on the facet
  21416. * @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
  21417. * @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
  21418. * @param x defines x coordinate
  21419. * @param y defines y coordinate
  21420. * @param z defines z coordinate
  21421. * @returns the face index if found (or null instead)
  21422. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21423. */
  21424. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21425. if (checkFace === void 0) { checkFace = false; }
  21426. if (facing === void 0) { facing = true; }
  21427. var world = this.getWorldMatrix();
  21428. var invMat = BABYLON.Tmp.Matrix[5];
  21429. world.invertToRef(invMat);
  21430. var invVect = BABYLON.Tmp.Vector3[8];
  21431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21432. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21433. if (projected) {
  21434. // tranform the local computed projected vector to world coordinates
  21435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21436. }
  21437. return closest;
  21438. };
  21439. /**
  21440. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21441. * @param projected sets as the (x,y,z) local projection on the facet
  21442. * @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
  21443. * @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
  21444. * @param x defines x coordinate
  21445. * @param y defines y coordinate
  21446. * @param z defines z coordinate
  21447. * @returns the face index if found (or null instead)
  21448. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21449. */
  21450. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21451. if (checkFace === void 0) { checkFace = false; }
  21452. if (facing === void 0) { facing = true; }
  21453. var closest = null;
  21454. var tmpx = 0.0;
  21455. var tmpy = 0.0;
  21456. var tmpz = 0.0;
  21457. var d = 0.0; // tmp dot facet normal * facet position
  21458. var t0 = 0.0;
  21459. var projx = 0.0;
  21460. var projy = 0.0;
  21461. var projz = 0.0;
  21462. // Get all the facets in the same partitioning block than (x, y, z)
  21463. var facetPositions = this.getFacetLocalPositions();
  21464. var facetNormals = this.getFacetLocalNormals();
  21465. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21466. if (!facetsInBlock) {
  21467. return null;
  21468. }
  21469. // Get the closest facet to (x, y, z)
  21470. var shortest = Number.MAX_VALUE; // init distance vars
  21471. var tmpDistance = shortest;
  21472. var fib; // current facet in the block
  21473. var norm; // current facet normal
  21474. var p0; // current facet barycenter position
  21475. // loop on all the facets in the current partitioning block
  21476. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21477. fib = facetsInBlock[idx];
  21478. norm = facetNormals[fib];
  21479. p0 = facetPositions[fib];
  21480. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21481. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21482. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21483. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21484. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21485. projx = x + norm.x * t0;
  21486. projy = y + norm.y * t0;
  21487. projz = z + norm.z * t0;
  21488. tmpx = projx - x;
  21489. tmpy = projy - y;
  21490. tmpz = projz - z;
  21491. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21492. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21493. shortest = tmpDistance;
  21494. closest = fib;
  21495. if (projected) {
  21496. projected.x = projx;
  21497. projected.y = projy;
  21498. projected.z = projz;
  21499. }
  21500. }
  21501. }
  21502. }
  21503. return closest;
  21504. };
  21505. /**
  21506. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21507. * @returns the parameters
  21508. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21509. */
  21510. AbstractMesh.prototype.getFacetDataParameters = function () {
  21511. return this._facetParameters;
  21512. };
  21513. /**
  21514. * Disables the feature FacetData and frees the related memory
  21515. * @returns the current mesh
  21516. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21517. */
  21518. AbstractMesh.prototype.disableFacetData = function () {
  21519. if (this._facetDataEnabled) {
  21520. this._facetDataEnabled = false;
  21521. this._facetPositions = new Array();
  21522. this._facetNormals = new Array();
  21523. this._facetPartitioning = new Array();
  21524. this._facetParameters = null;
  21525. this._depthSortedIndices = new Uint32Array(0);
  21526. }
  21527. return this;
  21528. };
  21529. /**
  21530. * Updates the AbstractMesh indices array
  21531. * @param indices defines the data source
  21532. * @returns the current mesh
  21533. */
  21534. AbstractMesh.prototype.updateIndices = function (indices) {
  21535. return this;
  21536. };
  21537. /**
  21538. * Creates new normals data for the mesh
  21539. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21540. * @returns the current mesh
  21541. */
  21542. AbstractMesh.prototype.createNormals = function (updatable) {
  21543. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21544. var indices = this.getIndices();
  21545. var normals;
  21546. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21547. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21548. }
  21549. else {
  21550. normals = [];
  21551. }
  21552. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21553. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21554. return this;
  21555. };
  21556. /**
  21557. * Align the mesh with a normal
  21558. * @param normal defines the normal to use
  21559. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21560. * @returns the current mesh
  21561. */
  21562. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21563. if (!upDirection) {
  21564. upDirection = BABYLON.Axis.Y;
  21565. }
  21566. var axisX = BABYLON.Tmp.Vector3[0];
  21567. var axisZ = BABYLON.Tmp.Vector3[1];
  21568. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21569. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21570. if (this.rotationQuaternion) {
  21571. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21572. }
  21573. else {
  21574. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21575. }
  21576. return this;
  21577. };
  21578. /** @hidden */
  21579. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21580. this._isOccluded = false;
  21581. };
  21582. /** No occlusion */
  21583. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21584. /** Occlusion set to optimisitic */
  21585. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21586. /** Occlusion set to strict */
  21587. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21588. /** Use an accurante occlusion algorithm */
  21589. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21590. /** Use a conservative occlusion algorithm */
  21591. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21592. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21593. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21594. /** Culling strategy with bounding sphere only and then frustum culling */
  21595. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21596. return AbstractMesh;
  21597. }(BABYLON.TransformNode));
  21598. BABYLON.AbstractMesh = AbstractMesh;
  21599. })(BABYLON || (BABYLON = {}));
  21600. //# sourceMappingURL=babylon.abstractMesh.js.map
  21601. var BABYLON;
  21602. (function (BABYLON) {
  21603. /**
  21604. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21605. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21606. * 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.
  21607. */
  21608. var Light = /** @class */ (function (_super) {
  21609. __extends(Light, _super);
  21610. /**
  21611. * Creates a Light object in the scene.
  21612. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21613. * @param name The firendly name of the light
  21614. * @param scene The scene the light belongs too
  21615. */
  21616. function Light(name, scene) {
  21617. var _this = _super.call(this, name, scene) || this;
  21618. /**
  21619. * Diffuse gives the basic color to an object.
  21620. */
  21621. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21622. /**
  21623. * Specular produces a highlight color on an object.
  21624. * Note: This is note affecting PBR materials.
  21625. */
  21626. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21627. /**
  21628. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21629. * falling off base on range or angle.
  21630. * This can be set to any values in Light.FALLOFF_x.
  21631. *
  21632. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21633. * other types of materials.
  21634. */
  21635. _this.falloffType = Light.FALLOFF_DEFAULT;
  21636. /**
  21637. * Strength of the light.
  21638. * Note: By default it is define in the framework own unit.
  21639. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21640. */
  21641. _this.intensity = 1.0;
  21642. _this._range = Number.MAX_VALUE;
  21643. _this._inverseSquaredRange = 0;
  21644. /**
  21645. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21646. * of light.
  21647. */
  21648. _this._photometricScale = 1.0;
  21649. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21650. _this._radius = 0.00001;
  21651. /**
  21652. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21653. * exceeding the number allowed of the materials.
  21654. */
  21655. _this.renderPriority = 0;
  21656. _this._shadowEnabled = true;
  21657. _this._excludeWithLayerMask = 0;
  21658. _this._includeOnlyWithLayerMask = 0;
  21659. _this._lightmapMode = 0;
  21660. /**
  21661. * @hidden Internal use only.
  21662. */
  21663. _this._excludedMeshesIds = new Array();
  21664. /**
  21665. * @hidden Internal use only.
  21666. */
  21667. _this._includedOnlyMeshesIds = new Array();
  21668. _this.getScene().addLight(_this);
  21669. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21670. _this._buildUniformLayout();
  21671. _this.includedOnlyMeshes = new Array();
  21672. _this.excludedMeshes = new Array();
  21673. _this._resyncMeshes();
  21674. return _this;
  21675. }
  21676. Object.defineProperty(Light.prototype, "range", {
  21677. /**
  21678. * Defines how far from the source the light is impacting in scene units.
  21679. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21680. */
  21681. get: function () {
  21682. return this._range;
  21683. },
  21684. /**
  21685. * Defines how far from the source the light is impacting in scene units.
  21686. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21687. */
  21688. set: function (value) {
  21689. this._range = value;
  21690. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21691. },
  21692. enumerable: true,
  21693. configurable: true
  21694. });
  21695. Object.defineProperty(Light.prototype, "intensityMode", {
  21696. /**
  21697. * Gets the photometric scale used to interpret the intensity.
  21698. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21699. */
  21700. get: function () {
  21701. return this._intensityMode;
  21702. },
  21703. /**
  21704. * Sets the photometric scale used to interpret the intensity.
  21705. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21706. */
  21707. set: function (value) {
  21708. this._intensityMode = value;
  21709. this._computePhotometricScale();
  21710. },
  21711. enumerable: true,
  21712. configurable: true
  21713. });
  21714. ;
  21715. ;
  21716. Object.defineProperty(Light.prototype, "radius", {
  21717. /**
  21718. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21719. */
  21720. get: function () {
  21721. return this._radius;
  21722. },
  21723. /**
  21724. * sets the light radius used by PBR Materials to simulate soft area lights.
  21725. */
  21726. set: function (value) {
  21727. this._radius = value;
  21728. this._computePhotometricScale();
  21729. },
  21730. enumerable: true,
  21731. configurable: true
  21732. });
  21733. ;
  21734. ;
  21735. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21736. /**
  21737. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21738. * the current shadow generator.
  21739. */
  21740. get: function () {
  21741. return this._shadowEnabled;
  21742. },
  21743. /**
  21744. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21745. * the current shadow generator.
  21746. */
  21747. set: function (value) {
  21748. if (this._shadowEnabled === value) {
  21749. return;
  21750. }
  21751. this._shadowEnabled = value;
  21752. this._markMeshesAsLightDirty();
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21758. /**
  21759. * Gets the only meshes impacted by this light.
  21760. */
  21761. get: function () {
  21762. return this._includedOnlyMeshes;
  21763. },
  21764. /**
  21765. * Sets the only meshes impacted by this light.
  21766. */
  21767. set: function (value) {
  21768. this._includedOnlyMeshes = value;
  21769. this._hookArrayForIncludedOnly(value);
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21775. /**
  21776. * Gets the meshes not impacted by this light.
  21777. */
  21778. get: function () {
  21779. return this._excludedMeshes;
  21780. },
  21781. /**
  21782. * Sets the meshes not impacted by this light.
  21783. */
  21784. set: function (value) {
  21785. this._excludedMeshes = value;
  21786. this._hookArrayForExcluded(value);
  21787. },
  21788. enumerable: true,
  21789. configurable: true
  21790. });
  21791. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21792. /**
  21793. * Gets the layer id use to find what meshes are not impacted by the light.
  21794. * Inactive if 0
  21795. */
  21796. get: function () {
  21797. return this._excludeWithLayerMask;
  21798. },
  21799. /**
  21800. * Sets the layer id use to find what meshes are not impacted by the light.
  21801. * Inactive if 0
  21802. */
  21803. set: function (value) {
  21804. this._excludeWithLayerMask = value;
  21805. this._resyncMeshes();
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21811. /**
  21812. * Gets the layer id use to find what meshes are impacted by the light.
  21813. * Inactive if 0
  21814. */
  21815. get: function () {
  21816. return this._includeOnlyWithLayerMask;
  21817. },
  21818. /**
  21819. * Sets the layer id use to find what meshes are impacted by the light.
  21820. * Inactive if 0
  21821. */
  21822. set: function (value) {
  21823. this._includeOnlyWithLayerMask = value;
  21824. this._resyncMeshes();
  21825. },
  21826. enumerable: true,
  21827. configurable: true
  21828. });
  21829. Object.defineProperty(Light.prototype, "lightmapMode", {
  21830. /**
  21831. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21832. */
  21833. get: function () {
  21834. return this._lightmapMode;
  21835. },
  21836. /**
  21837. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21838. */
  21839. set: function (value) {
  21840. if (this._lightmapMode === value) {
  21841. return;
  21842. }
  21843. this._lightmapMode = value;
  21844. this._markMeshesAsLightDirty();
  21845. },
  21846. enumerable: true,
  21847. configurable: true
  21848. });
  21849. /**
  21850. * Returns the string "Light".
  21851. * @returns the class name
  21852. */
  21853. Light.prototype.getClassName = function () {
  21854. return "Light";
  21855. };
  21856. /**
  21857. * Converts the light information to a readable string for debug purpose.
  21858. * @param fullDetails Supports for multiple levels of logging within scene loading
  21859. * @returns the human readable light info
  21860. */
  21861. Light.prototype.toString = function (fullDetails) {
  21862. var ret = "Name: " + this.name;
  21863. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21864. if (this.animations) {
  21865. for (var i = 0; i < this.animations.length; i++) {
  21866. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21867. }
  21868. }
  21869. if (fullDetails) {
  21870. }
  21871. return ret;
  21872. };
  21873. /** @hidden */
  21874. Light.prototype._syncParentEnabledState = function () {
  21875. _super.prototype._syncParentEnabledState.call(this);
  21876. this._resyncMeshes();
  21877. };
  21878. /**
  21879. * Set the enabled state of this node.
  21880. * @param value - the new enabled state
  21881. */
  21882. Light.prototype.setEnabled = function (value) {
  21883. _super.prototype.setEnabled.call(this, value);
  21884. this._resyncMeshes();
  21885. };
  21886. /**
  21887. * Returns the Light associated shadow generator if any.
  21888. * @return the associated shadow generator.
  21889. */
  21890. Light.prototype.getShadowGenerator = function () {
  21891. return this._shadowGenerator;
  21892. };
  21893. /**
  21894. * Returns a Vector3, the absolute light position in the World.
  21895. * @returns the world space position of the light
  21896. */
  21897. Light.prototype.getAbsolutePosition = function () {
  21898. return BABYLON.Vector3.Zero();
  21899. };
  21900. /**
  21901. * Specifies if the light will affect the passed mesh.
  21902. * @param mesh The mesh to test against the light
  21903. * @return true the mesh is affected otherwise, false.
  21904. */
  21905. Light.prototype.canAffectMesh = function (mesh) {
  21906. if (!mesh) {
  21907. return true;
  21908. }
  21909. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21910. return false;
  21911. }
  21912. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21913. return false;
  21914. }
  21915. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21916. return false;
  21917. }
  21918. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21919. return false;
  21920. }
  21921. return true;
  21922. };
  21923. /**
  21924. * Sort function to order lights for rendering.
  21925. * @param a First Light object to compare to second.
  21926. * @param b Second Light object to compare first.
  21927. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21928. */
  21929. Light.CompareLightsPriority = function (a, b) {
  21930. //shadow-casting lights have priority over non-shadow-casting lights
  21931. //the renderPrioirty is a secondary sort criterion
  21932. if (a.shadowEnabled !== b.shadowEnabled) {
  21933. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21934. }
  21935. return b.renderPriority - a.renderPriority;
  21936. };
  21937. /**
  21938. * Releases resources associated with this node.
  21939. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21940. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21941. */
  21942. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21943. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21944. if (this._shadowGenerator) {
  21945. this._shadowGenerator.dispose();
  21946. this._shadowGenerator = null;
  21947. }
  21948. // Animations
  21949. this.getScene().stopAnimation(this);
  21950. // Remove from meshes
  21951. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21952. var mesh = _a[_i];
  21953. mesh._removeLightSource(this);
  21954. }
  21955. this._uniformBuffer.dispose();
  21956. // Remove from scene
  21957. this.getScene().removeLight(this);
  21958. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21959. };
  21960. /**
  21961. * Returns the light type ID (integer).
  21962. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21963. */
  21964. Light.prototype.getTypeID = function () {
  21965. return 0;
  21966. };
  21967. /**
  21968. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21969. * @returns the scaled intensity in intensity mode unit
  21970. */
  21971. Light.prototype.getScaledIntensity = function () {
  21972. return this._photometricScale * this.intensity;
  21973. };
  21974. /**
  21975. * Returns a new Light object, named "name", from the current one.
  21976. * @param name The name of the cloned light
  21977. * @returns the new created light
  21978. */
  21979. Light.prototype.clone = function (name) {
  21980. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21981. if (!constructor) {
  21982. return null;
  21983. }
  21984. return BABYLON.SerializationHelper.Clone(constructor, this);
  21985. };
  21986. /**
  21987. * Serializes the current light into a Serialization object.
  21988. * @returns the serialized object.
  21989. */
  21990. Light.prototype.serialize = function () {
  21991. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21992. // Type
  21993. serializationObject.type = this.getTypeID();
  21994. // Parent
  21995. if (this.parent) {
  21996. serializationObject.parentId = this.parent.id;
  21997. }
  21998. // Inclusion / exclusions
  21999. if (this.excludedMeshes.length > 0) {
  22000. serializationObject.excludedMeshesIds = [];
  22001. this.excludedMeshes.forEach(function (mesh) {
  22002. serializationObject.excludedMeshesIds.push(mesh.id);
  22003. });
  22004. }
  22005. if (this.includedOnlyMeshes.length > 0) {
  22006. serializationObject.includedOnlyMeshesIds = [];
  22007. this.includedOnlyMeshes.forEach(function (mesh) {
  22008. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22009. });
  22010. }
  22011. // Animations
  22012. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22013. serializationObject.ranges = this.serializeAnimationRanges();
  22014. return serializationObject;
  22015. };
  22016. /**
  22017. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22018. * This new light is named "name" and added to the passed scene.
  22019. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22020. * @param name The friendly name of the light
  22021. * @param scene The scene the new light will belong to
  22022. * @returns the constructor function
  22023. */
  22024. Light.GetConstructorFromName = function (type, name, scene) {
  22025. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22026. if (constructorFunc) {
  22027. return constructorFunc;
  22028. }
  22029. // Default to no light for none present once.
  22030. return null;
  22031. };
  22032. /**
  22033. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22034. * @param parsedLight The JSON representation of the light
  22035. * @param scene The scene to create the parsed light in
  22036. * @returns the created light after parsing
  22037. */
  22038. Light.Parse = function (parsedLight, scene) {
  22039. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22040. if (!constructor) {
  22041. return null;
  22042. }
  22043. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22044. // Inclusion / exclusions
  22045. if (parsedLight.excludedMeshesIds) {
  22046. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22047. }
  22048. if (parsedLight.includedOnlyMeshesIds) {
  22049. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22050. }
  22051. // Parent
  22052. if (parsedLight.parentId) {
  22053. light._waitingParentId = parsedLight.parentId;
  22054. }
  22055. // Animations
  22056. if (parsedLight.animations) {
  22057. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22058. var parsedAnimation = parsedLight.animations[animationIndex];
  22059. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22060. }
  22061. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22062. }
  22063. if (parsedLight.autoAnimate) {
  22064. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22065. }
  22066. return light;
  22067. };
  22068. Light.prototype._hookArrayForExcluded = function (array) {
  22069. var _this = this;
  22070. var oldPush = array.push;
  22071. array.push = function () {
  22072. var items = [];
  22073. for (var _i = 0; _i < arguments.length; _i++) {
  22074. items[_i] = arguments[_i];
  22075. }
  22076. var result = oldPush.apply(array, items);
  22077. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22078. var item = items_1[_a];
  22079. item._resyncLighSource(_this);
  22080. }
  22081. return result;
  22082. };
  22083. var oldSplice = array.splice;
  22084. array.splice = function (index, deleteCount) {
  22085. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22086. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22087. var item = deleted_1[_i];
  22088. item._resyncLighSource(_this);
  22089. }
  22090. return deleted;
  22091. };
  22092. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22093. var item = array_1[_i];
  22094. item._resyncLighSource(this);
  22095. }
  22096. };
  22097. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22098. var _this = this;
  22099. var oldPush = array.push;
  22100. array.push = function () {
  22101. var items = [];
  22102. for (var _i = 0; _i < arguments.length; _i++) {
  22103. items[_i] = arguments[_i];
  22104. }
  22105. var result = oldPush.apply(array, items);
  22106. _this._resyncMeshes();
  22107. return result;
  22108. };
  22109. var oldSplice = array.splice;
  22110. array.splice = function (index, deleteCount) {
  22111. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22112. _this._resyncMeshes();
  22113. return deleted;
  22114. };
  22115. this._resyncMeshes();
  22116. };
  22117. Light.prototype._resyncMeshes = function () {
  22118. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22119. var mesh = _a[_i];
  22120. mesh._resyncLighSource(this);
  22121. }
  22122. };
  22123. /**
  22124. * Forces the meshes to update their light related information in their rendering used effects
  22125. * @hidden Internal Use Only
  22126. */
  22127. Light.prototype._markMeshesAsLightDirty = function () {
  22128. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22129. var mesh = _a[_i];
  22130. if (mesh._lightSources.indexOf(this) !== -1) {
  22131. mesh._markSubMeshesAsLightDirty();
  22132. }
  22133. }
  22134. };
  22135. /**
  22136. * Recomputes the cached photometric scale if needed.
  22137. */
  22138. Light.prototype._computePhotometricScale = function () {
  22139. this._photometricScale = this._getPhotometricScale();
  22140. this.getScene().resetCachedMaterial();
  22141. };
  22142. /**
  22143. * Returns the Photometric Scale according to the light type and intensity mode.
  22144. */
  22145. Light.prototype._getPhotometricScale = function () {
  22146. var photometricScale = 0.0;
  22147. var lightTypeID = this.getTypeID();
  22148. //get photometric mode
  22149. var photometricMode = this.intensityMode;
  22150. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22151. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22152. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22153. }
  22154. else {
  22155. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22156. }
  22157. }
  22158. //compute photometric scale
  22159. switch (lightTypeID) {
  22160. case Light.LIGHTTYPEID_POINTLIGHT:
  22161. case Light.LIGHTTYPEID_SPOTLIGHT:
  22162. switch (photometricMode) {
  22163. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22164. photometricScale = 1.0 / (4.0 * Math.PI);
  22165. break;
  22166. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22167. photometricScale = 1.0;
  22168. break;
  22169. case Light.INTENSITYMODE_LUMINANCE:
  22170. photometricScale = this.radius * this.radius;
  22171. break;
  22172. }
  22173. break;
  22174. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22175. switch (photometricMode) {
  22176. case Light.INTENSITYMODE_ILLUMINANCE:
  22177. photometricScale = 1.0;
  22178. break;
  22179. case Light.INTENSITYMODE_LUMINANCE:
  22180. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22181. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22182. var apexAngleRadians = this.radius;
  22183. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22184. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22185. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22186. photometricScale = solidAngle;
  22187. break;
  22188. }
  22189. break;
  22190. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22191. // No fall off in hemisperic light.
  22192. photometricScale = 1.0;
  22193. break;
  22194. }
  22195. return photometricScale;
  22196. };
  22197. /**
  22198. * Reorder the light in the scene according to their defined priority.
  22199. * @hidden Internal Use Only
  22200. */
  22201. Light.prototype._reorderLightsInScene = function () {
  22202. var scene = this.getScene();
  22203. if (this._renderPriority != 0) {
  22204. scene.requireLightSorting = true;
  22205. }
  22206. this.getScene().sortLightsByPriority();
  22207. };
  22208. /**
  22209. * Falloff Default: light is falling off following the material specification:
  22210. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22211. */
  22212. Light.FALLOFF_DEFAULT = 0;
  22213. /**
  22214. * Falloff Physical: light is falling off following the inverse squared distance law.
  22215. */
  22216. Light.FALLOFF_PHYSICAL = 1;
  22217. /**
  22218. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22219. * to enhance interoperability with other engines.
  22220. */
  22221. Light.FALLOFF_GLTF = 2;
  22222. /**
  22223. * Falloff Standard: light is falling off like in the standard material
  22224. * to enhance interoperability with other materials.
  22225. */
  22226. Light.FALLOFF_STANDARD = 3;
  22227. //lightmapMode Consts
  22228. /**
  22229. * If every light affecting the material is in this lightmapMode,
  22230. * material.lightmapTexture adds or multiplies
  22231. * (depends on material.useLightmapAsShadowmap)
  22232. * after every other light calculations.
  22233. */
  22234. Light.LIGHTMAP_DEFAULT = 0;
  22235. /**
  22236. * material.lightmapTexture as only diffuse lighting from this light
  22237. * adds only specular lighting from this light
  22238. * adds dynamic shadows
  22239. */
  22240. Light.LIGHTMAP_SPECULAR = 1;
  22241. /**
  22242. * material.lightmapTexture as only lighting
  22243. * no light calculation from this light
  22244. * only adds dynamic shadows from this light
  22245. */
  22246. Light.LIGHTMAP_SHADOWSONLY = 2;
  22247. // Intensity Mode Consts
  22248. /**
  22249. * Each light type uses the default quantity according to its type:
  22250. * point/spot lights use luminous intensity
  22251. * directional lights use illuminance
  22252. */
  22253. Light.INTENSITYMODE_AUTOMATIC = 0;
  22254. /**
  22255. * lumen (lm)
  22256. */
  22257. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22258. /**
  22259. * candela (lm/sr)
  22260. */
  22261. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22262. /**
  22263. * lux (lm/m^2)
  22264. */
  22265. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22266. /**
  22267. * nit (cd/m^2)
  22268. */
  22269. Light.INTENSITYMODE_LUMINANCE = 4;
  22270. // Light types ids const.
  22271. /**
  22272. * Light type const id of the point light.
  22273. */
  22274. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22275. /**
  22276. * Light type const id of the directional light.
  22277. */
  22278. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22279. /**
  22280. * Light type const id of the spot light.
  22281. */
  22282. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22283. /**
  22284. * Light type const id of the hemispheric light.
  22285. */
  22286. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22287. __decorate([
  22288. BABYLON.serializeAsColor3()
  22289. ], Light.prototype, "diffuse", void 0);
  22290. __decorate([
  22291. BABYLON.serializeAsColor3()
  22292. ], Light.prototype, "specular", void 0);
  22293. __decorate([
  22294. BABYLON.serialize()
  22295. ], Light.prototype, "falloffType", void 0);
  22296. __decorate([
  22297. BABYLON.serialize()
  22298. ], Light.prototype, "intensity", void 0);
  22299. __decorate([
  22300. BABYLON.serialize()
  22301. ], Light.prototype, "range", null);
  22302. __decorate([
  22303. BABYLON.serialize()
  22304. ], Light.prototype, "intensityMode", null);
  22305. __decorate([
  22306. BABYLON.serialize()
  22307. ], Light.prototype, "radius", null);
  22308. __decorate([
  22309. BABYLON.serialize()
  22310. ], Light.prototype, "_renderPriority", void 0);
  22311. __decorate([
  22312. BABYLON.expandToProperty("_reorderLightsInScene")
  22313. ], Light.prototype, "renderPriority", void 0);
  22314. __decorate([
  22315. BABYLON.serialize("shadowEnabled")
  22316. ], Light.prototype, "_shadowEnabled", void 0);
  22317. __decorate([
  22318. BABYLON.serialize("excludeWithLayerMask")
  22319. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22320. __decorate([
  22321. BABYLON.serialize("includeOnlyWithLayerMask")
  22322. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22323. __decorate([
  22324. BABYLON.serialize("lightmapMode")
  22325. ], Light.prototype, "_lightmapMode", void 0);
  22326. return Light;
  22327. }(BABYLON.Node));
  22328. BABYLON.Light = Light;
  22329. })(BABYLON || (BABYLON = {}));
  22330. //# sourceMappingURL=babylon.light.js.map
  22331. var BABYLON;
  22332. (function (BABYLON) {
  22333. /**
  22334. * This is the base class of all the camera used in the application.
  22335. * @see http://doc.babylonjs.com/features/cameras
  22336. */
  22337. var Camera = /** @class */ (function (_super) {
  22338. __extends(Camera, _super);
  22339. /**
  22340. * Instantiates a new camera object.
  22341. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22342. * @see http://doc.babylonjs.com/features/cameras
  22343. * @param name Defines the name of the camera in the scene
  22344. * @param position Defines the position of the camera
  22345. * @param scene Defines the scene the camera belongs too
  22346. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22347. */
  22348. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22349. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22350. var _this = _super.call(this, name, scene) || this;
  22351. /**
  22352. * The vector the camera should consider as up.
  22353. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22354. */
  22355. _this.upVector = BABYLON.Vector3.Up();
  22356. /**
  22357. * Define the current limit on the left side for an orthographic camera
  22358. * In scene unit
  22359. */
  22360. _this.orthoLeft = null;
  22361. /**
  22362. * Define the current limit on the right side for an orthographic camera
  22363. * In scene unit
  22364. */
  22365. _this.orthoRight = null;
  22366. /**
  22367. * Define the current limit on the bottom side for an orthographic camera
  22368. * In scene unit
  22369. */
  22370. _this.orthoBottom = null;
  22371. /**
  22372. * Define the current limit on the top side for an orthographic camera
  22373. * In scene unit
  22374. */
  22375. _this.orthoTop = null;
  22376. /**
  22377. * Field Of View is set in Radians. (default is 0.8)
  22378. */
  22379. _this.fov = 0.8;
  22380. /**
  22381. * Define the minimum distance the camera can see from.
  22382. * This is important to note that the depth buffer are not infinite and the closer it starts
  22383. * the more your scene might encounter depth fighting issue.
  22384. */
  22385. _this.minZ = 1;
  22386. /**
  22387. * Define the maximum distance the camera can see to.
  22388. * This is important to note that the depth buffer are not infinite and the further it end
  22389. * the more your scene might encounter depth fighting issue.
  22390. */
  22391. _this.maxZ = 10000.0;
  22392. /**
  22393. * Define the default inertia of the camera.
  22394. * This helps giving a smooth feeling to the camera movement.
  22395. */
  22396. _this.inertia = 0.9;
  22397. /**
  22398. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22399. */
  22400. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22401. /**
  22402. * Define wether the camera is intermediate.
  22403. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22404. */
  22405. _this.isIntermediate = false;
  22406. /**
  22407. * Define the viewport of the camera.
  22408. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22409. */
  22410. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22411. /**
  22412. * Restricts the camera to viewing objects with the same layerMask.
  22413. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22414. */
  22415. _this.layerMask = 0x0FFFFFFF;
  22416. /**
  22417. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22418. */
  22419. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22420. /**
  22421. * Rig mode of the camera.
  22422. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22423. * This is normally controlled byt the camera themselves as internal use.
  22424. */
  22425. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22426. /**
  22427. * Defines the list of custom render target the camera should render to.
  22428. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22429. * else in the scene.
  22430. */
  22431. _this.customRenderTargets = new Array();
  22432. /**
  22433. * Observable triggered when the camera view matrix has changed.
  22434. */
  22435. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22436. /**
  22437. * Observable triggered when the camera Projection matrix has changed.
  22438. */
  22439. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22440. /**
  22441. * Observable triggered when the inputs have been processed.
  22442. */
  22443. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22444. /**
  22445. * Observable triggered when reset has been called and applied to the camera.
  22446. */
  22447. _this.onRestoreStateObservable = new BABYLON.Observable();
  22448. /** @hidden */
  22449. _this._rigCameras = new Array();
  22450. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22451. /** @hidden */
  22452. _this._skipRendering = false;
  22453. /** @hidden */
  22454. _this._projectionMatrix = new BABYLON.Matrix();
  22455. /** @hidden */
  22456. _this._postProcesses = new Array();
  22457. /** @hidden */
  22458. _this._activeMeshes = new BABYLON.SmartArray(256);
  22459. _this._globalPosition = BABYLON.Vector3.Zero();
  22460. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22461. _this._doNotComputeProjectionMatrix = false;
  22462. _this._transformMatrix = BABYLON.Matrix.Zero();
  22463. _this._refreshFrustumPlanes = true;
  22464. _this.getScene().addCamera(_this);
  22465. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22466. _this.getScene().activeCamera = _this;
  22467. }
  22468. _this.position = position;
  22469. return _this;
  22470. }
  22471. /**
  22472. * Store current camera state (fov, position, etc..)
  22473. * @returns the camera
  22474. */
  22475. Camera.prototype.storeState = function () {
  22476. this._stateStored = true;
  22477. this._storedFov = this.fov;
  22478. return this;
  22479. };
  22480. /**
  22481. * Restores the camera state values if it has been stored. You must call storeState() first
  22482. */
  22483. Camera.prototype._restoreStateValues = function () {
  22484. if (!this._stateStored) {
  22485. return false;
  22486. }
  22487. this.fov = this._storedFov;
  22488. return true;
  22489. };
  22490. /**
  22491. * Restored camera state. You must call storeState() first.
  22492. * @returns true if restored and false otherwise
  22493. */
  22494. Camera.prototype.restoreState = function () {
  22495. if (this._restoreStateValues()) {
  22496. this.onRestoreStateObservable.notifyObservers(this);
  22497. return true;
  22498. }
  22499. return false;
  22500. };
  22501. /**
  22502. * Gets the class name of the camera.
  22503. * @returns the class name
  22504. */
  22505. Camera.prototype.getClassName = function () {
  22506. return "Camera";
  22507. };
  22508. /**
  22509. * Gets a string representation of the camera usefull for debug purpose.
  22510. * @param fullDetails Defines that a more verboe level of logging is required
  22511. * @returns the string representation
  22512. */
  22513. Camera.prototype.toString = function (fullDetails) {
  22514. var ret = "Name: " + this.name;
  22515. ret += ", type: " + this.getClassName();
  22516. if (this.animations) {
  22517. for (var i = 0; i < this.animations.length; i++) {
  22518. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22519. }
  22520. }
  22521. if (fullDetails) {
  22522. }
  22523. return ret;
  22524. };
  22525. Object.defineProperty(Camera.prototype, "globalPosition", {
  22526. /**
  22527. * Gets the current world space position of the camera.
  22528. */
  22529. get: function () {
  22530. return this._globalPosition;
  22531. },
  22532. enumerable: true,
  22533. configurable: true
  22534. });
  22535. /**
  22536. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22537. * @returns the active meshe list
  22538. */
  22539. Camera.prototype.getActiveMeshes = function () {
  22540. return this._activeMeshes;
  22541. };
  22542. /**
  22543. * Check wether a mesh is part of the current active mesh list of the camera
  22544. * @param mesh Defines the mesh to check
  22545. * @returns true if active, false otherwise
  22546. */
  22547. Camera.prototype.isActiveMesh = function (mesh) {
  22548. return (this._activeMeshes.indexOf(mesh) !== -1);
  22549. };
  22550. /**
  22551. * Is this camera ready to be used/rendered
  22552. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22553. * @return true if the camera is ready
  22554. */
  22555. Camera.prototype.isReady = function (completeCheck) {
  22556. if (completeCheck === void 0) { completeCheck = false; }
  22557. if (completeCheck) {
  22558. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22559. var pp = _a[_i];
  22560. if (pp && !pp.isReady()) {
  22561. return false;
  22562. }
  22563. }
  22564. }
  22565. return _super.prototype.isReady.call(this, completeCheck);
  22566. };
  22567. /** @hidden */
  22568. Camera.prototype._initCache = function () {
  22569. _super.prototype._initCache.call(this);
  22570. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22571. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22572. this._cache.mode = undefined;
  22573. this._cache.minZ = undefined;
  22574. this._cache.maxZ = undefined;
  22575. this._cache.fov = undefined;
  22576. this._cache.fovMode = undefined;
  22577. this._cache.aspectRatio = undefined;
  22578. this._cache.orthoLeft = undefined;
  22579. this._cache.orthoRight = undefined;
  22580. this._cache.orthoBottom = undefined;
  22581. this._cache.orthoTop = undefined;
  22582. this._cache.renderWidth = undefined;
  22583. this._cache.renderHeight = undefined;
  22584. };
  22585. /** @hidden */
  22586. Camera.prototype._updateCache = function (ignoreParentClass) {
  22587. if (!ignoreParentClass) {
  22588. _super.prototype._updateCache.call(this);
  22589. }
  22590. this._cache.position.copyFrom(this.position);
  22591. this._cache.upVector.copyFrom(this.upVector);
  22592. };
  22593. /** @hidden */
  22594. Camera.prototype._isSynchronized = function () {
  22595. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22596. };
  22597. /** @hidden */
  22598. Camera.prototype._isSynchronizedViewMatrix = function () {
  22599. if (!_super.prototype._isSynchronized.call(this))
  22600. return false;
  22601. return this._cache.position.equals(this.position)
  22602. && this._cache.upVector.equals(this.upVector)
  22603. && this.isSynchronizedWithParent();
  22604. };
  22605. /** @hidden */
  22606. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22607. var check = this._cache.mode === this.mode
  22608. && this._cache.minZ === this.minZ
  22609. && this._cache.maxZ === this.maxZ;
  22610. if (!check) {
  22611. return false;
  22612. }
  22613. var engine = this.getEngine();
  22614. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22615. check = this._cache.fov === this.fov
  22616. && this._cache.fovMode === this.fovMode
  22617. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22618. }
  22619. else {
  22620. check = this._cache.orthoLeft === this.orthoLeft
  22621. && this._cache.orthoRight === this.orthoRight
  22622. && this._cache.orthoBottom === this.orthoBottom
  22623. && this._cache.orthoTop === this.orthoTop
  22624. && this._cache.renderWidth === engine.getRenderWidth()
  22625. && this._cache.renderHeight === engine.getRenderHeight();
  22626. }
  22627. return check;
  22628. };
  22629. /**
  22630. * Attach the input controls to a specific dom element to get the input from.
  22631. * @param element Defines the element the controls should be listened from
  22632. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22633. */
  22634. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22635. };
  22636. /**
  22637. * Detach the current controls from the specified dom element.
  22638. * @param element Defines the element to stop listening the inputs from
  22639. */
  22640. Camera.prototype.detachControl = function (element) {
  22641. };
  22642. /**
  22643. * Update the camera state according to the different inputs gathered during the frame.
  22644. */
  22645. Camera.prototype.update = function () {
  22646. this._checkInputs();
  22647. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22648. this._updateRigCameras();
  22649. }
  22650. };
  22651. /** @hidden */
  22652. Camera.prototype._checkInputs = function () {
  22653. this.onAfterCheckInputsObservable.notifyObservers(this);
  22654. };
  22655. Object.defineProperty(Camera.prototype, "rigCameras", {
  22656. /** @hidden */
  22657. get: function () {
  22658. return this._rigCameras;
  22659. },
  22660. enumerable: true,
  22661. configurable: true
  22662. });
  22663. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22664. get: function () {
  22665. return this._rigPostProcess;
  22666. },
  22667. enumerable: true,
  22668. configurable: true
  22669. });
  22670. /**
  22671. * Internal, gets the first post proces.
  22672. * @returns the first post process to be run on this camera.
  22673. */
  22674. Camera.prototype._getFirstPostProcess = function () {
  22675. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22676. if (this._postProcesses[ppIndex] !== null) {
  22677. return this._postProcesses[ppIndex];
  22678. }
  22679. }
  22680. return null;
  22681. };
  22682. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22683. // invalidate framebuffer
  22684. var firstPostProcess = this._getFirstPostProcess();
  22685. if (firstPostProcess) {
  22686. firstPostProcess.markTextureDirty();
  22687. }
  22688. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22689. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22690. var cam = this._rigCameras[i];
  22691. var rigPostProcess = cam._rigPostProcess;
  22692. // for VR rig, there does not have to be a post process
  22693. if (rigPostProcess) {
  22694. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22695. if (isPass) {
  22696. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22697. cam.isIntermediate = this._postProcesses.length === 0;
  22698. }
  22699. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22700. rigPostProcess.markTextureDirty();
  22701. }
  22702. else {
  22703. cam._postProcesses = this._postProcesses.slice(0);
  22704. }
  22705. }
  22706. };
  22707. /**
  22708. * Attach a post process to the camera.
  22709. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22710. * @param postProcess The post process to attach to the camera
  22711. * @param insertAt The position of the post process in case several of them are in use in the scene
  22712. * @returns the position the post process has been inserted at
  22713. */
  22714. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22715. if (insertAt === void 0) { insertAt = null; }
  22716. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22717. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22718. return 0;
  22719. }
  22720. if (insertAt == null || insertAt < 0) {
  22721. this._postProcesses.push(postProcess);
  22722. }
  22723. else if (this._postProcesses[insertAt] === null) {
  22724. this._postProcesses[insertAt] = postProcess;
  22725. }
  22726. else {
  22727. this._postProcesses.splice(insertAt, 0, postProcess);
  22728. }
  22729. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22730. return this._postProcesses.indexOf(postProcess);
  22731. };
  22732. /**
  22733. * Detach a post process to the camera.
  22734. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22735. * @param postProcess The post process to detach from the camera
  22736. */
  22737. Camera.prototype.detachPostProcess = function (postProcess) {
  22738. var idx = this._postProcesses.indexOf(postProcess);
  22739. if (idx !== -1) {
  22740. this._postProcesses[idx] = null;
  22741. }
  22742. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22743. };
  22744. /**
  22745. * Gets the current world matrix of the camera
  22746. */
  22747. Camera.prototype.getWorldMatrix = function () {
  22748. if (this._isSynchronizedViewMatrix()) {
  22749. return this._worldMatrix;
  22750. }
  22751. // Getting the the view matrix will also compute the world matrix.
  22752. this.getViewMatrix();
  22753. return this._worldMatrix;
  22754. };
  22755. /** @hidden */
  22756. Camera.prototype._getViewMatrix = function () {
  22757. return BABYLON.Matrix.Identity();
  22758. };
  22759. /**
  22760. * Gets the current view matrix of the camera.
  22761. * @param force forces the camera to recompute the matrix without looking at the cached state
  22762. * @returns the view matrix
  22763. */
  22764. Camera.prototype.getViewMatrix = function (force) {
  22765. if (!force && this._isSynchronizedViewMatrix()) {
  22766. return this._computedViewMatrix;
  22767. }
  22768. this.updateCache();
  22769. this._computedViewMatrix = this._getViewMatrix();
  22770. this._currentRenderId = this.getScene().getRenderId();
  22771. this._childRenderId = this._currentRenderId;
  22772. this._refreshFrustumPlanes = true;
  22773. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22774. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22775. }
  22776. this.onViewMatrixChangedObservable.notifyObservers(this);
  22777. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22778. return this._computedViewMatrix;
  22779. };
  22780. /**
  22781. * Freeze the projection matrix.
  22782. * It will prevent the cache check of the camera projection compute and can speed up perf
  22783. * if no parameter of the camera are meant to change
  22784. * @param projection Defines manually a projection if necessary
  22785. */
  22786. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22787. this._doNotComputeProjectionMatrix = true;
  22788. if (projection !== undefined) {
  22789. this._projectionMatrix = projection;
  22790. }
  22791. };
  22792. ;
  22793. /**
  22794. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22795. */
  22796. Camera.prototype.unfreezeProjectionMatrix = function () {
  22797. this._doNotComputeProjectionMatrix = false;
  22798. };
  22799. ;
  22800. /**
  22801. * Gets the current projection matrix of the camera.
  22802. * @param force forces the camera to recompute the matrix without looking at the cached state
  22803. * @returns the projection matrix
  22804. */
  22805. Camera.prototype.getProjectionMatrix = function (force) {
  22806. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22807. return this._projectionMatrix;
  22808. }
  22809. // Cache
  22810. this._cache.mode = this.mode;
  22811. this._cache.minZ = this.minZ;
  22812. this._cache.maxZ = this.maxZ;
  22813. // Matrix
  22814. this._refreshFrustumPlanes = true;
  22815. var engine = this.getEngine();
  22816. var scene = this.getScene();
  22817. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22818. this._cache.fov = this.fov;
  22819. this._cache.fovMode = this.fovMode;
  22820. this._cache.aspectRatio = engine.getAspectRatio(this);
  22821. if (this.minZ <= 0) {
  22822. this.minZ = 0.1;
  22823. }
  22824. if (scene.useRightHandedSystem) {
  22825. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22826. }
  22827. else {
  22828. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22829. }
  22830. }
  22831. else {
  22832. var halfWidth = engine.getRenderWidth() / 2.0;
  22833. var halfHeight = engine.getRenderHeight() / 2.0;
  22834. if (scene.useRightHandedSystem) {
  22835. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22836. }
  22837. else {
  22838. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22839. }
  22840. this._cache.orthoLeft = this.orthoLeft;
  22841. this._cache.orthoRight = this.orthoRight;
  22842. this._cache.orthoBottom = this.orthoBottom;
  22843. this._cache.orthoTop = this.orthoTop;
  22844. this._cache.renderWidth = engine.getRenderWidth();
  22845. this._cache.renderHeight = engine.getRenderHeight();
  22846. }
  22847. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22848. return this._projectionMatrix;
  22849. };
  22850. /**
  22851. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22852. * @returns a Matrix
  22853. */
  22854. Camera.prototype.getTransformationMatrix = function () {
  22855. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22856. return this._transformMatrix;
  22857. };
  22858. Camera.prototype._updateFrustumPlanes = function () {
  22859. if (!this._refreshFrustumPlanes) {
  22860. return;
  22861. }
  22862. this.getTransformationMatrix();
  22863. if (!this._frustumPlanes) {
  22864. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22865. }
  22866. else {
  22867. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22868. }
  22869. this._refreshFrustumPlanes = false;
  22870. };
  22871. /**
  22872. * Checks if a cullable object (mesh...) is in the camera frustum
  22873. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22874. * @param target The object to check
  22875. * @returns true if the object is in frustum otherwise false
  22876. */
  22877. Camera.prototype.isInFrustum = function (target) {
  22878. this._updateFrustumPlanes();
  22879. return target.isInFrustum(this._frustumPlanes);
  22880. };
  22881. /**
  22882. * Checks if a cullable object (mesh...) is in the camera frustum
  22883. * Unlike isInFrustum this cheks the full bounding box
  22884. * @param target The object to check
  22885. * @returns true if the object is in frustum otherwise false
  22886. */
  22887. Camera.prototype.isCompletelyInFrustum = function (target) {
  22888. this._updateFrustumPlanes();
  22889. return target.isCompletelyInFrustum(this._frustumPlanes);
  22890. };
  22891. /**
  22892. * Gets a ray in the forward direction from the camera.
  22893. * @param length Defines the length of the ray to create
  22894. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22895. * @param origin Defines the start point of the ray which defaults to the camera position
  22896. * @returns the forward ray
  22897. */
  22898. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22899. if (length === void 0) { length = 100; }
  22900. if (!transform) {
  22901. transform = this.getWorldMatrix();
  22902. }
  22903. if (!origin) {
  22904. origin = this.position;
  22905. }
  22906. var forward = new BABYLON.Vector3(0, 0, 1);
  22907. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22908. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22909. return new BABYLON.Ray(origin, direction, length);
  22910. };
  22911. /**
  22912. * Releases resources associated with this node.
  22913. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22914. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22915. */
  22916. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22917. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22918. // Observables
  22919. this.onViewMatrixChangedObservable.clear();
  22920. this.onProjectionMatrixChangedObservable.clear();
  22921. this.onAfterCheckInputsObservable.clear();
  22922. this.onRestoreStateObservable.clear();
  22923. // Inputs
  22924. if (this.inputs) {
  22925. this.inputs.clear();
  22926. }
  22927. // Animations
  22928. this.getScene().stopAnimation(this);
  22929. // Remove from scene
  22930. this.getScene().removeCamera(this);
  22931. while (this._rigCameras.length > 0) {
  22932. var camera = this._rigCameras.pop();
  22933. if (camera) {
  22934. camera.dispose();
  22935. }
  22936. }
  22937. // Postprocesses
  22938. if (this._rigPostProcess) {
  22939. this._rigPostProcess.dispose(this);
  22940. this._rigPostProcess = null;
  22941. this._postProcesses = [];
  22942. }
  22943. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22944. this._rigPostProcess = null;
  22945. this._postProcesses = [];
  22946. }
  22947. else {
  22948. var i = this._postProcesses.length;
  22949. while (--i >= 0) {
  22950. var postProcess = this._postProcesses[i];
  22951. if (postProcess) {
  22952. postProcess.dispose(this);
  22953. }
  22954. }
  22955. }
  22956. // Render targets
  22957. var i = this.customRenderTargets.length;
  22958. while (--i >= 0) {
  22959. this.customRenderTargets[i].dispose();
  22960. }
  22961. this.customRenderTargets = [];
  22962. // Active Meshes
  22963. this._activeMeshes.dispose();
  22964. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22965. };
  22966. Object.defineProperty(Camera.prototype, "leftCamera", {
  22967. /**
  22968. * Gets the left camera of a rig setup in case of Rigged Camera
  22969. */
  22970. get: function () {
  22971. if (this._rigCameras.length < 1) {
  22972. return null;
  22973. }
  22974. return this._rigCameras[0];
  22975. },
  22976. enumerable: true,
  22977. configurable: true
  22978. });
  22979. Object.defineProperty(Camera.prototype, "rightCamera", {
  22980. /**
  22981. * Gets the right camera of a rig setup in case of Rigged Camera
  22982. */
  22983. get: function () {
  22984. if (this._rigCameras.length < 2) {
  22985. return null;
  22986. }
  22987. return this._rigCameras[1];
  22988. },
  22989. enumerable: true,
  22990. configurable: true
  22991. });
  22992. /**
  22993. * Gets the left camera target of a rig setup in case of Rigged Camera
  22994. * @returns the target position
  22995. */
  22996. Camera.prototype.getLeftTarget = function () {
  22997. if (this._rigCameras.length < 1) {
  22998. return null;
  22999. }
  23000. return this._rigCameras[0].getTarget();
  23001. };
  23002. /**
  23003. * Gets the right camera target of a rig setup in case of Rigged Camera
  23004. * @returns the target position
  23005. */
  23006. Camera.prototype.getRightTarget = function () {
  23007. if (this._rigCameras.length < 2) {
  23008. return null;
  23009. }
  23010. return this._rigCameras[1].getTarget();
  23011. };
  23012. /**
  23013. * @hidden
  23014. */
  23015. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23016. if (this.cameraRigMode === mode) {
  23017. return;
  23018. }
  23019. while (this._rigCameras.length > 0) {
  23020. var camera = this._rigCameras.pop();
  23021. if (camera) {
  23022. camera.dispose();
  23023. }
  23024. }
  23025. this.cameraRigMode = mode;
  23026. this._cameraRigParams = {};
  23027. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23028. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23029. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23030. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23031. // create the rig cameras, unless none
  23032. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23033. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23034. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23035. if (leftCamera && rightCamera) {
  23036. this._rigCameras.push(leftCamera);
  23037. this._rigCameras.push(rightCamera);
  23038. }
  23039. }
  23040. switch (this.cameraRigMode) {
  23041. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23042. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23043. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23044. break;
  23045. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23046. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23047. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23048. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23049. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23050. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23051. break;
  23052. case Camera.RIG_MODE_VR:
  23053. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23054. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23055. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23056. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23057. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23058. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23059. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23060. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23061. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23062. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23063. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23064. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23065. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23066. if (metrics.compensateDistortion) {
  23067. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23068. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23069. }
  23070. break;
  23071. case Camera.RIG_MODE_WEBVR:
  23072. if (rigParams.vrDisplay) {
  23073. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23074. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23075. //Left eye
  23076. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23077. this._rigCameras[0].setCameraRigParameter("left", true);
  23078. //leaving this for future reference
  23079. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23080. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23081. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23082. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23083. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23084. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23085. this._rigCameras[0].parent = this;
  23086. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23087. //Right eye
  23088. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23089. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23090. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23091. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23092. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23093. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23094. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23095. this._rigCameras[1].parent = this;
  23096. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23097. if (Camera.UseAlternateWebVRRendering) {
  23098. this._rigCameras[1]._skipRendering = true;
  23099. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23100. }
  23101. }
  23102. break;
  23103. }
  23104. this._cascadePostProcessesToRigCams();
  23105. this.update();
  23106. };
  23107. Camera.prototype._getVRProjectionMatrix = function () {
  23108. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23109. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23110. return this._projectionMatrix;
  23111. };
  23112. Camera.prototype._updateCameraRotationMatrix = function () {
  23113. //Here for WebVR
  23114. };
  23115. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23116. //Here for WebVR
  23117. };
  23118. /**
  23119. * This function MUST be overwritten by the different WebVR cameras available.
  23120. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23121. */
  23122. Camera.prototype._getWebVRProjectionMatrix = function () {
  23123. return BABYLON.Matrix.Identity();
  23124. };
  23125. /**
  23126. * This function MUST be overwritten by the different WebVR cameras available.
  23127. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23128. */
  23129. Camera.prototype._getWebVRViewMatrix = function () {
  23130. return BABYLON.Matrix.Identity();
  23131. };
  23132. /** @hidden */
  23133. Camera.prototype.setCameraRigParameter = function (name, value) {
  23134. if (!this._cameraRigParams) {
  23135. this._cameraRigParams = {};
  23136. }
  23137. this._cameraRigParams[name] = value;
  23138. //provisionnally:
  23139. if (name === "interaxialDistance") {
  23140. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23141. }
  23142. };
  23143. /**
  23144. * needs to be overridden by children so sub has required properties to be copied
  23145. * @hidden
  23146. */
  23147. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23148. return null;
  23149. };
  23150. /**
  23151. * May need to be overridden by children
  23152. * @hidden
  23153. */
  23154. Camera.prototype._updateRigCameras = function () {
  23155. for (var i = 0; i < this._rigCameras.length; i++) {
  23156. this._rigCameras[i].minZ = this.minZ;
  23157. this._rigCameras[i].maxZ = this.maxZ;
  23158. this._rigCameras[i].fov = this.fov;
  23159. }
  23160. // only update viewport when ANAGLYPH
  23161. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23162. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23163. }
  23164. };
  23165. /** @hidden */
  23166. Camera.prototype._setupInputs = function () {
  23167. };
  23168. /**
  23169. * Serialiaze the camera setup to a json represention
  23170. * @returns the JSON representation
  23171. */
  23172. Camera.prototype.serialize = function () {
  23173. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23174. // Type
  23175. serializationObject.type = this.getClassName();
  23176. // Parent
  23177. if (this.parent) {
  23178. serializationObject.parentId = this.parent.id;
  23179. }
  23180. if (this.inputs) {
  23181. this.inputs.serialize(serializationObject);
  23182. }
  23183. // Animations
  23184. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23185. serializationObject.ranges = this.serializeAnimationRanges();
  23186. return serializationObject;
  23187. };
  23188. /**
  23189. * Clones the current camera.
  23190. * @param name The cloned camera name
  23191. * @returns the cloned camera
  23192. */
  23193. Camera.prototype.clone = function (name) {
  23194. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23195. };
  23196. /**
  23197. * Gets the direction of the camera relative to a given local axis.
  23198. * @param localAxis Defines the reference axis to provide a relative direction.
  23199. * @return the direction
  23200. */
  23201. Camera.prototype.getDirection = function (localAxis) {
  23202. var result = BABYLON.Vector3.Zero();
  23203. this.getDirectionToRef(localAxis, result);
  23204. return result;
  23205. };
  23206. /**
  23207. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23208. * @param localAxis Defines the reference axis to provide a relative direction.
  23209. * @param result Defines the vector to store the result in
  23210. */
  23211. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23212. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23213. };
  23214. /**
  23215. * Gets a camera constructor for a given camera type
  23216. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23217. * @param name The name of the camera the result will be able to instantiate
  23218. * @param scene The scene the result will construct the camera in
  23219. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23220. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23221. * @returns a factory method to construc the camera
  23222. */
  23223. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23224. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23225. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23226. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23227. interaxial_distance: interaxial_distance,
  23228. isStereoscopicSideBySide: isStereoscopicSideBySide
  23229. });
  23230. if (constructorFunc) {
  23231. return constructorFunc;
  23232. }
  23233. // Default to universal camera
  23234. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23235. };
  23236. /**
  23237. * Compute the world matrix of the camera.
  23238. * @returns the camera workd matrix
  23239. */
  23240. Camera.prototype.computeWorldMatrix = function () {
  23241. return this.getWorldMatrix();
  23242. };
  23243. /**
  23244. * Parse a JSON and creates the camera from the parsed information
  23245. * @param parsedCamera The JSON to parse
  23246. * @param scene The scene to instantiate the camera in
  23247. * @returns the newly constructed camera
  23248. */
  23249. Camera.Parse = function (parsedCamera, scene) {
  23250. var type = parsedCamera.type;
  23251. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23252. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23253. // Parent
  23254. if (parsedCamera.parentId) {
  23255. camera._waitingParentId = parsedCamera.parentId;
  23256. }
  23257. //If camera has an input manager, let it parse inputs settings
  23258. if (camera.inputs) {
  23259. camera.inputs.parse(parsedCamera);
  23260. camera._setupInputs();
  23261. }
  23262. if (camera.setPosition) { // need to force position
  23263. camera.position.copyFromFloats(0, 0, 0);
  23264. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23265. }
  23266. // Target
  23267. if (parsedCamera.target) {
  23268. if (camera.setTarget) {
  23269. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23270. }
  23271. }
  23272. // Apply 3d rig, when found
  23273. if (parsedCamera.cameraRigMode) {
  23274. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23275. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23276. }
  23277. // Animations
  23278. if (parsedCamera.animations) {
  23279. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23280. var parsedAnimation = parsedCamera.animations[animationIndex];
  23281. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23282. }
  23283. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23284. }
  23285. if (parsedCamera.autoAnimate) {
  23286. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23287. }
  23288. return camera;
  23289. };
  23290. /**
  23291. * This is the default projection mode used by the cameras.
  23292. * It helps recreating a feeling of perspective and better appreciate depth.
  23293. * This is the best way to simulate real life cameras.
  23294. */
  23295. Camera.PERSPECTIVE_CAMERA = 0;
  23296. /**
  23297. * This helps creating camera with an orthographic mode.
  23298. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23299. */
  23300. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23301. /**
  23302. * This is the default FOV mode for perspective cameras.
  23303. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23304. */
  23305. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23306. /**
  23307. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23308. */
  23309. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23310. /**
  23311. * This specifies ther is no need for a camera rig.
  23312. * Basically only one eye is rendered corresponding to the camera.
  23313. */
  23314. Camera.RIG_MODE_NONE = 0;
  23315. /**
  23316. * Simulates a camera Rig with one blue eye and one red eye.
  23317. * This can be use with 3d blue and red glasses.
  23318. */
  23319. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23320. /**
  23321. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23322. */
  23323. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23324. /**
  23325. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23326. */
  23327. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23328. /**
  23329. * Defines that both eyes of the camera will be rendered over under each other.
  23330. */
  23331. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23332. /**
  23333. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23334. */
  23335. Camera.RIG_MODE_VR = 20;
  23336. /**
  23337. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23338. */
  23339. Camera.RIG_MODE_WEBVR = 21;
  23340. /**
  23341. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23342. */
  23343. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23344. /**
  23345. * @hidden
  23346. * Might be removed once multiview will be a thing
  23347. */
  23348. Camera.UseAlternateWebVRRendering = false;
  23349. __decorate([
  23350. BABYLON.serializeAsVector3()
  23351. ], Camera.prototype, "position", void 0);
  23352. __decorate([
  23353. BABYLON.serializeAsVector3()
  23354. ], Camera.prototype, "upVector", void 0);
  23355. __decorate([
  23356. BABYLON.serialize()
  23357. ], Camera.prototype, "orthoLeft", void 0);
  23358. __decorate([
  23359. BABYLON.serialize()
  23360. ], Camera.prototype, "orthoRight", void 0);
  23361. __decorate([
  23362. BABYLON.serialize()
  23363. ], Camera.prototype, "orthoBottom", void 0);
  23364. __decorate([
  23365. BABYLON.serialize()
  23366. ], Camera.prototype, "orthoTop", void 0);
  23367. __decorate([
  23368. BABYLON.serialize()
  23369. ], Camera.prototype, "fov", void 0);
  23370. __decorate([
  23371. BABYLON.serialize()
  23372. ], Camera.prototype, "minZ", void 0);
  23373. __decorate([
  23374. BABYLON.serialize()
  23375. ], Camera.prototype, "maxZ", void 0);
  23376. __decorate([
  23377. BABYLON.serialize()
  23378. ], Camera.prototype, "inertia", void 0);
  23379. __decorate([
  23380. BABYLON.serialize()
  23381. ], Camera.prototype, "mode", void 0);
  23382. __decorate([
  23383. BABYLON.serialize()
  23384. ], Camera.prototype, "layerMask", void 0);
  23385. __decorate([
  23386. BABYLON.serialize()
  23387. ], Camera.prototype, "fovMode", void 0);
  23388. __decorate([
  23389. BABYLON.serialize()
  23390. ], Camera.prototype, "cameraRigMode", void 0);
  23391. __decorate([
  23392. BABYLON.serialize()
  23393. ], Camera.prototype, "interaxialDistance", void 0);
  23394. __decorate([
  23395. BABYLON.serialize()
  23396. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23397. return Camera;
  23398. }(BABYLON.Node));
  23399. BABYLON.Camera = Camera;
  23400. })(BABYLON || (BABYLON = {}));
  23401. //# sourceMappingURL=babylon.camera.js.map
  23402. var BABYLON;
  23403. (function (BABYLON) {
  23404. /**
  23405. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23406. * It is enable to manage the different groups as well as the different necessary sort functions.
  23407. * This should not be used directly aside of the few static configurations
  23408. */
  23409. var RenderingManager = /** @class */ (function () {
  23410. /**
  23411. * Instantiates a new rendering group for a particular scene
  23412. * @param scene Defines the scene the groups belongs to
  23413. */
  23414. function RenderingManager(scene) {
  23415. /**
  23416. * @hidden
  23417. */
  23418. this._useSceneAutoClearSetup = false;
  23419. this._renderingGroups = new Array();
  23420. this._autoClearDepthStencil = {};
  23421. this._customOpaqueSortCompareFn = {};
  23422. this._customAlphaTestSortCompareFn = {};
  23423. this._customTransparentSortCompareFn = {};
  23424. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23425. this._scene = scene;
  23426. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23427. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23428. }
  23429. }
  23430. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23431. if (depth === void 0) { depth = true; }
  23432. if (stencil === void 0) { stencil = true; }
  23433. if (this._depthStencilBufferAlreadyCleaned) {
  23434. return;
  23435. }
  23436. this._scene.getEngine().clear(null, false, depth, stencil);
  23437. this._depthStencilBufferAlreadyCleaned = true;
  23438. };
  23439. /**
  23440. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23441. * @hidden
  23442. */
  23443. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23444. // Update the observable context (not null as it only goes away on dispose)
  23445. var info = this._renderingGroupInfo;
  23446. info.scene = this._scene;
  23447. info.camera = this._scene.activeCamera;
  23448. // Dispatch sprites
  23449. if (this._scene.spriteManagers && renderSprites) {
  23450. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23451. var manager = this._scene.spriteManagers[index];
  23452. this.dispatchSprites(manager);
  23453. }
  23454. }
  23455. // Render
  23456. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23457. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23458. var renderingGroup = this._renderingGroups[index];
  23459. if (!renderingGroup)
  23460. continue;
  23461. var renderingGroupMask = Math.pow(2, index);
  23462. info.renderingGroupId = index;
  23463. // Before Observable
  23464. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23465. // Clear depth/stencil if needed
  23466. if (RenderingManager.AUTOCLEAR) {
  23467. var autoClear = this._useSceneAutoClearSetup ?
  23468. this._scene.getAutoClearDepthStencilSetup(index) :
  23469. this._autoClearDepthStencil[index];
  23470. if (autoClear && autoClear.autoClear) {
  23471. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23472. }
  23473. }
  23474. // Render
  23475. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23476. var step = _a[_i];
  23477. step.action(index);
  23478. }
  23479. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23480. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23481. var step = _c[_b];
  23482. step.action(index);
  23483. }
  23484. // After Observable
  23485. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23486. }
  23487. };
  23488. /**
  23489. * Resets the different information of the group to prepare a new frame
  23490. * @hidden
  23491. */
  23492. RenderingManager.prototype.reset = function () {
  23493. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23494. var renderingGroup = this._renderingGroups[index];
  23495. if (renderingGroup) {
  23496. renderingGroup.prepare();
  23497. }
  23498. }
  23499. };
  23500. /**
  23501. * Dispose and release the group and its associated resources.
  23502. * @hidden
  23503. */
  23504. RenderingManager.prototype.dispose = function () {
  23505. this.freeRenderingGroups();
  23506. this._renderingGroups.length = 0;
  23507. this._renderingGroupInfo = null;
  23508. };
  23509. /**
  23510. * Clear the info related to rendering groups preventing retention points during dispose.
  23511. */
  23512. RenderingManager.prototype.freeRenderingGroups = function () {
  23513. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23514. var renderingGroup = this._renderingGroups[index];
  23515. if (renderingGroup) {
  23516. renderingGroup.dispose();
  23517. }
  23518. }
  23519. };
  23520. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23521. if (this._renderingGroups[renderingGroupId] === undefined) {
  23522. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23523. }
  23524. };
  23525. /**
  23526. * Add a sprite manager to the rendering manager in order to render it this frame.
  23527. * @param spriteManager Define the sprite manager to render
  23528. */
  23529. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23530. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23531. this._prepareRenderingGroup(renderingGroupId);
  23532. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23533. };
  23534. /**
  23535. * Add a particle system to the rendering manager in order to render it this frame.
  23536. * @param particleSystem Define the particle system to render
  23537. */
  23538. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23539. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23540. this._prepareRenderingGroup(renderingGroupId);
  23541. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23542. };
  23543. /**
  23544. * Add a submesh to the manager in order to render it this frame
  23545. * @param subMesh The submesh to dispatch
  23546. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23547. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23548. */
  23549. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23550. if (mesh === undefined) {
  23551. mesh = subMesh.getMesh();
  23552. }
  23553. var renderingGroupId = mesh.renderingGroupId || 0;
  23554. this._prepareRenderingGroup(renderingGroupId);
  23555. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23556. };
  23557. /**
  23558. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23559. * This allowed control for front to back rendering or reversly depending of the special needs.
  23560. *
  23561. * @param renderingGroupId The rendering group id corresponding to its index
  23562. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23563. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23564. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23565. */
  23566. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23567. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23568. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23569. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23570. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23571. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23572. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23573. if (this._renderingGroups[renderingGroupId]) {
  23574. var group = this._renderingGroups[renderingGroupId];
  23575. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23576. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23577. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23578. }
  23579. };
  23580. /**
  23581. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23582. *
  23583. * @param renderingGroupId The rendering group id corresponding to its index
  23584. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23585. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23586. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23587. */
  23588. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23589. if (depth === void 0) { depth = true; }
  23590. if (stencil === void 0) { stencil = true; }
  23591. this._autoClearDepthStencil[renderingGroupId] = {
  23592. autoClear: autoClearDepthStencil,
  23593. depth: depth,
  23594. stencil: stencil
  23595. };
  23596. };
  23597. /**
  23598. * Gets the current auto clear configuration for one rendering group of the rendering
  23599. * manager.
  23600. * @param index the rendering group index to get the information for
  23601. * @returns The auto clear setup for the requested rendering group
  23602. */
  23603. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23604. return this._autoClearDepthStencil[index];
  23605. };
  23606. /**
  23607. * The max id used for rendering groups (not included)
  23608. */
  23609. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23610. /**
  23611. * The min id used for rendering groups (included)
  23612. */
  23613. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23614. /**
  23615. * Used to globally prevent autoclearing scenes.
  23616. */
  23617. RenderingManager.AUTOCLEAR = true;
  23618. return RenderingManager;
  23619. }());
  23620. BABYLON.RenderingManager = RenderingManager;
  23621. })(BABYLON || (BABYLON = {}));
  23622. //# sourceMappingURL=babylon.renderingManager.js.map
  23623. var BABYLON;
  23624. (function (BABYLON) {
  23625. /**
  23626. * This represents the object necessary to create a rendering group.
  23627. * This is exclusively used and created by the rendering manager.
  23628. * To modify the behavior, you use the available helpers in your scene or meshes.
  23629. * @hidden
  23630. */
  23631. var RenderingGroup = /** @class */ (function () {
  23632. /**
  23633. * Creates a new rendering group.
  23634. * @param index The rendering group index
  23635. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23636. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23637. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23638. */
  23639. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23640. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23641. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23642. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23643. this.index = index;
  23644. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23645. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23646. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23647. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23648. this._particleSystems = new BABYLON.SmartArray(256);
  23649. this._spriteManagers = new BABYLON.SmartArray(256);
  23650. this._edgesRenderers = new BABYLON.SmartArray(16);
  23651. this._scene = scene;
  23652. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23653. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23654. this.transparentSortCompareFn = transparentSortCompareFn;
  23655. }
  23656. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23657. /**
  23658. * Set the opaque sort comparison function.
  23659. * If null the sub meshes will be render in the order they were created
  23660. */
  23661. set: function (value) {
  23662. this._opaqueSortCompareFn = value;
  23663. if (value) {
  23664. this._renderOpaque = this.renderOpaqueSorted;
  23665. }
  23666. else {
  23667. this._renderOpaque = RenderingGroup.renderUnsorted;
  23668. }
  23669. },
  23670. enumerable: true,
  23671. configurable: true
  23672. });
  23673. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23674. /**
  23675. * Set the alpha test sort comparison function.
  23676. * If null the sub meshes will be render in the order they were created
  23677. */
  23678. set: function (value) {
  23679. this._alphaTestSortCompareFn = value;
  23680. if (value) {
  23681. this._renderAlphaTest = this.renderAlphaTestSorted;
  23682. }
  23683. else {
  23684. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23685. }
  23686. },
  23687. enumerable: true,
  23688. configurable: true
  23689. });
  23690. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23691. /**
  23692. * Set the transparent sort comparison function.
  23693. * If null the sub meshes will be render in the order they were created
  23694. */
  23695. set: function (value) {
  23696. if (value) {
  23697. this._transparentSortCompareFn = value;
  23698. }
  23699. else {
  23700. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23701. }
  23702. this._renderTransparent = this.renderTransparentSorted;
  23703. },
  23704. enumerable: true,
  23705. configurable: true
  23706. });
  23707. /**
  23708. * Render all the sub meshes contained in the group.
  23709. * @param customRenderFunction Used to override the default render behaviour of the group.
  23710. * @returns true if rendered some submeshes.
  23711. */
  23712. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23713. if (customRenderFunction) {
  23714. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23715. return;
  23716. }
  23717. var engine = this._scene.getEngine();
  23718. // Depth only
  23719. if (this._depthOnlySubMeshes.length !== 0) {
  23720. engine.setColorWrite(false);
  23721. this._renderAlphaTest(this._depthOnlySubMeshes);
  23722. engine.setColorWrite(true);
  23723. }
  23724. // Opaque
  23725. if (this._opaqueSubMeshes.length !== 0) {
  23726. this._renderOpaque(this._opaqueSubMeshes);
  23727. }
  23728. // Alpha test
  23729. if (this._alphaTestSubMeshes.length !== 0) {
  23730. this._renderAlphaTest(this._alphaTestSubMeshes);
  23731. }
  23732. var stencilState = engine.getStencilBuffer();
  23733. engine.setStencilBuffer(false);
  23734. // Sprites
  23735. if (renderSprites) {
  23736. this._renderSprites();
  23737. }
  23738. // Particles
  23739. if (renderParticles) {
  23740. this._renderParticles(activeMeshes);
  23741. }
  23742. if (this.onBeforeTransparentRendering) {
  23743. this.onBeforeTransparentRendering();
  23744. }
  23745. // Transparent
  23746. if (this._transparentSubMeshes.length !== 0) {
  23747. this._renderTransparent(this._transparentSubMeshes);
  23748. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23749. }
  23750. // Set back stencil to false in case it changes before the edge renderer.
  23751. engine.setStencilBuffer(false);
  23752. // Edges
  23753. if (this._edgesRenderers.length) {
  23754. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23755. this._edgesRenderers.data[edgesRendererIndex].render();
  23756. }
  23757. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23758. }
  23759. // Restore Stencil state.
  23760. engine.setStencilBuffer(stencilState);
  23761. };
  23762. /**
  23763. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23764. * @param subMeshes The submeshes to render
  23765. */
  23766. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23767. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23768. };
  23769. /**
  23770. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23771. * @param subMeshes The submeshes to render
  23772. */
  23773. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23774. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23775. };
  23776. /**
  23777. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23778. * @param subMeshes The submeshes to render
  23779. */
  23780. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23781. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23782. };
  23783. /**
  23784. * Renders the submeshes in a specified order.
  23785. * @param subMeshes The submeshes to sort before render
  23786. * @param sortCompareFn The comparison function use to sort
  23787. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23788. * @param transparent Specifies to activate blending if true
  23789. */
  23790. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23791. var subIndex = 0;
  23792. var subMesh;
  23793. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23794. for (; subIndex < subMeshes.length; subIndex++) {
  23795. subMesh = subMeshes.data[subIndex];
  23796. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23797. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23798. }
  23799. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23800. if (sortCompareFn) {
  23801. sortedArray.sort(sortCompareFn);
  23802. }
  23803. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23804. subMesh = sortedArray[subIndex];
  23805. if (transparent) {
  23806. var material = subMesh.getMaterial();
  23807. if (material && material.needDepthPrePass) {
  23808. var engine = material.getScene().getEngine();
  23809. engine.setColorWrite(false);
  23810. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23811. subMesh.render(false);
  23812. engine.setColorWrite(true);
  23813. }
  23814. }
  23815. subMesh.render(transparent);
  23816. }
  23817. };
  23818. /**
  23819. * Renders the submeshes in the order they were dispatched (no sort applied).
  23820. * @param subMeshes The submeshes to render
  23821. */
  23822. RenderingGroup.renderUnsorted = function (subMeshes) {
  23823. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23824. var submesh = subMeshes.data[subIndex];
  23825. submesh.render(false);
  23826. }
  23827. };
  23828. /**
  23829. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23830. * are rendered back to front if in the same alpha index.
  23831. *
  23832. * @param a The first submesh
  23833. * @param b The second submesh
  23834. * @returns The result of the comparison
  23835. */
  23836. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23837. // Alpha index first
  23838. if (a._alphaIndex > b._alphaIndex) {
  23839. return 1;
  23840. }
  23841. if (a._alphaIndex < b._alphaIndex) {
  23842. return -1;
  23843. }
  23844. // Then distance to camera
  23845. return RenderingGroup.backToFrontSortCompare(a, b);
  23846. };
  23847. /**
  23848. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23849. * are rendered back to front.
  23850. *
  23851. * @param a The first submesh
  23852. * @param b The second submesh
  23853. * @returns The result of the comparison
  23854. */
  23855. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23856. // Then distance to camera
  23857. if (a._distanceToCamera < b._distanceToCamera) {
  23858. return 1;
  23859. }
  23860. if (a._distanceToCamera > b._distanceToCamera) {
  23861. return -1;
  23862. }
  23863. return 0;
  23864. };
  23865. /**
  23866. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23867. * are rendered front to back (prevent overdraw).
  23868. *
  23869. * @param a The first submesh
  23870. * @param b The second submesh
  23871. * @returns The result of the comparison
  23872. */
  23873. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23874. // Then distance to camera
  23875. if (a._distanceToCamera < b._distanceToCamera) {
  23876. return -1;
  23877. }
  23878. if (a._distanceToCamera > b._distanceToCamera) {
  23879. return 1;
  23880. }
  23881. return 0;
  23882. };
  23883. /**
  23884. * Resets the different lists of submeshes to prepare a new frame.
  23885. */
  23886. RenderingGroup.prototype.prepare = function () {
  23887. this._opaqueSubMeshes.reset();
  23888. this._transparentSubMeshes.reset();
  23889. this._alphaTestSubMeshes.reset();
  23890. this._depthOnlySubMeshes.reset();
  23891. this._particleSystems.reset();
  23892. this._spriteManagers.reset();
  23893. this._edgesRenderers.reset();
  23894. };
  23895. RenderingGroup.prototype.dispose = function () {
  23896. this._opaqueSubMeshes.dispose();
  23897. this._transparentSubMeshes.dispose();
  23898. this._alphaTestSubMeshes.dispose();
  23899. this._depthOnlySubMeshes.dispose();
  23900. this._particleSystems.dispose();
  23901. this._spriteManagers.dispose();
  23902. this._edgesRenderers.dispose();
  23903. };
  23904. /**
  23905. * Inserts the submesh in its correct queue depending on its material.
  23906. * @param subMesh The submesh to dispatch
  23907. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23908. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23909. */
  23910. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23911. // Get mesh and materials if not provided
  23912. if (mesh === undefined) {
  23913. mesh = subMesh.getMesh();
  23914. }
  23915. if (material === undefined) {
  23916. material = subMesh.getMaterial();
  23917. }
  23918. if (material === null || material === undefined) {
  23919. return;
  23920. }
  23921. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23922. this._transparentSubMeshes.push(subMesh);
  23923. }
  23924. else if (material.needAlphaTesting()) { // Alpha test
  23925. if (material.needDepthPrePass) {
  23926. this._depthOnlySubMeshes.push(subMesh);
  23927. }
  23928. this._alphaTestSubMeshes.push(subMesh);
  23929. }
  23930. else {
  23931. if (material.needDepthPrePass) {
  23932. this._depthOnlySubMeshes.push(subMesh);
  23933. }
  23934. this._opaqueSubMeshes.push(subMesh); // Opaque
  23935. }
  23936. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23937. this._edgesRenderers.push(mesh._edgesRenderer);
  23938. }
  23939. };
  23940. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23941. this._spriteManagers.push(spriteManager);
  23942. };
  23943. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23944. this._particleSystems.push(particleSystem);
  23945. };
  23946. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23947. if (this._particleSystems.length === 0) {
  23948. return;
  23949. }
  23950. // Particles
  23951. var activeCamera = this._scene.activeCamera;
  23952. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23953. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23954. var particleSystem = this._particleSystems.data[particleIndex];
  23955. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23956. continue;
  23957. }
  23958. var emitter = particleSystem.emitter;
  23959. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23960. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23961. }
  23962. }
  23963. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23964. };
  23965. RenderingGroup.prototype._renderSprites = function () {
  23966. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23967. return;
  23968. }
  23969. // Sprites
  23970. var activeCamera = this._scene.activeCamera;
  23971. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23972. for (var id = 0; id < this._spriteManagers.length; id++) {
  23973. var spriteManager = this._spriteManagers.data[id];
  23974. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23975. spriteManager.render();
  23976. }
  23977. }
  23978. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23979. };
  23980. return RenderingGroup;
  23981. }());
  23982. BABYLON.RenderingGroup = RenderingGroup;
  23983. })(BABYLON || (BABYLON = {}));
  23984. //# sourceMappingURL=babylon.renderingGroup.js.map
  23985. var BABYLON;
  23986. (function (BABYLON) {
  23987. /**
  23988. * Groups all the scene component constants in one place to ease maintenance.
  23989. * @hidden
  23990. */
  23991. var SceneComponentConstants = /** @class */ (function () {
  23992. function SceneComponentConstants() {
  23993. }
  23994. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23995. SceneComponentConstants.NAME_LAYER = "Layer";
  23996. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23997. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23998. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23999. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24000. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24001. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24002. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24003. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24004. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24005. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24006. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24007. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24008. SceneComponentConstants.NAME_OCTREE = "Octree";
  24009. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24010. SceneComponentConstants.NAME_AUDIO = "Audio";
  24011. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24012. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24013. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24014. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24015. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24016. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24017. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24018. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24019. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24020. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24021. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24022. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24023. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24024. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24025. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24026. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24027. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24028. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24029. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24030. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24031. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24032. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24033. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24034. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24035. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24036. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24037. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24038. return SceneComponentConstants;
  24039. }());
  24040. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24041. /**
  24042. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24043. * @hidden
  24044. */
  24045. var Stage = /** @class */ (function (_super) {
  24046. __extends(Stage, _super);
  24047. /**
  24048. * Hide ctor from the rest of the world.
  24049. * @param items The items to add.
  24050. */
  24051. function Stage(items) {
  24052. return _super.apply(this, items) || this;
  24053. }
  24054. /**
  24055. * Creates a new Stage.
  24056. * @returns A new instance of a Stage
  24057. */
  24058. Stage.Create = function () {
  24059. return Object.create(Stage.prototype);
  24060. };
  24061. /**
  24062. * Registers a step in an ordered way in the targeted stage.
  24063. * @param index Defines the position to register the step in
  24064. * @param component Defines the component attached to the step
  24065. * @param action Defines the action to launch during the step
  24066. */
  24067. Stage.prototype.registerStep = function (index, component, action) {
  24068. var i = 0;
  24069. var maxIndex = Number.MAX_VALUE;
  24070. for (; i < this.length && i < maxIndex; i++) {
  24071. var step = this[i];
  24072. maxIndex = step.index;
  24073. }
  24074. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24075. };
  24076. /**
  24077. * Clears all the steps from the stage.
  24078. */
  24079. Stage.prototype.clear = function () {
  24080. this.length = 0;
  24081. };
  24082. return Stage;
  24083. }(Array));
  24084. BABYLON.Stage = Stage;
  24085. })(BABYLON || (BABYLON = {}));
  24086. //# sourceMappingURL=babylon.sceneComponent.js.map
  24087. var BABYLON;
  24088. (function (BABYLON) {
  24089. /**
  24090. * Base class of the scene acting as a container for the different elements composing a scene.
  24091. * This class is dynamically extended by the different components of the scene increasing
  24092. * flexibility and reducing coupling
  24093. */
  24094. var AbstractScene = /** @class */ (function () {
  24095. function AbstractScene() {
  24096. /**
  24097. * Gets the list of root nodes (ie. nodes with no parent)
  24098. */
  24099. this.rootNodes = new Array();
  24100. /** All of the cameras added to this scene
  24101. * @see http://doc.babylonjs.com/babylon101/cameras
  24102. */
  24103. this.cameras = new Array();
  24104. /**
  24105. * All of the lights added to this scene
  24106. * @see http://doc.babylonjs.com/babylon101/lights
  24107. */
  24108. this.lights = new Array();
  24109. /**
  24110. * All of the (abstract) meshes added to this scene
  24111. */
  24112. this.meshes = new Array();
  24113. /**
  24114. * The list of skeletons added to the scene
  24115. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24116. */
  24117. this.skeletons = new Array();
  24118. /**
  24119. * All of the particle systems added to this scene
  24120. * @see http://doc.babylonjs.com/babylon101/particles
  24121. */
  24122. this.particleSystems = new Array();
  24123. /**
  24124. * Gets a list of Animations associated with the scene
  24125. */
  24126. this.animations = [];
  24127. /**
  24128. * All of the animation groups added to this scene
  24129. * @see http://doc.babylonjs.com/how_to/group
  24130. */
  24131. this.animationGroups = new Array();
  24132. /**
  24133. * All of the multi-materials added to this scene
  24134. * @see http://doc.babylonjs.com/how_to/multi_materials
  24135. */
  24136. this.multiMaterials = new Array();
  24137. /**
  24138. * All of the materials added to this scene
  24139. * @see http://doc.babylonjs.com/babylon101/materials
  24140. */
  24141. this.materials = new Array();
  24142. /**
  24143. * The list of morph target managers added to the scene
  24144. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24145. */
  24146. this.morphTargetManagers = new Array();
  24147. /**
  24148. * The list of geometries used in the scene.
  24149. */
  24150. this.geometries = new Array();
  24151. /**
  24152. * All of the tranform nodes added to this scene
  24153. * @see http://doc.babylonjs.com/how_to/transformnode
  24154. */
  24155. this.transformNodes = new Array();
  24156. /**
  24157. * ActionManagers available on the scene.
  24158. */
  24159. this.actionManagers = new Array();
  24160. /**
  24161. * Textures to keep.
  24162. */
  24163. this.textures = new Array();
  24164. }
  24165. /**
  24166. * Adds a parser in the list of available ones
  24167. * @param name Defines the name of the parser
  24168. * @param parser Defines the parser to add
  24169. */
  24170. AbstractScene.AddParser = function (name, parser) {
  24171. this._BabylonFileParsers[name] = parser;
  24172. };
  24173. /**
  24174. * Gets a general parser from the list of avaialble ones
  24175. * @param name Defines the name of the parser
  24176. * @returns the requested parser or null
  24177. */
  24178. AbstractScene.GetParser = function (name) {
  24179. if (this._BabylonFileParsers[name]) {
  24180. return this._BabylonFileParsers[name];
  24181. }
  24182. return null;
  24183. };
  24184. /**
  24185. * Adds n individual parser in the list of available ones
  24186. * @param name Defines the name of the parser
  24187. * @param parser Defines the parser to add
  24188. */
  24189. AbstractScene.AddIndividualParser = function (name, parser) {
  24190. this._IndividualBabylonFileParsers[name] = parser;
  24191. };
  24192. /**
  24193. * Gets an individual parser from the list of avaialble ones
  24194. * @param name Defines the name of the parser
  24195. * @returns the requested parser or null
  24196. */
  24197. AbstractScene.GetIndividualParser = function (name) {
  24198. if (this._IndividualBabylonFileParsers[name]) {
  24199. return this._IndividualBabylonFileParsers[name];
  24200. }
  24201. return null;
  24202. };
  24203. /**
  24204. * Parser json data and populate both a scene and its associated container object
  24205. * @param jsonData Defines the data to parse
  24206. * @param scene Defines the scene to parse the data for
  24207. * @param container Defines the container attached to the parsing sequence
  24208. * @param rootUrl Defines the root url of the data
  24209. */
  24210. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24211. for (var parserName in this._BabylonFileParsers) {
  24212. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24213. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24214. }
  24215. }
  24216. };
  24217. /**
  24218. * Stores the list of available parsers in the application.
  24219. */
  24220. AbstractScene._BabylonFileParsers = {};
  24221. /**
  24222. * Stores the list of available individual parsers in the application.
  24223. */
  24224. AbstractScene._IndividualBabylonFileParsers = {};
  24225. return AbstractScene;
  24226. }());
  24227. BABYLON.AbstractScene = AbstractScene;
  24228. })(BABYLON || (BABYLON = {}));
  24229. //# sourceMappingURL=babylon.abstractScene.js.map
  24230. var BABYLON;
  24231. (function (BABYLON) {
  24232. /** @hidden */
  24233. var ClickInfo = /** @class */ (function () {
  24234. function ClickInfo() {
  24235. this._singleClick = false;
  24236. this._doubleClick = false;
  24237. this._hasSwiped = false;
  24238. this._ignore = false;
  24239. }
  24240. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24241. get: function () {
  24242. return this._singleClick;
  24243. },
  24244. set: function (b) {
  24245. this._singleClick = b;
  24246. },
  24247. enumerable: true,
  24248. configurable: true
  24249. });
  24250. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24251. get: function () {
  24252. return this._doubleClick;
  24253. },
  24254. set: function (b) {
  24255. this._doubleClick = b;
  24256. },
  24257. enumerable: true,
  24258. configurable: true
  24259. });
  24260. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24261. get: function () {
  24262. return this._hasSwiped;
  24263. },
  24264. set: function (b) {
  24265. this._hasSwiped = b;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24271. get: function () {
  24272. return this._ignore;
  24273. },
  24274. set: function (b) {
  24275. this._ignore = b;
  24276. },
  24277. enumerable: true,
  24278. configurable: true
  24279. });
  24280. return ClickInfo;
  24281. }());
  24282. /**
  24283. * This class is used by the onRenderingGroupObservable
  24284. */
  24285. var RenderingGroupInfo = /** @class */ (function () {
  24286. function RenderingGroupInfo() {
  24287. }
  24288. return RenderingGroupInfo;
  24289. }());
  24290. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24291. /**
  24292. * Represents a scene to be rendered by the engine.
  24293. * @see http://doc.babylonjs.com/features/scene
  24294. */
  24295. var Scene = /** @class */ (function (_super) {
  24296. __extends(Scene, _super);
  24297. /**
  24298. * Creates a new Scene
  24299. * @param engine defines the engine to use to render this scene
  24300. */
  24301. function Scene(engine) {
  24302. var _this = _super.call(this) || this;
  24303. // Members
  24304. /**
  24305. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24306. */
  24307. _this.autoClear = true;
  24308. /**
  24309. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24310. */
  24311. _this.autoClearDepthAndStencil = true;
  24312. /**
  24313. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24314. */
  24315. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24316. /**
  24317. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24318. */
  24319. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24320. _this._forceWireframe = false;
  24321. _this._forcePointsCloud = false;
  24322. /**
  24323. * Gets or sets a boolean indicating if animations are enabled
  24324. */
  24325. _this.animationsEnabled = true;
  24326. _this._animationPropertiesOverride = null;
  24327. /**
  24328. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24329. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24330. */
  24331. _this.useConstantAnimationDeltaTime = false;
  24332. /**
  24333. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24334. * Please note that it requires to run a ray cast through the scene on every frame
  24335. */
  24336. _this.constantlyUpdateMeshUnderPointer = false;
  24337. /**
  24338. * Defines the HTML cursor to use when hovering over interactive elements
  24339. */
  24340. _this.hoverCursor = "pointer";
  24341. /**
  24342. * Defines the HTML default cursor to use (empty by default)
  24343. */
  24344. _this.defaultCursor = "";
  24345. /**
  24346. * This is used to call preventDefault() on pointer down
  24347. * in order to block unwanted artifacts like system double clicks
  24348. */
  24349. _this.preventDefaultOnPointerDown = true;
  24350. // Metadata
  24351. /**
  24352. * Gets or sets user defined metadata
  24353. */
  24354. _this.metadata = null;
  24355. /**
  24356. * Use this array to add regular expressions used to disable offline support for specific urls
  24357. */
  24358. _this.disableOfflineSupportExceptionRules = new Array();
  24359. /**
  24360. * An event triggered when the scene is disposed.
  24361. */
  24362. _this.onDisposeObservable = new BABYLON.Observable();
  24363. _this._onDisposeObserver = null;
  24364. /**
  24365. * An event triggered before rendering the scene (right after animations and physics)
  24366. */
  24367. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24368. _this._onBeforeRenderObserver = null;
  24369. /**
  24370. * An event triggered after rendering the scene
  24371. */
  24372. _this.onAfterRenderObservable = new BABYLON.Observable();
  24373. _this._onAfterRenderObserver = null;
  24374. /**
  24375. * An event triggered before animating the scene
  24376. */
  24377. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24378. /**
  24379. * An event triggered after animations processing
  24380. */
  24381. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24382. /**
  24383. * An event triggered before draw calls are ready to be sent
  24384. */
  24385. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24386. /**
  24387. * An event triggered after draw calls have been sent
  24388. */
  24389. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24390. /**
  24391. * An event triggered when the scene is ready
  24392. */
  24393. _this.onReadyObservable = new BABYLON.Observable();
  24394. /**
  24395. * An event triggered before rendering a camera
  24396. */
  24397. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24398. _this._onBeforeCameraRenderObserver = null;
  24399. /**
  24400. * An event triggered after rendering a camera
  24401. */
  24402. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24403. _this._onAfterCameraRenderObserver = null;
  24404. /**
  24405. * An event triggered when active meshes evaluation is about to start
  24406. */
  24407. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24408. /**
  24409. * An event triggered when active meshes evaluation is done
  24410. */
  24411. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24412. /**
  24413. * An event triggered when particles rendering is about to start
  24414. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24415. */
  24416. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24417. /**
  24418. * An event triggered when particles rendering is done
  24419. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24420. */
  24421. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24422. /**
  24423. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24424. */
  24425. _this.onDataLoadedObservable = new BABYLON.Observable();
  24426. /**
  24427. * An event triggered when a camera is created
  24428. */
  24429. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24430. /**
  24431. * An event triggered when a camera is removed
  24432. */
  24433. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24434. /**
  24435. * An event triggered when a light is created
  24436. */
  24437. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24438. /**
  24439. * An event triggered when a light is removed
  24440. */
  24441. _this.onLightRemovedObservable = new BABYLON.Observable();
  24442. /**
  24443. * An event triggered when a geometry is created
  24444. */
  24445. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24446. /**
  24447. * An event triggered when a geometry is removed
  24448. */
  24449. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24450. /**
  24451. * An event triggered when a transform node is created
  24452. */
  24453. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24454. /**
  24455. * An event triggered when a transform node is removed
  24456. */
  24457. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24458. /**
  24459. * An event triggered when a mesh is created
  24460. */
  24461. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24462. /**
  24463. * An event triggered when a mesh is removed
  24464. */
  24465. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24466. /**
  24467. * An event triggered when a material is created
  24468. */
  24469. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24470. /**
  24471. * An event triggered when a material is removed
  24472. */
  24473. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24474. /**
  24475. * An event triggered when a texture is created
  24476. */
  24477. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24478. /**
  24479. * An event triggered when a texture is removed
  24480. */
  24481. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24482. /**
  24483. * An event triggered when render targets are about to be rendered
  24484. * Can happen multiple times per frame.
  24485. */
  24486. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24487. /**
  24488. * An event triggered when render targets were rendered.
  24489. * Can happen multiple times per frame.
  24490. */
  24491. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24492. /**
  24493. * An event triggered before calculating deterministic simulation step
  24494. */
  24495. _this.onBeforeStepObservable = new BABYLON.Observable();
  24496. /**
  24497. * An event triggered after calculating deterministic simulation step
  24498. */
  24499. _this.onAfterStepObservable = new BABYLON.Observable();
  24500. /**
  24501. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24502. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24503. * 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)
  24504. */
  24505. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24506. /**
  24507. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24508. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24509. * 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)
  24510. */
  24511. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24512. /**
  24513. * This Observable will when a mesh has been imported into the scene.
  24514. */
  24515. _this.onMeshImportedObservable = new BABYLON.Observable();
  24516. // Animations
  24517. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24518. /**
  24519. * 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).
  24520. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24521. */
  24522. _this.onPrePointerObservable = new BABYLON.Observable();
  24523. /**
  24524. * Observable event triggered each time an input event is received from the rendering canvas
  24525. */
  24526. _this.onPointerObservable = new BABYLON.Observable();
  24527. _this._meshPickProceed = false;
  24528. _this._currentPickResult = null;
  24529. _this._previousPickResult = null;
  24530. _this._totalPointersPressed = 0;
  24531. _this._doubleClickOccured = false;
  24532. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24533. _this.cameraToUseForPointers = null;
  24534. _this._pointerX = 0;
  24535. _this._pointerY = 0;
  24536. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24537. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24538. _this._startingPointerTime = 0;
  24539. _this._previousStartingPointerTime = 0;
  24540. _this._pointerCaptures = {};
  24541. // Deterministic lockstep
  24542. _this._timeAccumulator = 0;
  24543. _this._currentStepId = 0;
  24544. _this._currentInternalStep = 0;
  24545. // Keyboard
  24546. /**
  24547. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24548. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24549. */
  24550. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24551. /**
  24552. * Observable event triggered each time an keyboard event is received from the hosting window
  24553. */
  24554. _this.onKeyboardObservable = new BABYLON.Observable();
  24555. // Coordinates system
  24556. _this._useRightHandedSystem = false;
  24557. // Fog
  24558. _this._fogEnabled = true;
  24559. _this._fogMode = Scene.FOGMODE_NONE;
  24560. /**
  24561. * Gets or sets the fog color to use
  24562. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24563. */
  24564. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24565. /**
  24566. * Gets or sets the fog density to use
  24567. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24568. */
  24569. _this.fogDensity = 0.1;
  24570. /**
  24571. * Gets or sets the fog start distance to use
  24572. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24573. */
  24574. _this.fogStart = 0;
  24575. /**
  24576. * Gets or sets the fog end distance to use
  24577. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24578. */
  24579. _this.fogEnd = 1000.0;
  24580. // Lights
  24581. _this._shadowsEnabled = true;
  24582. _this._lightsEnabled = true;
  24583. /** All of the active cameras added to this scene. */
  24584. _this.activeCameras = new Array();
  24585. // Textures
  24586. _this._texturesEnabled = true;
  24587. // Particles
  24588. /**
  24589. * Gets or sets a boolean indicating if particles are enabled on this scene
  24590. */
  24591. _this.particlesEnabled = true;
  24592. // Sprites
  24593. /**
  24594. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24595. */
  24596. _this.spritesEnabled = true;
  24597. // Skeletons
  24598. _this._skeletonsEnabled = true;
  24599. // Lens flares
  24600. /**
  24601. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24602. */
  24603. _this.lensFlaresEnabled = true;
  24604. // Collisions
  24605. /**
  24606. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24607. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24608. */
  24609. _this.collisionsEnabled = true;
  24610. /**
  24611. * Defines the gravity applied to this scene (used only for collisions)
  24612. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24613. */
  24614. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24615. // Postprocesses
  24616. /**
  24617. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24618. */
  24619. _this.postProcessesEnabled = true;
  24620. /**
  24621. * The list of postprocesses added to the scene
  24622. */
  24623. _this.postProcesses = new Array();
  24624. // Customs render targets
  24625. /**
  24626. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24627. */
  24628. _this.renderTargetsEnabled = true;
  24629. /**
  24630. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24631. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24632. */
  24633. _this.dumpNextRenderTargets = false;
  24634. /**
  24635. * The list of user defined render targets added to the scene
  24636. */
  24637. _this.customRenderTargets = new Array();
  24638. /**
  24639. * Gets the list of meshes imported to the scene through SceneLoader
  24640. */
  24641. _this.importedMeshesFiles = new Array();
  24642. // Probes
  24643. /**
  24644. * Gets or sets a boolean indicating if probes are enabled on this scene
  24645. */
  24646. _this.probesEnabled = true;
  24647. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24648. // Procedural textures
  24649. /**
  24650. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24651. */
  24652. _this.proceduralTexturesEnabled = true;
  24653. // Performance counters
  24654. _this._totalVertices = new BABYLON.PerfCounter();
  24655. /** @hidden */
  24656. _this._activeIndices = new BABYLON.PerfCounter();
  24657. /** @hidden */
  24658. _this._activeParticles = new BABYLON.PerfCounter();
  24659. /** @hidden */
  24660. _this._activeBones = new BABYLON.PerfCounter();
  24661. _this._animationTime = 0;
  24662. /**
  24663. * Gets or sets a general scale for animation speed
  24664. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24665. */
  24666. _this.animationTimeScale = 1;
  24667. _this._renderId = 0;
  24668. _this._frameId = 0;
  24669. _this._executeWhenReadyTimeoutId = -1;
  24670. _this._intermediateRendering = false;
  24671. _this._viewUpdateFlag = -1;
  24672. _this._projectionUpdateFlag = -1;
  24673. _this._alternateViewUpdateFlag = -1;
  24674. _this._alternateProjectionUpdateFlag = -1;
  24675. /** @hidden */
  24676. _this._toBeDisposed = new Array(256);
  24677. _this._activeRequests = new Array();
  24678. _this._pendingData = new Array();
  24679. _this._isDisposed = false;
  24680. /**
  24681. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24682. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24683. */
  24684. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24685. _this._activeMeshes = new BABYLON.SmartArray(256);
  24686. _this._processedMaterials = new BABYLON.SmartArray(256);
  24687. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24688. /** @hidden */
  24689. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24690. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24691. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24692. /** @hidden */
  24693. _this._activeAnimatables = new Array();
  24694. _this._transformMatrix = BABYLON.Matrix.Zero();
  24695. _this._useAlternateCameraConfiguration = false;
  24696. _this._alternateRendering = false;
  24697. /**
  24698. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24699. * This is useful if there are more lights that the maximum simulteanous authorized
  24700. */
  24701. _this.requireLightSorting = false;
  24702. /**
  24703. * @hidden
  24704. * Backing store of defined scene components.
  24705. */
  24706. _this._components = [];
  24707. /**
  24708. * @hidden
  24709. * Backing store of defined scene components.
  24710. */
  24711. _this._serializableComponents = [];
  24712. /**
  24713. * List of components to register on the next registration step.
  24714. */
  24715. _this._transientComponents = [];
  24716. /**
  24717. * @hidden
  24718. * Defines the actions happening before camera updates.
  24719. */
  24720. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24721. /**
  24722. * @hidden
  24723. * Defines the actions happening before clear the canvas.
  24724. */
  24725. _this._beforeClearStage = BABYLON.Stage.Create();
  24726. /**
  24727. * @hidden
  24728. * Defines the actions when collecting render targets for the frame.
  24729. */
  24730. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24731. /**
  24732. * @hidden
  24733. * Defines the actions happening for one camera in the frame.
  24734. */
  24735. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24736. /**
  24737. * @hidden
  24738. * Defines the actions happening during the per mesh ready checks.
  24739. */
  24740. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24741. /**
  24742. * @hidden
  24743. * Defines the actions happening before evaluate active mesh checks.
  24744. */
  24745. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24746. /**
  24747. * @hidden
  24748. * Defines the actions happening during the evaluate sub mesh checks.
  24749. */
  24750. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24751. /**
  24752. * @hidden
  24753. * Defines the actions happening during the active mesh stage.
  24754. */
  24755. _this._activeMeshStage = BABYLON.Stage.Create();
  24756. /**
  24757. * @hidden
  24758. * Defines the actions happening during the per camera render target step.
  24759. */
  24760. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24761. /**
  24762. * @hidden
  24763. * Defines the actions happening just before the active camera is drawing.
  24764. */
  24765. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24766. /**
  24767. * @hidden
  24768. * Defines the actions happening just before a rendering group is drawing.
  24769. */
  24770. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24771. /**
  24772. * @hidden
  24773. * Defines the actions happening just before a mesh is drawing.
  24774. */
  24775. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24776. /**
  24777. * @hidden
  24778. * Defines the actions happening just after a mesh has been drawn.
  24779. */
  24780. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24781. /**
  24782. * @hidden
  24783. * Defines the actions happening just after a rendering group has been drawn.
  24784. */
  24785. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24786. /**
  24787. * @hidden
  24788. * Defines the actions happening just after the active camera has been drawn.
  24789. */
  24790. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24791. /**
  24792. * @hidden
  24793. * Defines the actions happening just after rendering all cameras and computing intersections.
  24794. */
  24795. _this._afterRenderStage = BABYLON.Stage.Create();
  24796. /**
  24797. * @hidden
  24798. * Defines the actions happening when a pointer move event happens.
  24799. */
  24800. _this._pointerMoveStage = BABYLON.Stage.Create();
  24801. /**
  24802. * @hidden
  24803. * Defines the actions happening when a pointer down event happens.
  24804. */
  24805. _this._pointerDownStage = BABYLON.Stage.Create();
  24806. /**
  24807. * @hidden
  24808. * Defines the actions happening when a pointer up event happens.
  24809. */
  24810. _this._pointerUpStage = BABYLON.Stage.Create();
  24811. _this._defaultMeshCandidates = {
  24812. data: [],
  24813. length: 0
  24814. };
  24815. _this._defaultSubMeshCandidates = {
  24816. data: [],
  24817. length: 0
  24818. };
  24819. _this._activeMeshesFrozen = false;
  24820. /** @hidden */
  24821. _this._allowPostProcessClearColor = true;
  24822. /**
  24823. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24824. */
  24825. _this.getDeterministicFrameTime = function () {
  24826. return 1000.0 / 60.0; // frame time in ms
  24827. };
  24828. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24829. _this._blockMaterialDirtyMechanism = false;
  24830. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24831. _this._engine.scenes.push(_this);
  24832. _this._uid = null;
  24833. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24834. if (BABYLON.PostProcessManager) {
  24835. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24836. }
  24837. if (BABYLON.Tools.IsWindowObjectExist()) {
  24838. _this.attachControl();
  24839. }
  24840. //collision coordinator initialization. For now legacy per default.
  24841. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24842. // Uniform Buffer
  24843. _this._createUbo();
  24844. // Default Image processing definition
  24845. if (BABYLON.ImageProcessingConfiguration) {
  24846. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24847. }
  24848. _this.setDefaultCandidateProviders();
  24849. return _this;
  24850. }
  24851. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24852. /**
  24853. * Texture used in all pbr material as the reflection texture.
  24854. * As in the majority of the scene they are the same (exception for multi room and so on),
  24855. * this is easier to reference from here than from all the materials.
  24856. */
  24857. get: function () {
  24858. return this._environmentTexture;
  24859. },
  24860. /**
  24861. * Texture used in all pbr material as the reflection texture.
  24862. * As in the majority of the scene they are the same (exception for multi room and so on),
  24863. * this is easier to set here than in all the materials.
  24864. */
  24865. set: function (value) {
  24866. if (this._environmentTexture === value) {
  24867. return;
  24868. }
  24869. this._environmentTexture = value;
  24870. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24871. },
  24872. enumerable: true,
  24873. configurable: true
  24874. });
  24875. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24876. /**
  24877. * Default image processing configuration used either in the rendering
  24878. * Forward main pass or through the imageProcessingPostProcess if present.
  24879. * As in the majority of the scene they are the same (exception for multi camera),
  24880. * this is easier to reference from here than from all the materials and post process.
  24881. *
  24882. * No setter as we it is a shared configuration, you can set the values instead.
  24883. */
  24884. get: function () {
  24885. return this._imageProcessingConfiguration;
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24891. get: function () {
  24892. return this._forceWireframe;
  24893. },
  24894. /**
  24895. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24896. */
  24897. set: function (value) {
  24898. if (this._forceWireframe === value) {
  24899. return;
  24900. }
  24901. this._forceWireframe = value;
  24902. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24903. },
  24904. enumerable: true,
  24905. configurable: true
  24906. });
  24907. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24908. get: function () {
  24909. return this._forcePointsCloud;
  24910. },
  24911. /**
  24912. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24913. */
  24914. set: function (value) {
  24915. if (this._forcePointsCloud === value) {
  24916. return;
  24917. }
  24918. this._forcePointsCloud = value;
  24919. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24920. },
  24921. enumerable: true,
  24922. configurable: true
  24923. });
  24924. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24925. /**
  24926. * Gets or sets the animation properties override
  24927. */
  24928. get: function () {
  24929. return this._animationPropertiesOverride;
  24930. },
  24931. set: function (value) {
  24932. this._animationPropertiesOverride = value;
  24933. },
  24934. enumerable: true,
  24935. configurable: true
  24936. });
  24937. Object.defineProperty(Scene.prototype, "onDispose", {
  24938. /** Sets a function to be executed when this scene is disposed. */
  24939. set: function (callback) {
  24940. if (this._onDisposeObserver) {
  24941. this.onDisposeObservable.remove(this._onDisposeObserver);
  24942. }
  24943. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(Scene.prototype, "beforeRender", {
  24949. /** Sets a function to be executed before rendering this scene */
  24950. set: function (callback) {
  24951. if (this._onBeforeRenderObserver) {
  24952. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24953. }
  24954. if (callback) {
  24955. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24956. }
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. Object.defineProperty(Scene.prototype, "afterRender", {
  24962. /** Sets a function to be executed after rendering this scene */
  24963. set: function (callback) {
  24964. if (this._onAfterRenderObserver) {
  24965. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24966. }
  24967. if (callback) {
  24968. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24969. }
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24975. /** Sets a function to be executed before rendering a camera*/
  24976. set: function (callback) {
  24977. if (this._onBeforeCameraRenderObserver) {
  24978. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24979. }
  24980. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24986. /** Sets a function to be executed after rendering a camera*/
  24987. set: function (callback) {
  24988. if (this._onAfterCameraRenderObserver) {
  24989. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24990. }
  24991. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24992. },
  24993. enumerable: true,
  24994. configurable: true
  24995. });
  24996. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24997. /**
  24998. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24999. */
  25000. get: function () {
  25001. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25007. get: function () {
  25008. return this._useRightHandedSystem;
  25009. },
  25010. /**
  25011. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25012. */
  25013. set: function (value) {
  25014. if (this._useRightHandedSystem === value) {
  25015. return;
  25016. }
  25017. this._useRightHandedSystem = value;
  25018. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25019. },
  25020. enumerable: true,
  25021. configurable: true
  25022. });
  25023. /**
  25024. * Sets the step Id used by deterministic lock step
  25025. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25026. * @param newStepId defines the step Id
  25027. */
  25028. Scene.prototype.setStepId = function (newStepId) {
  25029. this._currentStepId = newStepId;
  25030. };
  25031. ;
  25032. /**
  25033. * Gets the step Id used by deterministic lock step
  25034. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25035. * @returns the step Id
  25036. */
  25037. Scene.prototype.getStepId = function () {
  25038. return this._currentStepId;
  25039. };
  25040. ;
  25041. /**
  25042. * Gets the internal step used by deterministic lock step
  25043. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25044. * @returns the internal step
  25045. */
  25046. Scene.prototype.getInternalStep = function () {
  25047. return this._currentInternalStep;
  25048. };
  25049. ;
  25050. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25051. get: function () {
  25052. return this._fogEnabled;
  25053. },
  25054. /**
  25055. * Gets or sets a boolean indicating if fog is enabled on this scene
  25056. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25057. */
  25058. set: function (value) {
  25059. if (this._fogEnabled === value) {
  25060. return;
  25061. }
  25062. this._fogEnabled = value;
  25063. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25064. },
  25065. enumerable: true,
  25066. configurable: true
  25067. });
  25068. Object.defineProperty(Scene.prototype, "fogMode", {
  25069. get: function () {
  25070. return this._fogMode;
  25071. },
  25072. /**
  25073. * Gets or sets the fog mode to use
  25074. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25075. */
  25076. set: function (value) {
  25077. if (this._fogMode === value) {
  25078. return;
  25079. }
  25080. this._fogMode = value;
  25081. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25082. },
  25083. enumerable: true,
  25084. configurable: true
  25085. });
  25086. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25087. get: function () {
  25088. return this._shadowsEnabled;
  25089. },
  25090. /**
  25091. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25092. */
  25093. set: function (value) {
  25094. if (this._shadowsEnabled === value) {
  25095. return;
  25096. }
  25097. this._shadowsEnabled = value;
  25098. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25099. },
  25100. enumerable: true,
  25101. configurable: true
  25102. });
  25103. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25104. get: function () {
  25105. return this._lightsEnabled;
  25106. },
  25107. /**
  25108. * Gets or sets a boolean indicating if lights are enabled on this scene
  25109. */
  25110. set: function (value) {
  25111. if (this._lightsEnabled === value) {
  25112. return;
  25113. }
  25114. this._lightsEnabled = value;
  25115. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25116. },
  25117. enumerable: true,
  25118. configurable: true
  25119. });
  25120. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25121. /** The default material used on meshes when no material is affected */
  25122. get: function () {
  25123. if (!this._defaultMaterial) {
  25124. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25125. }
  25126. return this._defaultMaterial;
  25127. },
  25128. /** The default material used on meshes when no material is affected */
  25129. set: function (value) {
  25130. this._defaultMaterial = value;
  25131. },
  25132. enumerable: true,
  25133. configurable: true
  25134. });
  25135. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25136. get: function () {
  25137. return this._texturesEnabled;
  25138. },
  25139. /**
  25140. * Gets or sets a boolean indicating if textures are enabled on this scene
  25141. */
  25142. set: function (value) {
  25143. if (this._texturesEnabled === value) {
  25144. return;
  25145. }
  25146. this._texturesEnabled = value;
  25147. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25148. },
  25149. enumerable: true,
  25150. configurable: true
  25151. });
  25152. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25153. get: function () {
  25154. return this._skeletonsEnabled;
  25155. },
  25156. /**
  25157. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25158. */
  25159. set: function (value) {
  25160. if (this._skeletonsEnabled === value) {
  25161. return;
  25162. }
  25163. this._skeletonsEnabled = value;
  25164. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25165. },
  25166. enumerable: true,
  25167. configurable: true
  25168. });
  25169. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25170. /** @hidden */
  25171. get: function () {
  25172. return this._alternateRendering;
  25173. },
  25174. enumerable: true,
  25175. configurable: true
  25176. });
  25177. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25178. /**
  25179. * Gets the list of frustum planes (built from the active camera)
  25180. */
  25181. get: function () {
  25182. return this._frustumPlanes;
  25183. },
  25184. enumerable: true,
  25185. configurable: true
  25186. });
  25187. /**
  25188. * Registers the transient components if needed.
  25189. */
  25190. Scene.prototype._registerTransientComponents = function () {
  25191. // Register components that have been associated lately to the scene.
  25192. if (this._transientComponents.length > 0) {
  25193. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25194. var component = _a[_i];
  25195. component.register();
  25196. }
  25197. this._transientComponents = [];
  25198. }
  25199. };
  25200. /**
  25201. * @hidden
  25202. * Add a component to the scene.
  25203. * Note that the ccomponent could be registered on th next frame if this is called after
  25204. * the register component stage.
  25205. * @param component Defines the component to add to the scene
  25206. */
  25207. Scene.prototype._addComponent = function (component) {
  25208. this._components.push(component);
  25209. this._transientComponents.push(component);
  25210. var serializableComponent = component;
  25211. if (serializableComponent.addFromContainer) {
  25212. this._serializableComponents.push(serializableComponent);
  25213. }
  25214. };
  25215. /**
  25216. * @hidden
  25217. * Gets a component from the scene.
  25218. * @param name defines the name of the component to retrieve
  25219. * @returns the component or null if not present
  25220. */
  25221. Scene.prototype._getComponent = function (name) {
  25222. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25223. var component = _a[_i];
  25224. if (component.name === name) {
  25225. return component;
  25226. }
  25227. }
  25228. return null;
  25229. };
  25230. /**
  25231. * @hidden
  25232. */
  25233. Scene.prototype._getDefaultMeshCandidates = function () {
  25234. this._defaultMeshCandidates.data = this.meshes;
  25235. this._defaultMeshCandidates.length = this.meshes.length;
  25236. return this._defaultMeshCandidates;
  25237. };
  25238. /**
  25239. * @hidden
  25240. */
  25241. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25242. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25243. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25244. return this._defaultSubMeshCandidates;
  25245. };
  25246. /**
  25247. * Sets the default candidate providers for the scene.
  25248. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25249. * and getCollidingSubMeshCandidates to their default function
  25250. */
  25251. Scene.prototype.setDefaultCandidateProviders = function () {
  25252. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25253. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25254. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25255. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25256. };
  25257. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25258. /**
  25259. * Gets a boolean indicating if collisions are processed on a web worker
  25260. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25261. */
  25262. get: function () {
  25263. return this._workerCollisions;
  25264. },
  25265. set: function (enabled) {
  25266. if (!BABYLON.CollisionCoordinatorLegacy) {
  25267. return;
  25268. }
  25269. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25270. this._workerCollisions = enabled;
  25271. if (this.collisionCoordinator) {
  25272. this.collisionCoordinator.destroy();
  25273. }
  25274. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25275. this.collisionCoordinator.init(this);
  25276. },
  25277. enumerable: true,
  25278. configurable: true
  25279. });
  25280. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25281. /**
  25282. * Gets the mesh that is currently under the pointer
  25283. */
  25284. get: function () {
  25285. return this._pointerOverMesh;
  25286. },
  25287. enumerable: true,
  25288. configurable: true
  25289. });
  25290. Object.defineProperty(Scene.prototype, "pointerX", {
  25291. /**
  25292. * Gets the current on-screen X position of the pointer
  25293. */
  25294. get: function () {
  25295. return this._pointerX;
  25296. },
  25297. enumerable: true,
  25298. configurable: true
  25299. });
  25300. Object.defineProperty(Scene.prototype, "pointerY", {
  25301. /**
  25302. * Gets the current on-screen Y position of the pointer
  25303. */
  25304. get: function () {
  25305. return this._pointerY;
  25306. },
  25307. enumerable: true,
  25308. configurable: true
  25309. });
  25310. /**
  25311. * Gets the cached material (ie. the latest rendered one)
  25312. * @returns the cached material
  25313. */
  25314. Scene.prototype.getCachedMaterial = function () {
  25315. return this._cachedMaterial;
  25316. };
  25317. /**
  25318. * Gets the cached effect (ie. the latest rendered one)
  25319. * @returns the cached effect
  25320. */
  25321. Scene.prototype.getCachedEffect = function () {
  25322. return this._cachedEffect;
  25323. };
  25324. /**
  25325. * Gets the cached visibility state (ie. the latest rendered one)
  25326. * @returns the cached visibility state
  25327. */
  25328. Scene.prototype.getCachedVisibility = function () {
  25329. return this._cachedVisibility;
  25330. };
  25331. /**
  25332. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25333. * @param material defines the current material
  25334. * @param effect defines the current effect
  25335. * @param visibility defines the current visibility state
  25336. * @returns true if one parameter is not cached
  25337. */
  25338. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25339. if (visibility === void 0) { visibility = 1; }
  25340. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25341. };
  25342. /**
  25343. * Gets the engine associated with the scene
  25344. * @returns an Engine
  25345. */
  25346. Scene.prototype.getEngine = function () {
  25347. return this._engine;
  25348. };
  25349. /**
  25350. * Gets the total number of vertices rendered per frame
  25351. * @returns the total number of vertices rendered per frame
  25352. */
  25353. Scene.prototype.getTotalVertices = function () {
  25354. return this._totalVertices.current;
  25355. };
  25356. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25357. /**
  25358. * Gets the performance counter for total vertices
  25359. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25360. */
  25361. get: function () {
  25362. return this._totalVertices;
  25363. },
  25364. enumerable: true,
  25365. configurable: true
  25366. });
  25367. /**
  25368. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25369. * @returns the total number of active indices rendered per frame
  25370. */
  25371. Scene.prototype.getActiveIndices = function () {
  25372. return this._activeIndices.current;
  25373. };
  25374. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25375. /**
  25376. * Gets the performance counter for active indices
  25377. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25378. */
  25379. get: function () {
  25380. return this._activeIndices;
  25381. },
  25382. enumerable: true,
  25383. configurable: true
  25384. });
  25385. /**
  25386. * Gets the total number of active particles rendered per frame
  25387. * @returns the total number of active particles rendered per frame
  25388. */
  25389. Scene.prototype.getActiveParticles = function () {
  25390. return this._activeParticles.current;
  25391. };
  25392. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25393. /**
  25394. * Gets the performance counter for active particles
  25395. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25396. */
  25397. get: function () {
  25398. return this._activeParticles;
  25399. },
  25400. enumerable: true,
  25401. configurable: true
  25402. });
  25403. /**
  25404. * Gets the total number of active bones rendered per frame
  25405. * @returns the total number of active bones rendered per frame
  25406. */
  25407. Scene.prototype.getActiveBones = function () {
  25408. return this._activeBones.current;
  25409. };
  25410. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25411. /**
  25412. * Gets the performance counter for active bones
  25413. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25414. */
  25415. get: function () {
  25416. return this._activeBones;
  25417. },
  25418. enumerable: true,
  25419. configurable: true
  25420. });
  25421. /** @hidden */
  25422. Scene.prototype.getInterFramePerfCounter = function () {
  25423. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25424. return 0;
  25425. };
  25426. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25427. /** @hidden */
  25428. get: function () {
  25429. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25430. return null;
  25431. },
  25432. enumerable: true,
  25433. configurable: true
  25434. });
  25435. /** @hidden */
  25436. Scene.prototype.getLastFrameDuration = function () {
  25437. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25438. return 0;
  25439. };
  25440. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25441. /** @hidden */
  25442. get: function () {
  25443. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25444. return null;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. /** @hidden */
  25450. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25451. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25452. return 0;
  25453. };
  25454. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25455. /** @hidden */
  25456. get: function () {
  25457. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25458. return null;
  25459. },
  25460. enumerable: true,
  25461. configurable: true
  25462. });
  25463. /**
  25464. * Gets the array of active meshes
  25465. * @returns an array of AbstractMesh
  25466. */
  25467. Scene.prototype.getActiveMeshes = function () {
  25468. return this._activeMeshes;
  25469. };
  25470. /** @hidden */
  25471. Scene.prototype.getRenderTargetsDuration = function () {
  25472. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25473. return 0;
  25474. };
  25475. /** @hidden */
  25476. Scene.prototype.getRenderDuration = function () {
  25477. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25478. return 0;
  25479. };
  25480. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25481. /** @hidden */
  25482. get: function () {
  25483. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25484. return null;
  25485. },
  25486. enumerable: true,
  25487. configurable: true
  25488. });
  25489. /** @hidden */
  25490. Scene.prototype.getParticlesDuration = function () {
  25491. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25492. return 0;
  25493. };
  25494. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25495. /** @hidden */
  25496. get: function () {
  25497. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25498. return null;
  25499. },
  25500. enumerable: true,
  25501. configurable: true
  25502. });
  25503. /** @hidden */
  25504. Scene.prototype.getSpritesDuration = function () {
  25505. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25506. return 0;
  25507. };
  25508. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25509. /** @hidden */
  25510. get: function () {
  25511. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25512. return null;
  25513. },
  25514. enumerable: true,
  25515. configurable: true
  25516. });
  25517. /**
  25518. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25519. * @returns a number
  25520. */
  25521. Scene.prototype.getAnimationRatio = function () {
  25522. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25523. };
  25524. /**
  25525. * Gets an unique Id for the current render phase
  25526. * @returns a number
  25527. */
  25528. Scene.prototype.getRenderId = function () {
  25529. return this._renderId;
  25530. };
  25531. /**
  25532. * Gets an unique Id for the current frame
  25533. * @returns a number
  25534. */
  25535. Scene.prototype.getFrameId = function () {
  25536. return this._frameId;
  25537. };
  25538. /** Call this function if you want to manually increment the render Id*/
  25539. Scene.prototype.incrementRenderId = function () {
  25540. this._renderId++;
  25541. };
  25542. Scene.prototype._updatePointerPosition = function (evt) {
  25543. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25544. if (!canvasRect) {
  25545. return;
  25546. }
  25547. this._pointerX = evt.clientX - canvasRect.left;
  25548. this._pointerY = evt.clientY - canvasRect.top;
  25549. this._unTranslatedPointerX = this._pointerX;
  25550. this._unTranslatedPointerY = this._pointerY;
  25551. };
  25552. Scene.prototype._createUbo = function () {
  25553. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25554. this._sceneUbo.addUniform("viewProjection", 16);
  25555. this._sceneUbo.addUniform("view", 16);
  25556. };
  25557. Scene.prototype._createAlternateUbo = function () {
  25558. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25559. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25560. this._alternateSceneUbo.addUniform("view", 16);
  25561. };
  25562. // Pointers handling
  25563. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25564. if (pointerInfo.pickInfo) {
  25565. if (!pointerInfo.pickInfo.ray) {
  25566. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25567. }
  25568. }
  25569. };
  25570. /**
  25571. * Use this method to simulate a pointer move on a mesh
  25572. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25573. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25574. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25575. * @returns the current scene
  25576. */
  25577. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25578. var evt = new PointerEvent("pointermove", pointerEventInit);
  25579. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25580. return this;
  25581. }
  25582. return this._processPointerMove(pickResult, evt);
  25583. };
  25584. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25585. var canvas = this._engine.getRenderingCanvas();
  25586. if (!canvas) {
  25587. return this;
  25588. }
  25589. // Restore pointer
  25590. canvas.style.cursor = this.defaultCursor;
  25591. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25592. if (isMeshPicked) {
  25593. this.setPointerOverMesh(pickResult.pickedMesh);
  25594. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25595. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25596. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25597. }
  25598. else {
  25599. canvas.style.cursor = this.hoverCursor;
  25600. }
  25601. }
  25602. }
  25603. else {
  25604. this.setPointerOverMesh(null);
  25605. }
  25606. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25607. var step = _a[_i];
  25608. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25609. }
  25610. if (pickResult) {
  25611. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25612. if (this.onPointerMove) {
  25613. this.onPointerMove(evt, pickResult, type);
  25614. }
  25615. if (this.onPointerObservable.hasObservers()) {
  25616. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25617. this._setRayOnPointerInfo(pi);
  25618. this.onPointerObservable.notifyObservers(pi, type);
  25619. }
  25620. }
  25621. return this;
  25622. };
  25623. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25624. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25625. if (pickResult) {
  25626. pi.ray = pickResult.ray;
  25627. }
  25628. this.onPrePointerObservable.notifyObservers(pi, type);
  25629. if (pi.skipOnPointerObservable) {
  25630. return true;
  25631. }
  25632. else {
  25633. return false;
  25634. }
  25635. };
  25636. /**
  25637. * Use this method to simulate a pointer down on a mesh
  25638. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25639. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25640. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25641. * @returns the current scene
  25642. */
  25643. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25644. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25645. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25646. return this;
  25647. }
  25648. return this._processPointerDown(pickResult, evt);
  25649. };
  25650. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25651. var _this = this;
  25652. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25653. this._pickedDownMesh = pickResult.pickedMesh;
  25654. var actionManager = pickResult.pickedMesh.actionManager;
  25655. if (actionManager) {
  25656. if (actionManager.hasPickTriggers) {
  25657. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25658. switch (evt.button) {
  25659. case 0:
  25660. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25661. break;
  25662. case 1:
  25663. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25664. break;
  25665. case 2:
  25666. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25667. break;
  25668. }
  25669. }
  25670. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25671. window.setTimeout(function () {
  25672. 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);
  25673. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25674. if (_this._totalPointersPressed !== 0 &&
  25675. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25676. !_this._isPointerSwiping()) {
  25677. _this._startingPointerTime = 0;
  25678. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25679. }
  25680. }
  25681. }, Scene.LongPressDelay);
  25682. }
  25683. }
  25684. }
  25685. else {
  25686. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25687. var step = _a[_i];
  25688. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25689. }
  25690. }
  25691. if (pickResult) {
  25692. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25693. if (this.onPointerDown) {
  25694. this.onPointerDown(evt, pickResult, type);
  25695. }
  25696. if (this.onPointerObservable.hasObservers()) {
  25697. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25698. this._setRayOnPointerInfo(pi);
  25699. this.onPointerObservable.notifyObservers(pi, type);
  25700. }
  25701. }
  25702. return this;
  25703. };
  25704. /**
  25705. * Use this method to simulate a pointer up on a mesh
  25706. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25707. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25708. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25709. * @returns the current scene
  25710. */
  25711. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25712. var evt = new PointerEvent("pointerup", pointerEventInit);
  25713. var clickInfo = new ClickInfo();
  25714. clickInfo.singleClick = true;
  25715. clickInfo.ignore = true;
  25716. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25717. return this;
  25718. }
  25719. return this._processPointerUp(pickResult, evt, clickInfo);
  25720. };
  25721. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25722. if (pickResult && pickResult && pickResult.pickedMesh) {
  25723. this._pickedUpMesh = pickResult.pickedMesh;
  25724. if (this._pickedDownMesh === this._pickedUpMesh) {
  25725. if (this.onPointerPick) {
  25726. this.onPointerPick(evt, pickResult);
  25727. }
  25728. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25729. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25730. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25731. this._setRayOnPointerInfo(pi);
  25732. this.onPointerObservable.notifyObservers(pi, type_1);
  25733. }
  25734. }
  25735. if (pickResult.pickedMesh.actionManager) {
  25736. if (clickInfo.ignore) {
  25737. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25738. }
  25739. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25740. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25741. }
  25742. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25743. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25744. }
  25745. }
  25746. }
  25747. else {
  25748. if (!clickInfo.ignore) {
  25749. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25750. var step = _a[_i];
  25751. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25752. }
  25753. }
  25754. }
  25755. if (this._pickedDownMesh &&
  25756. this._pickedDownMesh.actionManager &&
  25757. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25758. this._pickedDownMesh !== this._pickedUpMesh) {
  25759. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25760. }
  25761. var type = BABYLON.PointerEventTypes.POINTERUP;
  25762. if (this.onPointerObservable.hasObservers()) {
  25763. if (!clickInfo.ignore) {
  25764. if (!clickInfo.hasSwiped) {
  25765. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25766. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25767. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25768. this._setRayOnPointerInfo(pi);
  25769. this.onPointerObservable.notifyObservers(pi, type_2);
  25770. }
  25771. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25772. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25773. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25774. this._setRayOnPointerInfo(pi);
  25775. this.onPointerObservable.notifyObservers(pi, type_3);
  25776. }
  25777. }
  25778. }
  25779. else {
  25780. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25781. this._setRayOnPointerInfo(pi);
  25782. this.onPointerObservable.notifyObservers(pi, type);
  25783. }
  25784. }
  25785. if (this.onPointerUp) {
  25786. this.onPointerUp(evt, pickResult, type);
  25787. }
  25788. return this;
  25789. };
  25790. /**
  25791. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25792. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25793. * @returns true if the pointer was captured
  25794. */
  25795. Scene.prototype.isPointerCaptured = function (pointerId) {
  25796. if (pointerId === void 0) { pointerId = 0; }
  25797. return this._pointerCaptures[pointerId];
  25798. };
  25799. /** @hidden */
  25800. Scene.prototype._isPointerSwiping = function () {
  25801. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25802. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25803. };
  25804. /**
  25805. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25806. * @param attachUp defines if you want to attach events to pointerup
  25807. * @param attachDown defines if you want to attach events to pointerdown
  25808. * @param attachMove defines if you want to attach events to pointermove
  25809. */
  25810. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25811. var _this = this;
  25812. if (attachUp === void 0) { attachUp = true; }
  25813. if (attachDown === void 0) { attachDown = true; }
  25814. if (attachMove === void 0) { attachMove = true; }
  25815. this._initActionManager = function (act, clickInfo) {
  25816. if (!_this._meshPickProceed) {
  25817. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25818. _this._currentPickResult = pickResult;
  25819. if (pickResult) {
  25820. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25821. }
  25822. _this._meshPickProceed = true;
  25823. }
  25824. return act;
  25825. };
  25826. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25827. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25828. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25829. btn !== _this._previousButtonPressed) {
  25830. _this._doubleClickOccured = false;
  25831. clickInfo.singleClick = true;
  25832. clickInfo.ignore = false;
  25833. cb(clickInfo, _this._currentPickResult);
  25834. }
  25835. };
  25836. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25837. var clickInfo = new ClickInfo();
  25838. _this._currentPickResult = null;
  25839. var act = null;
  25840. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25841. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25842. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25843. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25844. act = _this._initActionManager(act, clickInfo);
  25845. if (act)
  25846. checkPicking = act.hasPickTriggers;
  25847. }
  25848. if (checkPicking) {
  25849. var btn = evt.button;
  25850. clickInfo.hasSwiped = _this._isPointerSwiping();
  25851. if (!clickInfo.hasSwiped) {
  25852. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25853. if (!checkSingleClickImmediately) {
  25854. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25855. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25856. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25857. act = _this._initActionManager(act, clickInfo);
  25858. if (act)
  25859. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25860. }
  25861. }
  25862. if (checkSingleClickImmediately) {
  25863. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25864. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25865. btn !== _this._previousButtonPressed) {
  25866. clickInfo.singleClick = true;
  25867. cb(clickInfo, _this._currentPickResult);
  25868. }
  25869. }
  25870. // at least one double click is required to be check and exclusive double click is enabled
  25871. else {
  25872. // wait that no double click has been raised during the double click delay
  25873. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25874. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25875. }
  25876. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25877. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25878. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25879. act = _this._initActionManager(act, clickInfo);
  25880. if (act)
  25881. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25882. }
  25883. if (checkDoubleClick) {
  25884. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25885. if (btn === _this._previousButtonPressed &&
  25886. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25887. !_this._doubleClickOccured) {
  25888. // pointer has not moved for 2 clicks, it's a double click
  25889. if (!clickInfo.hasSwiped &&
  25890. !_this._isPointerSwiping()) {
  25891. _this._previousStartingPointerTime = 0;
  25892. _this._doubleClickOccured = true;
  25893. clickInfo.doubleClick = true;
  25894. clickInfo.ignore = false;
  25895. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25896. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25897. }
  25898. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25899. cb(clickInfo, _this._currentPickResult);
  25900. }
  25901. // if the two successive clicks are too far, it's just two simple clicks
  25902. else {
  25903. _this._doubleClickOccured = false;
  25904. _this._previousStartingPointerTime = _this._startingPointerTime;
  25905. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25906. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25907. _this._previousButtonPressed = btn;
  25908. if (Scene.ExclusiveDoubleClickMode) {
  25909. if (_this._previousDelayedSimpleClickTimeout) {
  25910. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25911. }
  25912. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25913. cb(clickInfo, _this._previousPickResult);
  25914. }
  25915. else {
  25916. cb(clickInfo, _this._currentPickResult);
  25917. }
  25918. }
  25919. }
  25920. // just the first click of the double has been raised
  25921. else {
  25922. _this._doubleClickOccured = false;
  25923. _this._previousStartingPointerTime = _this._startingPointerTime;
  25924. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25925. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25926. _this._previousButtonPressed = btn;
  25927. }
  25928. }
  25929. }
  25930. }
  25931. clickInfo.ignore = true;
  25932. cb(clickInfo, _this._currentPickResult);
  25933. };
  25934. this._onPointerMove = function (evt) {
  25935. _this._updatePointerPosition(evt);
  25936. // PreObservable support
  25937. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25938. return;
  25939. }
  25940. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25941. return;
  25942. }
  25943. if (!_this.pointerMovePredicate) {
  25944. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25945. }
  25946. // Meshes
  25947. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25948. _this._processPointerMove(pickResult, evt);
  25949. };
  25950. this._onPointerDown = function (evt) {
  25951. _this._totalPointersPressed++;
  25952. _this._pickedDownMesh = null;
  25953. _this._meshPickProceed = false;
  25954. _this._updatePointerPosition(evt);
  25955. if (_this.preventDefaultOnPointerDown && canvas) {
  25956. evt.preventDefault();
  25957. canvas.focus();
  25958. }
  25959. // PreObservable support
  25960. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25961. return;
  25962. }
  25963. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25964. return;
  25965. }
  25966. _this._pointerCaptures[evt.pointerId] = true;
  25967. _this._startingPointerPosition.x = _this._pointerX;
  25968. _this._startingPointerPosition.y = _this._pointerY;
  25969. _this._startingPointerTime = Date.now();
  25970. if (!_this.pointerDownPredicate) {
  25971. _this.pointerDownPredicate = function (mesh) {
  25972. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25973. };
  25974. }
  25975. // Meshes
  25976. _this._pickedDownMesh = null;
  25977. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25978. _this._processPointerDown(pickResult, evt);
  25979. };
  25980. this._onPointerUp = function (evt) {
  25981. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25982. return; // So we need to test it the pointer down was pressed before.
  25983. }
  25984. _this._totalPointersPressed--;
  25985. _this._pickedUpMesh = null;
  25986. _this._meshPickProceed = false;
  25987. _this._updatePointerPosition(evt);
  25988. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25989. // PreObservable support
  25990. if (_this.onPrePointerObservable.hasObservers()) {
  25991. if (!clickInfo.ignore) {
  25992. if (!clickInfo.hasSwiped) {
  25993. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25994. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25995. return;
  25996. }
  25997. }
  25998. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25999. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26000. return;
  26001. }
  26002. }
  26003. }
  26004. }
  26005. else {
  26006. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26007. return;
  26008. }
  26009. }
  26010. }
  26011. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26012. return;
  26013. }
  26014. _this._pointerCaptures[evt.pointerId] = false;
  26015. if (!_this.pointerUpPredicate) {
  26016. _this.pointerUpPredicate = function (mesh) {
  26017. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26018. };
  26019. }
  26020. // Meshes
  26021. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26022. _this._initActionManager(null, clickInfo);
  26023. }
  26024. if (!pickResult) {
  26025. pickResult = _this._currentPickResult;
  26026. }
  26027. _this._processPointerUp(pickResult, evt, clickInfo);
  26028. _this._previousPickResult = _this._currentPickResult;
  26029. });
  26030. };
  26031. this._onKeyDown = function (evt) {
  26032. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26033. if (_this.onPreKeyboardObservable.hasObservers()) {
  26034. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26035. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26036. if (pi.skipOnPointerObservable) {
  26037. return;
  26038. }
  26039. }
  26040. if (_this.onKeyboardObservable.hasObservers()) {
  26041. var pi = new BABYLON.KeyboardInfo(type, evt);
  26042. _this.onKeyboardObservable.notifyObservers(pi, type);
  26043. }
  26044. if (_this.actionManager) {
  26045. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26046. }
  26047. };
  26048. this._onKeyUp = function (evt) {
  26049. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26050. if (_this.onPreKeyboardObservable.hasObservers()) {
  26051. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26052. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26053. if (pi.skipOnPointerObservable) {
  26054. return;
  26055. }
  26056. }
  26057. if (_this.onKeyboardObservable.hasObservers()) {
  26058. var pi = new BABYLON.KeyboardInfo(type, evt);
  26059. _this.onKeyboardObservable.notifyObservers(pi, type);
  26060. }
  26061. if (_this.actionManager) {
  26062. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26063. }
  26064. };
  26065. var engine = this.getEngine();
  26066. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26067. if (!canvas) {
  26068. return;
  26069. }
  26070. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26071. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26072. });
  26073. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26074. if (!canvas) {
  26075. return;
  26076. }
  26077. canvas.removeEventListener("keydown", _this._onKeyDown);
  26078. canvas.removeEventListener("keyup", _this._onKeyUp);
  26079. });
  26080. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26081. var canvas = this._engine.getRenderingCanvas();
  26082. if (!canvas) {
  26083. return;
  26084. }
  26085. if (attachMove) {
  26086. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26087. // Wheel
  26088. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26089. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26090. }
  26091. if (attachDown) {
  26092. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26093. }
  26094. if (attachUp) {
  26095. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26096. }
  26097. canvas.tabIndex = 1;
  26098. };
  26099. /** Detaches all event handlers*/
  26100. Scene.prototype.detachControl = function () {
  26101. var engine = this.getEngine();
  26102. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26103. var canvas = engine.getRenderingCanvas();
  26104. if (!canvas) {
  26105. return;
  26106. }
  26107. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26108. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26109. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26110. if (this._onCanvasBlurObserver) {
  26111. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26112. }
  26113. if (this._onCanvasFocusObserver) {
  26114. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26115. }
  26116. // Wheel
  26117. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26118. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26119. // Keyboard
  26120. canvas.removeEventListener("keydown", this._onKeyDown);
  26121. canvas.removeEventListener("keyup", this._onKeyUp);
  26122. // Observables
  26123. this.onKeyboardObservable.clear();
  26124. this.onPreKeyboardObservable.clear();
  26125. this.onPointerObservable.clear();
  26126. this.onPrePointerObservable.clear();
  26127. };
  26128. /**
  26129. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26130. * Delay loaded resources are not taking in account
  26131. * @return true if all required resources are ready
  26132. */
  26133. Scene.prototype.isReady = function () {
  26134. if (this._isDisposed) {
  26135. return false;
  26136. }
  26137. if (this._pendingData.length > 0) {
  26138. return false;
  26139. }
  26140. var index;
  26141. var engine = this.getEngine();
  26142. // Geometries
  26143. for (index = 0; index < this.geometries.length; index++) {
  26144. var geometry = this.geometries[index];
  26145. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26146. return false;
  26147. }
  26148. }
  26149. // Meshes
  26150. for (index = 0; index < this.meshes.length; index++) {
  26151. var mesh = this.meshes[index];
  26152. if (!mesh.isEnabled()) {
  26153. continue;
  26154. }
  26155. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26156. continue;
  26157. }
  26158. if (!mesh.isReady(true)) {
  26159. return false;
  26160. }
  26161. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26162. // Is Ready For Mesh
  26163. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26164. var step = _a[_i];
  26165. if (!step.action(mesh, hardwareInstancedRendering)) {
  26166. return false;
  26167. }
  26168. }
  26169. }
  26170. // Post-processes
  26171. if (this.activeCameras && this.activeCameras.length > 0) {
  26172. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26173. var camera = _c[_b];
  26174. if (!camera.isReady(true)) {
  26175. return false;
  26176. }
  26177. }
  26178. }
  26179. else if (this.activeCamera) {
  26180. if (!this.activeCamera.isReady(true)) {
  26181. return false;
  26182. }
  26183. }
  26184. // Particles
  26185. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26186. var particleSystem = _e[_d];
  26187. if (!particleSystem.isReady()) {
  26188. return false;
  26189. }
  26190. }
  26191. return true;
  26192. };
  26193. /** Resets all cached information relative to material (including effect and visibility) */
  26194. Scene.prototype.resetCachedMaterial = function () {
  26195. this._cachedMaterial = null;
  26196. this._cachedEffect = null;
  26197. this._cachedVisibility = null;
  26198. };
  26199. /**
  26200. * Registers a function to be called before every frame render
  26201. * @param func defines the function to register
  26202. */
  26203. Scene.prototype.registerBeforeRender = function (func) {
  26204. this.onBeforeRenderObservable.add(func);
  26205. };
  26206. /**
  26207. * Unregisters a function called before every frame render
  26208. * @param func defines the function to unregister
  26209. */
  26210. Scene.prototype.unregisterBeforeRender = function (func) {
  26211. this.onBeforeRenderObservable.removeCallback(func);
  26212. };
  26213. /**
  26214. * Registers a function to be called after every frame render
  26215. * @param func defines the function to register
  26216. */
  26217. Scene.prototype.registerAfterRender = function (func) {
  26218. this.onAfterRenderObservable.add(func);
  26219. };
  26220. /**
  26221. * Unregisters a function called after every frame render
  26222. * @param func defines the function to unregister
  26223. */
  26224. Scene.prototype.unregisterAfterRender = function (func) {
  26225. this.onAfterRenderObservable.removeCallback(func);
  26226. };
  26227. Scene.prototype._executeOnceBeforeRender = function (func) {
  26228. var _this = this;
  26229. var execFunc = function () {
  26230. func();
  26231. setTimeout(function () {
  26232. _this.unregisterBeforeRender(execFunc);
  26233. });
  26234. };
  26235. this.registerBeforeRender(execFunc);
  26236. };
  26237. /**
  26238. * The provided function will run before render once and will be disposed afterwards.
  26239. * A timeout delay can be provided so that the function will be executed in N ms.
  26240. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26241. * @param func The function to be executed.
  26242. * @param timeout optional delay in ms
  26243. */
  26244. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26245. var _this = this;
  26246. if (timeout !== undefined) {
  26247. setTimeout(function () {
  26248. _this._executeOnceBeforeRender(func);
  26249. }, timeout);
  26250. }
  26251. else {
  26252. this._executeOnceBeforeRender(func);
  26253. }
  26254. };
  26255. /** @hidden */
  26256. Scene.prototype._addPendingData = function (data) {
  26257. this._pendingData.push(data);
  26258. };
  26259. /** @hidden */
  26260. Scene.prototype._removePendingData = function (data) {
  26261. var wasLoading = this.isLoading;
  26262. var index = this._pendingData.indexOf(data);
  26263. if (index !== -1) {
  26264. this._pendingData.splice(index, 1);
  26265. }
  26266. if (wasLoading && !this.isLoading) {
  26267. this.onDataLoadedObservable.notifyObservers(this);
  26268. }
  26269. };
  26270. /**
  26271. * Returns the number of items waiting to be loaded
  26272. * @returns the number of items waiting to be loaded
  26273. */
  26274. Scene.prototype.getWaitingItemsCount = function () {
  26275. return this._pendingData.length;
  26276. };
  26277. Object.defineProperty(Scene.prototype, "isLoading", {
  26278. /**
  26279. * Returns a boolean indicating if the scene is still loading data
  26280. */
  26281. get: function () {
  26282. return this._pendingData.length > 0;
  26283. },
  26284. enumerable: true,
  26285. configurable: true
  26286. });
  26287. /**
  26288. * Registers a function to be executed when the scene is ready
  26289. * @param {Function} func - the function to be executed
  26290. */
  26291. Scene.prototype.executeWhenReady = function (func) {
  26292. var _this = this;
  26293. this.onReadyObservable.add(func);
  26294. if (this._executeWhenReadyTimeoutId !== -1) {
  26295. return;
  26296. }
  26297. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26298. _this._checkIsReady();
  26299. }, 150);
  26300. };
  26301. /**
  26302. * Returns a promise that resolves when the scene is ready
  26303. * @returns A promise that resolves when the scene is ready
  26304. */
  26305. Scene.prototype.whenReadyAsync = function () {
  26306. var _this = this;
  26307. return new Promise(function (resolve) {
  26308. _this.executeWhenReady(function () {
  26309. resolve();
  26310. });
  26311. });
  26312. };
  26313. /** @hidden */
  26314. Scene.prototype._checkIsReady = function () {
  26315. var _this = this;
  26316. this._registerTransientComponents();
  26317. if (this.isReady()) {
  26318. this.onReadyObservable.notifyObservers(this);
  26319. this.onReadyObservable.clear();
  26320. this._executeWhenReadyTimeoutId = -1;
  26321. return;
  26322. }
  26323. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26324. _this._checkIsReady();
  26325. }, 150);
  26326. };
  26327. // Animations
  26328. /**
  26329. * Will start the animation sequence of a given target
  26330. * @param target defines the target
  26331. * @param from defines from which frame should animation start
  26332. * @param to defines until which frame should animation run.
  26333. * @param weight defines the weight to apply to the animation (1.0 by default)
  26334. * @param loop defines if the animation loops
  26335. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26336. * @param onAnimationEnd defines the function to be executed when the animation ends
  26337. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26338. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26339. * @returns the animatable object created for this animation
  26340. */
  26341. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26342. if (weight === void 0) { weight = 1.0; }
  26343. if (speedRatio === void 0) { speedRatio = 1.0; }
  26344. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26345. returnedAnimatable.weight = weight;
  26346. return returnedAnimatable;
  26347. };
  26348. /**
  26349. * Will start the animation sequence of a given target
  26350. * @param target defines the target
  26351. * @param from defines from which frame should animation start
  26352. * @param to defines until which frame should animation run.
  26353. * @param loop defines if the animation loops
  26354. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26355. * @param onAnimationEnd defines the function to be executed when the animation ends
  26356. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26357. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26358. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26359. * @returns the animatable object created for this animation
  26360. */
  26361. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26362. if (speedRatio === void 0) { speedRatio = 1.0; }
  26363. if (stopCurrent === void 0) { stopCurrent = true; }
  26364. if (from > to && speedRatio > 0) {
  26365. speedRatio *= -1;
  26366. }
  26367. if (stopCurrent) {
  26368. this.stopAnimation(target, undefined, targetMask);
  26369. }
  26370. if (!animatable) {
  26371. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26372. }
  26373. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26374. // Local animations
  26375. if (target.animations && shouldRunTargetAnimations) {
  26376. animatable.appendAnimations(target, target.animations);
  26377. }
  26378. // Children animations
  26379. if (target.getAnimatables) {
  26380. var animatables = target.getAnimatables();
  26381. for (var index = 0; index < animatables.length; index++) {
  26382. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26383. }
  26384. }
  26385. animatable.reset();
  26386. return animatable;
  26387. };
  26388. /**
  26389. * Begin a new animation on a given node
  26390. * @param target defines the target where the animation will take place
  26391. * @param animations defines the list of animations to start
  26392. * @param from defines the initial value
  26393. * @param to defines the final value
  26394. * @param loop defines if you want animation to loop (off by default)
  26395. * @param speedRatio defines the speed ratio to apply to all animations
  26396. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26397. * @returns the list of created animatables
  26398. */
  26399. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26400. if (speedRatio === undefined) {
  26401. speedRatio = 1.0;
  26402. }
  26403. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26404. return animatable;
  26405. };
  26406. /**
  26407. * Begin a new animation on a given node and its hierarchy
  26408. * @param target defines the root node where the animation will take place
  26409. * @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.
  26410. * @param animations defines the list of animations to start
  26411. * @param from defines the initial value
  26412. * @param to defines the final value
  26413. * @param loop defines if you want animation to loop (off by default)
  26414. * @param speedRatio defines the speed ratio to apply to all animations
  26415. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26416. * @returns the list of animatables created for all nodes
  26417. */
  26418. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26419. var children = target.getDescendants(directDescendantsOnly);
  26420. var result = [];
  26421. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26422. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26423. var child = children_1[_i];
  26424. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26425. }
  26426. return result;
  26427. };
  26428. /**
  26429. * Gets the animatable associated with a specific target
  26430. * @param target defines the target of the animatable
  26431. * @returns the required animatable if found
  26432. */
  26433. Scene.prototype.getAnimatableByTarget = function (target) {
  26434. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26435. if (this._activeAnimatables[index].target === target) {
  26436. return this._activeAnimatables[index];
  26437. }
  26438. }
  26439. return null;
  26440. };
  26441. /**
  26442. * Gets all animatables associated with a given target
  26443. * @param target defines the target to look animatables for
  26444. * @returns an array of Animatables
  26445. */
  26446. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26447. var result = [];
  26448. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26449. if (this._activeAnimatables[index].target === target) {
  26450. result.push(this._activeAnimatables[index]);
  26451. }
  26452. }
  26453. return result;
  26454. };
  26455. Object.defineProperty(Scene.prototype, "animatables", {
  26456. /**
  26457. * Gets all animatable attached to the scene
  26458. */
  26459. get: function () {
  26460. return this._activeAnimatables;
  26461. },
  26462. enumerable: true,
  26463. configurable: true
  26464. });
  26465. /**
  26466. * Will stop the animation of the given target
  26467. * @param target - the target
  26468. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26469. * @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)
  26470. */
  26471. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26472. var animatables = this.getAllAnimatablesByTarget(target);
  26473. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26474. var animatable = animatables_1[_i];
  26475. animatable.stop(animationName, targetMask);
  26476. }
  26477. };
  26478. /**
  26479. * Stops and removes all animations that have been applied to the scene
  26480. */
  26481. Scene.prototype.stopAllAnimations = function () {
  26482. if (this._activeAnimatables) {
  26483. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26484. this._activeAnimatables[i].stop();
  26485. }
  26486. this._activeAnimatables = [];
  26487. }
  26488. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26489. var group = _a[_i];
  26490. group.stop();
  26491. }
  26492. };
  26493. Scene.prototype._animate = function () {
  26494. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26495. return;
  26496. }
  26497. // Getting time
  26498. var now = BABYLON.Tools.Now;
  26499. if (!this._animationTimeLast) {
  26500. if (this._pendingData.length > 0) {
  26501. return;
  26502. }
  26503. this._animationTimeLast = now;
  26504. }
  26505. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26506. this._animationTime += deltaTime;
  26507. this._animationTimeLast = now;
  26508. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26509. this._activeAnimatables[index]._animate(this._animationTime);
  26510. }
  26511. // Late animation bindings
  26512. this._processLateAnimationBindings();
  26513. };
  26514. /** @hidden */
  26515. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26516. var target = runtimeAnimation.target;
  26517. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26518. if (!target._lateAnimationHolders) {
  26519. target._lateAnimationHolders = {};
  26520. }
  26521. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26522. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26523. totalWeight: 0,
  26524. animations: [],
  26525. originalValue: originalValue
  26526. };
  26527. }
  26528. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26529. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26530. };
  26531. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26532. var normalizer = 1.0;
  26533. var finalPosition = BABYLON.Tmp.Vector3[0];
  26534. var finalScaling = BABYLON.Tmp.Vector3[1];
  26535. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26536. var startIndex = 0;
  26537. var originalAnimation = holder.animations[0];
  26538. var originalValue = holder.originalValue;
  26539. var scale = 1;
  26540. if (holder.totalWeight < 1.0) {
  26541. // We need to mix the original value in
  26542. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26543. scale = 1.0 - holder.totalWeight;
  26544. }
  26545. else {
  26546. startIndex = 1;
  26547. // We need to normalize the weights
  26548. normalizer = holder.totalWeight;
  26549. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26550. scale = originalAnimation.weight / normalizer;
  26551. if (scale == 1) {
  26552. return originalAnimation.currentValue;
  26553. }
  26554. }
  26555. finalScaling.scaleInPlace(scale);
  26556. finalPosition.scaleInPlace(scale);
  26557. finalQuaternion.scaleInPlace(scale);
  26558. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26559. var runtimeAnimation = holder.animations[animIndex];
  26560. var scale = runtimeAnimation.weight / normalizer;
  26561. var currentPosition = BABYLON.Tmp.Vector3[2];
  26562. var currentScaling = BABYLON.Tmp.Vector3[3];
  26563. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26564. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26565. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26566. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26567. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26568. }
  26569. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26570. return originalAnimation._workValue;
  26571. };
  26572. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26573. var originalAnimation = holder.animations[0];
  26574. var originalValue = holder.originalValue;
  26575. if (holder.animations.length === 1) {
  26576. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26577. return refQuaternion;
  26578. }
  26579. var normalizer = 1.0;
  26580. var quaternions;
  26581. var weights;
  26582. if (holder.totalWeight < 1.0) {
  26583. var scale = 1.0 - holder.totalWeight;
  26584. quaternions = [];
  26585. weights = [];
  26586. quaternions.push(originalValue);
  26587. weights.push(scale);
  26588. }
  26589. else {
  26590. if (holder.animations.length === 2) { // Slerp as soon as we can
  26591. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26592. return refQuaternion;
  26593. }
  26594. quaternions = [];
  26595. weights = [];
  26596. normalizer = holder.totalWeight;
  26597. }
  26598. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26599. var runtimeAnimation = holder.animations[animIndex];
  26600. quaternions.push(runtimeAnimation.currentValue);
  26601. weights.push(runtimeAnimation.weight / normalizer);
  26602. }
  26603. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26604. var cumulativeAmount = 0;
  26605. var cumulativeQuaternion = null;
  26606. for (var index = 0; index < quaternions.length;) {
  26607. if (!cumulativeQuaternion) {
  26608. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26609. cumulativeQuaternion = refQuaternion;
  26610. cumulativeAmount = weights[index] + weights[index + 1];
  26611. index += 2;
  26612. continue;
  26613. }
  26614. cumulativeAmount += weights[index];
  26615. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26616. index++;
  26617. }
  26618. return cumulativeQuaternion;
  26619. };
  26620. Scene.prototype._processLateAnimationBindings = function () {
  26621. if (!this._registeredForLateAnimationBindings.length) {
  26622. return;
  26623. }
  26624. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26625. var target = this._registeredForLateAnimationBindings.data[index];
  26626. for (var path in target._lateAnimationHolders) {
  26627. var holder = target._lateAnimationHolders[path];
  26628. var originalAnimation = holder.animations[0];
  26629. var originalValue = holder.originalValue;
  26630. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26631. var finalValue = target[path];
  26632. if (matrixDecomposeMode) {
  26633. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26634. }
  26635. else {
  26636. var quaternionMode = originalValue.w !== undefined;
  26637. if (quaternionMode) {
  26638. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26639. }
  26640. else {
  26641. var startIndex = 0;
  26642. var normalizer = 1.0;
  26643. if (holder.totalWeight < 1.0) {
  26644. // We need to mix the original value in
  26645. if (originalValue.scale) {
  26646. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26647. }
  26648. else {
  26649. finalValue = originalValue * (1.0 - holder.totalWeight);
  26650. }
  26651. }
  26652. else {
  26653. // We need to normalize the weights
  26654. normalizer = holder.totalWeight;
  26655. var scale_1 = originalAnimation.weight / normalizer;
  26656. if (scale_1 !== 1) {
  26657. if (originalAnimation.currentValue.scale) {
  26658. finalValue = originalAnimation.currentValue.scale(scale_1);
  26659. }
  26660. else {
  26661. finalValue = originalAnimation.currentValue * scale_1;
  26662. }
  26663. }
  26664. else {
  26665. finalValue = originalAnimation.currentValue;
  26666. }
  26667. startIndex = 1;
  26668. }
  26669. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26670. var runtimeAnimation = holder.animations[animIndex];
  26671. var scale = runtimeAnimation.weight / normalizer;
  26672. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26673. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26674. }
  26675. else {
  26676. finalValue += runtimeAnimation.currentValue * scale;
  26677. }
  26678. }
  26679. }
  26680. }
  26681. target[path] = finalValue;
  26682. }
  26683. target._lateAnimationHolders = {};
  26684. }
  26685. this._registeredForLateAnimationBindings.reset();
  26686. };
  26687. // Matrix
  26688. /** @hidden */
  26689. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26690. this._useAlternateCameraConfiguration = active;
  26691. };
  26692. /**
  26693. * Gets the current view matrix
  26694. * @returns a Matrix
  26695. */
  26696. Scene.prototype.getViewMatrix = function () {
  26697. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26698. };
  26699. /**
  26700. * Gets the current projection matrix
  26701. * @returns a Matrix
  26702. */
  26703. Scene.prototype.getProjectionMatrix = function () {
  26704. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26705. };
  26706. /**
  26707. * Gets the current transform matrix
  26708. * @returns a Matrix made of View * Projection
  26709. */
  26710. Scene.prototype.getTransformMatrix = function () {
  26711. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26712. };
  26713. /**
  26714. * Sets the current transform matrix
  26715. * @param view defines the View matrix to use
  26716. * @param projection defines the Projection matrix to use
  26717. */
  26718. Scene.prototype.setTransformMatrix = function (view, projection) {
  26719. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26720. return;
  26721. }
  26722. this._viewUpdateFlag = view.updateFlag;
  26723. this._projectionUpdateFlag = projection.updateFlag;
  26724. this._viewMatrix = view;
  26725. this._projectionMatrix = projection;
  26726. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26727. // Update frustum
  26728. if (!this._frustumPlanes) {
  26729. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26730. }
  26731. else {
  26732. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26733. }
  26734. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26735. var otherCamera = this.activeCamera._alternateCamera;
  26736. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26737. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26738. }
  26739. if (this._sceneUbo.useUbo) {
  26740. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26741. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26742. this._sceneUbo.update();
  26743. }
  26744. };
  26745. /** @hidden */
  26746. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26747. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26748. return;
  26749. }
  26750. this._alternateViewUpdateFlag = view.updateFlag;
  26751. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26752. this._alternateViewMatrix = view;
  26753. this._alternateProjectionMatrix = projection;
  26754. if (!this._alternateTransformMatrix) {
  26755. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26756. }
  26757. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26758. if (!this._alternateSceneUbo) {
  26759. this._createAlternateUbo();
  26760. }
  26761. if (this._alternateSceneUbo.useUbo) {
  26762. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26763. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26764. this._alternateSceneUbo.update();
  26765. }
  26766. };
  26767. /**
  26768. * Gets the uniform buffer used to store scene data
  26769. * @returns a UniformBuffer
  26770. */
  26771. Scene.prototype.getSceneUniformBuffer = function () {
  26772. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26773. };
  26774. /**
  26775. * Gets an unique (relatively to the current scene) Id
  26776. * @returns an unique number for the scene
  26777. */
  26778. Scene.prototype.getUniqueId = function () {
  26779. var result = Scene._uniqueIdCounter;
  26780. Scene._uniqueIdCounter++;
  26781. return result;
  26782. };
  26783. /**
  26784. * Add a mesh to the list of scene's meshes
  26785. * @param newMesh defines the mesh to add
  26786. * @param recursive if all child meshes should also be added to the scene
  26787. */
  26788. Scene.prototype.addMesh = function (newMesh, recursive) {
  26789. var _this = this;
  26790. if (recursive === void 0) { recursive = false; }
  26791. this.meshes.push(newMesh);
  26792. //notify the collision coordinator
  26793. if (this.collisionCoordinator) {
  26794. this.collisionCoordinator.onMeshAdded(newMesh);
  26795. }
  26796. newMesh._resyncLightSources();
  26797. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26798. if (recursive) {
  26799. newMesh.getChildMeshes().forEach(function (m) {
  26800. _this.addMesh(m);
  26801. });
  26802. }
  26803. };
  26804. /**
  26805. * Remove a mesh for the list of scene's meshes
  26806. * @param toRemove defines the mesh to remove
  26807. * @param recursive if all child meshes should also be removed from the scene
  26808. * @returns the index where the mesh was in the mesh list
  26809. */
  26810. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26811. var _this = this;
  26812. if (recursive === void 0) { recursive = false; }
  26813. var index = this.meshes.indexOf(toRemove);
  26814. if (index !== -1) {
  26815. // Remove from the scene if mesh found
  26816. this.meshes.splice(index, 1);
  26817. }
  26818. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26819. if (recursive) {
  26820. toRemove.getChildMeshes().forEach(function (m) {
  26821. _this.removeMesh(m);
  26822. });
  26823. }
  26824. return index;
  26825. };
  26826. /**
  26827. * Add a transform node to the list of scene's transform nodes
  26828. * @param newTransformNode defines the transform node to add
  26829. */
  26830. Scene.prototype.addTransformNode = function (newTransformNode) {
  26831. this.transformNodes.push(newTransformNode);
  26832. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26833. };
  26834. /**
  26835. * Remove a transform node for the list of scene's transform nodes
  26836. * @param toRemove defines the transform node to remove
  26837. * @returns the index where the transform node was in the transform node list
  26838. */
  26839. Scene.prototype.removeTransformNode = function (toRemove) {
  26840. var index = this.transformNodes.indexOf(toRemove);
  26841. if (index !== -1) {
  26842. // Remove from the scene if found
  26843. this.transformNodes.splice(index, 1);
  26844. }
  26845. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26846. return index;
  26847. };
  26848. /**
  26849. * Remove a skeleton for the list of scene's skeletons
  26850. * @param toRemove defines the skeleton to remove
  26851. * @returns the index where the skeleton was in the skeleton list
  26852. */
  26853. Scene.prototype.removeSkeleton = function (toRemove) {
  26854. var index = this.skeletons.indexOf(toRemove);
  26855. if (index !== -1) {
  26856. // Remove from the scene if found
  26857. this.skeletons.splice(index, 1);
  26858. }
  26859. return index;
  26860. };
  26861. /**
  26862. * Remove a morph target for the list of scene's morph targets
  26863. * @param toRemove defines the morph target to remove
  26864. * @returns the index where the morph target was in the morph target list
  26865. */
  26866. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26867. var index = this.morphTargetManagers.indexOf(toRemove);
  26868. if (index !== -1) {
  26869. // Remove from the scene if found
  26870. this.morphTargetManagers.splice(index, 1);
  26871. }
  26872. return index;
  26873. };
  26874. /**
  26875. * Remove a light for the list of scene's lights
  26876. * @param toRemove defines the light to remove
  26877. * @returns the index where the light was in the light list
  26878. */
  26879. Scene.prototype.removeLight = function (toRemove) {
  26880. var index = this.lights.indexOf(toRemove);
  26881. if (index !== -1) {
  26882. // Remove from meshes
  26883. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26884. var mesh = _a[_i];
  26885. mesh._removeLightSource(toRemove);
  26886. }
  26887. // Remove from the scene if mesh found
  26888. this.lights.splice(index, 1);
  26889. this.sortLightsByPriority();
  26890. }
  26891. this.onLightRemovedObservable.notifyObservers(toRemove);
  26892. return index;
  26893. };
  26894. /**
  26895. * Remove a camera for the list of scene's cameras
  26896. * @param toRemove defines the camera to remove
  26897. * @returns the index where the camera was in the camera list
  26898. */
  26899. Scene.prototype.removeCamera = function (toRemove) {
  26900. var index = this.cameras.indexOf(toRemove);
  26901. if (index !== -1) {
  26902. // Remove from the scene if mesh found
  26903. this.cameras.splice(index, 1);
  26904. }
  26905. // Remove from activeCameras
  26906. var index2 = this.activeCameras.indexOf(toRemove);
  26907. if (index2 !== -1) {
  26908. // Remove from the scene if mesh found
  26909. this.activeCameras.splice(index2, 1);
  26910. }
  26911. // Reset the activeCamera
  26912. if (this.activeCamera === toRemove) {
  26913. if (this.cameras.length > 0) {
  26914. this.activeCamera = this.cameras[0];
  26915. }
  26916. else {
  26917. this.activeCamera = null;
  26918. }
  26919. }
  26920. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26921. return index;
  26922. };
  26923. /**
  26924. * Remove a particle system for the list of scene's particle systems
  26925. * @param toRemove defines the particle system to remove
  26926. * @returns the index where the particle system was in the particle system list
  26927. */
  26928. Scene.prototype.removeParticleSystem = function (toRemove) {
  26929. var index = this.particleSystems.indexOf(toRemove);
  26930. if (index !== -1) {
  26931. this.particleSystems.splice(index, 1);
  26932. }
  26933. return index;
  26934. };
  26935. /**
  26936. * Remove a animation for the list of scene's animations
  26937. * @param toRemove defines the animation to remove
  26938. * @returns the index where the animation was in the animation list
  26939. */
  26940. Scene.prototype.removeAnimation = function (toRemove) {
  26941. var index = this.animations.indexOf(toRemove);
  26942. if (index !== -1) {
  26943. this.animations.splice(index, 1);
  26944. }
  26945. return index;
  26946. };
  26947. /**
  26948. * Removes the given animation group from this scene.
  26949. * @param toRemove The animation group to remove
  26950. * @returns The index of the removed animation group
  26951. */
  26952. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26953. var index = this.animationGroups.indexOf(toRemove);
  26954. if (index !== -1) {
  26955. this.animationGroups.splice(index, 1);
  26956. }
  26957. return index;
  26958. };
  26959. /**
  26960. * Removes the given multi-material from this scene.
  26961. * @param toRemove The multi-material to remove
  26962. * @returns The index of the removed multi-material
  26963. */
  26964. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26965. var index = this.multiMaterials.indexOf(toRemove);
  26966. if (index !== -1) {
  26967. this.multiMaterials.splice(index, 1);
  26968. }
  26969. return index;
  26970. };
  26971. /**
  26972. * Removes the given material from this scene.
  26973. * @param toRemove The material to remove
  26974. * @returns The index of the removed material
  26975. */
  26976. Scene.prototype.removeMaterial = function (toRemove) {
  26977. var index = this.materials.indexOf(toRemove);
  26978. if (index !== -1) {
  26979. this.materials.splice(index, 1);
  26980. }
  26981. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  26982. return index;
  26983. };
  26984. /**
  26985. * Removes the given action manager from this scene.
  26986. * @param toRemove The action manager to remove
  26987. * @returns The index of the removed action manager
  26988. */
  26989. Scene.prototype.removeActionManager = function (toRemove) {
  26990. var index = this.actionManagers.indexOf(toRemove);
  26991. if (index !== -1) {
  26992. this.actionManagers.splice(index, 1);
  26993. }
  26994. return index;
  26995. };
  26996. /**
  26997. * Removes the given texture from this scene.
  26998. * @param toRemove The texture to remove
  26999. * @returns The index of the removed texture
  27000. */
  27001. Scene.prototype.removeTexture = function (toRemove) {
  27002. var index = this.textures.indexOf(toRemove);
  27003. if (index !== -1) {
  27004. this.textures.splice(index, 1);
  27005. }
  27006. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27007. return index;
  27008. };
  27009. /**
  27010. * Adds the given light to this scene
  27011. * @param newLight The light to add
  27012. */
  27013. Scene.prototype.addLight = function (newLight) {
  27014. this.lights.push(newLight);
  27015. this.sortLightsByPriority();
  27016. // Add light to all meshes (To support if the light is removed and then readded)
  27017. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27018. var mesh = _a[_i];
  27019. if (mesh._lightSources.indexOf(newLight) === -1) {
  27020. mesh._lightSources.push(newLight);
  27021. mesh._resyncLightSources();
  27022. }
  27023. }
  27024. this.onNewLightAddedObservable.notifyObservers(newLight);
  27025. };
  27026. /**
  27027. * Sorts the list list based on light priorities
  27028. */
  27029. Scene.prototype.sortLightsByPriority = function () {
  27030. if (this.requireLightSorting) {
  27031. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27032. }
  27033. };
  27034. /**
  27035. * Adds the given camera to this scene
  27036. * @param newCamera The camera to add
  27037. */
  27038. Scene.prototype.addCamera = function (newCamera) {
  27039. this.cameras.push(newCamera);
  27040. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27041. };
  27042. /**
  27043. * Adds the given skeleton to this scene
  27044. * @param newSkeleton The skeleton to add
  27045. */
  27046. Scene.prototype.addSkeleton = function (newSkeleton) {
  27047. this.skeletons.push(newSkeleton);
  27048. };
  27049. /**
  27050. * Adds the given particle system to this scene
  27051. * @param newParticleSystem The particle system to add
  27052. */
  27053. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27054. this.particleSystems.push(newParticleSystem);
  27055. };
  27056. /**
  27057. * Adds the given animation to this scene
  27058. * @param newAnimation The animation to add
  27059. */
  27060. Scene.prototype.addAnimation = function (newAnimation) {
  27061. this.animations.push(newAnimation);
  27062. };
  27063. /**
  27064. * Adds the given animation group to this scene.
  27065. * @param newAnimationGroup The animation group to add
  27066. */
  27067. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27068. this.animationGroups.push(newAnimationGroup);
  27069. };
  27070. /**
  27071. * Adds the given multi-material to this scene
  27072. * @param newMultiMaterial The multi-material to add
  27073. */
  27074. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27075. this.multiMaterials.push(newMultiMaterial);
  27076. };
  27077. /**
  27078. * Adds the given material to this scene
  27079. * @param newMaterial The material to add
  27080. */
  27081. Scene.prototype.addMaterial = function (newMaterial) {
  27082. this.materials.push(newMaterial);
  27083. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27084. };
  27085. /**
  27086. * Adds the given morph target to this scene
  27087. * @param newMorphTargetManager The morph target to add
  27088. */
  27089. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27090. this.morphTargetManagers.push(newMorphTargetManager);
  27091. };
  27092. /**
  27093. * Adds the given geometry to this scene
  27094. * @param newGeometry The geometry to add
  27095. */
  27096. Scene.prototype.addGeometry = function (newGeometry) {
  27097. this.geometries.push(newGeometry);
  27098. };
  27099. /**
  27100. * Adds the given action manager to this scene
  27101. * @param newActionManager The action manager to add
  27102. */
  27103. Scene.prototype.addActionManager = function (newActionManager) {
  27104. this.actionManagers.push(newActionManager);
  27105. };
  27106. /**
  27107. * Adds the given texture to this scene.
  27108. * @param newTexture The texture to add
  27109. */
  27110. Scene.prototype.addTexture = function (newTexture) {
  27111. this.textures.push(newTexture);
  27112. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27113. };
  27114. /**
  27115. * Switch active camera
  27116. * @param newCamera defines the new active camera
  27117. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27118. */
  27119. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27120. if (attachControl === void 0) { attachControl = true; }
  27121. var canvas = this._engine.getRenderingCanvas();
  27122. if (!canvas) {
  27123. return;
  27124. }
  27125. if (this.activeCamera) {
  27126. this.activeCamera.detachControl(canvas);
  27127. }
  27128. this.activeCamera = newCamera;
  27129. if (attachControl) {
  27130. newCamera.attachControl(canvas);
  27131. }
  27132. };
  27133. /**
  27134. * sets the active camera of the scene using its ID
  27135. * @param id defines the camera's ID
  27136. * @return the new active camera or null if none found.
  27137. */
  27138. Scene.prototype.setActiveCameraByID = function (id) {
  27139. var camera = this.getCameraByID(id);
  27140. if (camera) {
  27141. this.activeCamera = camera;
  27142. return camera;
  27143. }
  27144. return null;
  27145. };
  27146. /**
  27147. * sets the active camera of the scene using its name
  27148. * @param name defines the camera's name
  27149. * @returns the new active camera or null if none found.
  27150. */
  27151. Scene.prototype.setActiveCameraByName = function (name) {
  27152. var camera = this.getCameraByName(name);
  27153. if (camera) {
  27154. this.activeCamera = camera;
  27155. return camera;
  27156. }
  27157. return null;
  27158. };
  27159. /**
  27160. * get an animation group using its name
  27161. * @param name defines the material's name
  27162. * @return the animation group or null if none found.
  27163. */
  27164. Scene.prototype.getAnimationGroupByName = function (name) {
  27165. for (var index = 0; index < this.animationGroups.length; index++) {
  27166. if (this.animationGroups[index].name === name) {
  27167. return this.animationGroups[index];
  27168. }
  27169. }
  27170. return null;
  27171. };
  27172. /**
  27173. * get a material using its id
  27174. * @param id defines the material's ID
  27175. * @return the material or null if none found.
  27176. */
  27177. Scene.prototype.getMaterialByID = function (id) {
  27178. for (var index = 0; index < this.materials.length; index++) {
  27179. if (this.materials[index].id === id) {
  27180. return this.materials[index];
  27181. }
  27182. }
  27183. return null;
  27184. };
  27185. /**
  27186. * Gets a material using its name
  27187. * @param name defines the material's name
  27188. * @return the material or null if none found.
  27189. */
  27190. Scene.prototype.getMaterialByName = function (name) {
  27191. for (var index = 0; index < this.materials.length; index++) {
  27192. if (this.materials[index].name === name) {
  27193. return this.materials[index];
  27194. }
  27195. }
  27196. return null;
  27197. };
  27198. /**
  27199. * Gets a camera using its id
  27200. * @param id defines the id to look for
  27201. * @returns the camera or null if not found
  27202. */
  27203. Scene.prototype.getCameraByID = function (id) {
  27204. for (var index = 0; index < this.cameras.length; index++) {
  27205. if (this.cameras[index].id === id) {
  27206. return this.cameras[index];
  27207. }
  27208. }
  27209. return null;
  27210. };
  27211. /**
  27212. * Gets a camera using its unique id
  27213. * @param uniqueId defines the unique id to look for
  27214. * @returns the camera or null if not found
  27215. */
  27216. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27217. for (var index = 0; index < this.cameras.length; index++) {
  27218. if (this.cameras[index].uniqueId === uniqueId) {
  27219. return this.cameras[index];
  27220. }
  27221. }
  27222. return null;
  27223. };
  27224. /**
  27225. * Gets a camera using its name
  27226. * @param name defines the camera's name
  27227. * @return the camera or null if none found.
  27228. */
  27229. Scene.prototype.getCameraByName = function (name) {
  27230. for (var index = 0; index < this.cameras.length; index++) {
  27231. if (this.cameras[index].name === name) {
  27232. return this.cameras[index];
  27233. }
  27234. }
  27235. return null;
  27236. };
  27237. /**
  27238. * Gets a bone using its id
  27239. * @param id defines the bone's id
  27240. * @return the bone or null if not found
  27241. */
  27242. Scene.prototype.getBoneByID = function (id) {
  27243. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27244. var skeleton = this.skeletons[skeletonIndex];
  27245. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27246. if (skeleton.bones[boneIndex].id === id) {
  27247. return skeleton.bones[boneIndex];
  27248. }
  27249. }
  27250. }
  27251. return null;
  27252. };
  27253. /**
  27254. * Gets a bone using its id
  27255. * @param name defines the bone's name
  27256. * @return the bone or null if not found
  27257. */
  27258. Scene.prototype.getBoneByName = function (name) {
  27259. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27260. var skeleton = this.skeletons[skeletonIndex];
  27261. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27262. if (skeleton.bones[boneIndex].name === name) {
  27263. return skeleton.bones[boneIndex];
  27264. }
  27265. }
  27266. }
  27267. return null;
  27268. };
  27269. /**
  27270. * Gets a light node using its name
  27271. * @param name defines the the light's name
  27272. * @return the light or null if none found.
  27273. */
  27274. Scene.prototype.getLightByName = function (name) {
  27275. for (var index = 0; index < this.lights.length; index++) {
  27276. if (this.lights[index].name === name) {
  27277. return this.lights[index];
  27278. }
  27279. }
  27280. return null;
  27281. };
  27282. /**
  27283. * Gets a light node using its id
  27284. * @param id defines the light's id
  27285. * @return the light or null if none found.
  27286. */
  27287. Scene.prototype.getLightByID = function (id) {
  27288. for (var index = 0; index < this.lights.length; index++) {
  27289. if (this.lights[index].id === id) {
  27290. return this.lights[index];
  27291. }
  27292. }
  27293. return null;
  27294. };
  27295. /**
  27296. * Gets a light node using its scene-generated unique ID
  27297. * @param uniqueId defines the light's unique id
  27298. * @return the light or null if none found.
  27299. */
  27300. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27301. for (var index = 0; index < this.lights.length; index++) {
  27302. if (this.lights[index].uniqueId === uniqueId) {
  27303. return this.lights[index];
  27304. }
  27305. }
  27306. return null;
  27307. };
  27308. /**
  27309. * Gets a particle system by id
  27310. * @param id defines the particle system id
  27311. * @return the corresponding system or null if none found
  27312. */
  27313. Scene.prototype.getParticleSystemByID = function (id) {
  27314. for (var index = 0; index < this.particleSystems.length; index++) {
  27315. if (this.particleSystems[index].id === id) {
  27316. return this.particleSystems[index];
  27317. }
  27318. }
  27319. return null;
  27320. };
  27321. /**
  27322. * Gets a geometry using its ID
  27323. * @param id defines the geometry's id
  27324. * @return the geometry or null if none found.
  27325. */
  27326. Scene.prototype.getGeometryByID = function (id) {
  27327. for (var index = 0; index < this.geometries.length; index++) {
  27328. if (this.geometries[index].id === id) {
  27329. return this.geometries[index];
  27330. }
  27331. }
  27332. return null;
  27333. };
  27334. /**
  27335. * Add a new geometry to this scene
  27336. * @param geometry defines the geometry to be added to the scene.
  27337. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27338. * @return a boolean defining if the geometry was added or not
  27339. */
  27340. Scene.prototype.pushGeometry = function (geometry, force) {
  27341. if (!force && this.getGeometryByID(geometry.id)) {
  27342. return false;
  27343. }
  27344. this.geometries.push(geometry);
  27345. //notify the collision coordinator
  27346. if (this.collisionCoordinator) {
  27347. this.collisionCoordinator.onGeometryAdded(geometry);
  27348. }
  27349. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27350. return true;
  27351. };
  27352. /**
  27353. * Removes an existing geometry
  27354. * @param geometry defines the geometry to be removed from the scene
  27355. * @return a boolean defining if the geometry was removed or not
  27356. */
  27357. Scene.prototype.removeGeometry = function (geometry) {
  27358. var index = this.geometries.indexOf(geometry);
  27359. if (index > -1) {
  27360. this.geometries.splice(index, 1);
  27361. //notify the collision coordinator
  27362. if (this.collisionCoordinator) {
  27363. this.collisionCoordinator.onGeometryDeleted(geometry);
  27364. }
  27365. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27366. return true;
  27367. }
  27368. return false;
  27369. };
  27370. /**
  27371. * Gets the list of geometries attached to the scene
  27372. * @returns an array of Geometry
  27373. */
  27374. Scene.prototype.getGeometries = function () {
  27375. return this.geometries;
  27376. };
  27377. /**
  27378. * Gets the first added mesh found of a given ID
  27379. * @param id defines the id to search for
  27380. * @return the mesh found or null if not found at all
  27381. */
  27382. Scene.prototype.getMeshByID = function (id) {
  27383. for (var index = 0; index < this.meshes.length; index++) {
  27384. if (this.meshes[index].id === id) {
  27385. return this.meshes[index];
  27386. }
  27387. }
  27388. return null;
  27389. };
  27390. /**
  27391. * Gets a list of meshes using their id
  27392. * @param id defines the id to search for
  27393. * @returns a list of meshes
  27394. */
  27395. Scene.prototype.getMeshesByID = function (id) {
  27396. return this.meshes.filter(function (m) {
  27397. return m.id === id;
  27398. });
  27399. };
  27400. /**
  27401. * Gets the first added transform node found of a given ID
  27402. * @param id defines the id to search for
  27403. * @return the found transform node or null if not found at all.
  27404. */
  27405. Scene.prototype.getTransformNodeByID = function (id) {
  27406. for (var index = 0; index < this.transformNodes.length; index++) {
  27407. if (this.transformNodes[index].id === id) {
  27408. return this.transformNodes[index];
  27409. }
  27410. }
  27411. return null;
  27412. };
  27413. /**
  27414. * Gets a list of transform nodes using their id
  27415. * @param id defines the id to search for
  27416. * @returns a list of transform nodes
  27417. */
  27418. Scene.prototype.getTransformNodesByID = function (id) {
  27419. return this.transformNodes.filter(function (m) {
  27420. return m.id === id;
  27421. });
  27422. };
  27423. /**
  27424. * Gets a mesh with its auto-generated unique id
  27425. * @param uniqueId defines the unique id to search for
  27426. * @return the found mesh or null if not found at all.
  27427. */
  27428. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27429. for (var index = 0; index < this.meshes.length; index++) {
  27430. if (this.meshes[index].uniqueId === uniqueId) {
  27431. return this.meshes[index];
  27432. }
  27433. }
  27434. return null;
  27435. };
  27436. /**
  27437. * Gets a the last added mesh using a given id
  27438. * @param id defines the id to search for
  27439. * @return the found mesh or null if not found at all.
  27440. */
  27441. Scene.prototype.getLastMeshByID = function (id) {
  27442. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27443. if (this.meshes[index].id === id) {
  27444. return this.meshes[index];
  27445. }
  27446. }
  27447. return null;
  27448. };
  27449. /**
  27450. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27451. * @param id defines the id to search for
  27452. * @return the found node or null if not found at all
  27453. */
  27454. Scene.prototype.getLastEntryByID = function (id) {
  27455. var index;
  27456. for (index = this.meshes.length - 1; index >= 0; index--) {
  27457. if (this.meshes[index].id === id) {
  27458. return this.meshes[index];
  27459. }
  27460. }
  27461. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27462. if (this.transformNodes[index].id === id) {
  27463. return this.transformNodes[index];
  27464. }
  27465. }
  27466. for (index = this.cameras.length - 1; index >= 0; index--) {
  27467. if (this.cameras[index].id === id) {
  27468. return this.cameras[index];
  27469. }
  27470. }
  27471. for (index = this.lights.length - 1; index >= 0; index--) {
  27472. if (this.lights[index].id === id) {
  27473. return this.lights[index];
  27474. }
  27475. }
  27476. return null;
  27477. };
  27478. /**
  27479. * Gets a node (Mesh, Camera, Light) using a given id
  27480. * @param id defines the id to search for
  27481. * @return the found node or null if not found at all
  27482. */
  27483. Scene.prototype.getNodeByID = function (id) {
  27484. var mesh = this.getMeshByID(id);
  27485. if (mesh) {
  27486. return mesh;
  27487. }
  27488. var light = this.getLightByID(id);
  27489. if (light) {
  27490. return light;
  27491. }
  27492. var camera = this.getCameraByID(id);
  27493. if (camera) {
  27494. return camera;
  27495. }
  27496. var bone = this.getBoneByID(id);
  27497. return bone;
  27498. };
  27499. /**
  27500. * Gets a node (Mesh, Camera, Light) using a given name
  27501. * @param name defines the name to search for
  27502. * @return the found node or null if not found at all.
  27503. */
  27504. Scene.prototype.getNodeByName = function (name) {
  27505. var mesh = this.getMeshByName(name);
  27506. if (mesh) {
  27507. return mesh;
  27508. }
  27509. var light = this.getLightByName(name);
  27510. if (light) {
  27511. return light;
  27512. }
  27513. var camera = this.getCameraByName(name);
  27514. if (camera) {
  27515. return camera;
  27516. }
  27517. var bone = this.getBoneByName(name);
  27518. return bone;
  27519. };
  27520. /**
  27521. * Gets a mesh using a given name
  27522. * @param name defines the name to search for
  27523. * @return the found mesh or null if not found at all.
  27524. */
  27525. Scene.prototype.getMeshByName = function (name) {
  27526. for (var index = 0; index < this.meshes.length; index++) {
  27527. if (this.meshes[index].name === name) {
  27528. return this.meshes[index];
  27529. }
  27530. }
  27531. return null;
  27532. };
  27533. /**
  27534. * Gets a transform node using a given name
  27535. * @param name defines the name to search for
  27536. * @return the found transform node or null if not found at all.
  27537. */
  27538. Scene.prototype.getTransformNodeByName = function (name) {
  27539. for (var index = 0; index < this.transformNodes.length; index++) {
  27540. if (this.transformNodes[index].name === name) {
  27541. return this.transformNodes[index];
  27542. }
  27543. }
  27544. return null;
  27545. };
  27546. /**
  27547. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27548. * @param id defines the id to search for
  27549. * @return the found skeleton or null if not found at all.
  27550. */
  27551. Scene.prototype.getLastSkeletonByID = function (id) {
  27552. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27553. if (this.skeletons[index].id === id) {
  27554. return this.skeletons[index];
  27555. }
  27556. }
  27557. return null;
  27558. };
  27559. /**
  27560. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27561. * @param id defines the id to search for
  27562. * @return the found skeleton or null if not found at all.
  27563. */
  27564. Scene.prototype.getSkeletonById = function (id) {
  27565. for (var index = 0; index < this.skeletons.length; index++) {
  27566. if (this.skeletons[index].id === id) {
  27567. return this.skeletons[index];
  27568. }
  27569. }
  27570. return null;
  27571. };
  27572. /**
  27573. * Gets a skeleton using a given name
  27574. * @param name defines the name to search for
  27575. * @return the found skeleton or null if not found at all.
  27576. */
  27577. Scene.prototype.getSkeletonByName = function (name) {
  27578. for (var index = 0; index < this.skeletons.length; index++) {
  27579. if (this.skeletons[index].name === name) {
  27580. return this.skeletons[index];
  27581. }
  27582. }
  27583. return null;
  27584. };
  27585. /**
  27586. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27587. * @param id defines the id to search for
  27588. * @return the found morph target manager or null if not found at all.
  27589. */
  27590. Scene.prototype.getMorphTargetManagerById = function (id) {
  27591. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27592. if (this.morphTargetManagers[index].uniqueId === id) {
  27593. return this.morphTargetManagers[index];
  27594. }
  27595. }
  27596. return null;
  27597. };
  27598. /**
  27599. * Gets a boolean indicating if the given mesh is active
  27600. * @param mesh defines the mesh to look for
  27601. * @returns true if the mesh is in the active list
  27602. */
  27603. Scene.prototype.isActiveMesh = function (mesh) {
  27604. return (this._activeMeshes.indexOf(mesh) !== -1);
  27605. };
  27606. Object.defineProperty(Scene.prototype, "uid", {
  27607. /**
  27608. * Return a unique id as a string which can serve as an identifier for the scene
  27609. */
  27610. get: function () {
  27611. if (!this._uid) {
  27612. this._uid = BABYLON.Tools.RandomId();
  27613. }
  27614. return this._uid;
  27615. },
  27616. enumerable: true,
  27617. configurable: true
  27618. });
  27619. /**
  27620. * Add an externaly attached data from its key.
  27621. * This method call will fail and return false, if such key already exists.
  27622. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27623. * @param key the unique key that identifies the data
  27624. * @param data the data object to associate to the key for this Engine instance
  27625. * @return true if no such key were already present and the data was added successfully, false otherwise
  27626. */
  27627. Scene.prototype.addExternalData = function (key, data) {
  27628. if (!this._externalData) {
  27629. this._externalData = new BABYLON.StringDictionary();
  27630. }
  27631. return this._externalData.add(key, data);
  27632. };
  27633. /**
  27634. * Get an externaly attached data from its key
  27635. * @param key the unique key that identifies the data
  27636. * @return the associated data, if present (can be null), or undefined if not present
  27637. */
  27638. Scene.prototype.getExternalData = function (key) {
  27639. if (!this._externalData) {
  27640. return null;
  27641. }
  27642. return this._externalData.get(key);
  27643. };
  27644. /**
  27645. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27646. * @param key the unique key that identifies the data
  27647. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27648. * @return the associated data, can be null if the factory returned null.
  27649. */
  27650. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27651. if (!this._externalData) {
  27652. this._externalData = new BABYLON.StringDictionary();
  27653. }
  27654. return this._externalData.getOrAddWithFactory(key, factory);
  27655. };
  27656. /**
  27657. * Remove an externaly attached data from the Engine instance
  27658. * @param key the unique key that identifies the data
  27659. * @return true if the data was successfully removed, false if it doesn't exist
  27660. */
  27661. Scene.prototype.removeExternalData = function (key) {
  27662. return this._externalData.remove(key);
  27663. };
  27664. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27665. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27666. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27667. var step = _a[_i];
  27668. step.action(mesh, subMesh);
  27669. }
  27670. var material = subMesh.getMaterial();
  27671. if (material !== null && material !== undefined) {
  27672. // Render targets
  27673. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27674. if (this._processedMaterials.indexOf(material) === -1) {
  27675. this._processedMaterials.push(material);
  27676. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27677. }
  27678. }
  27679. // Dispatch
  27680. this._activeIndices.addCount(subMesh.indexCount, false);
  27681. this._renderingManager.dispatch(subMesh, mesh, material);
  27682. }
  27683. }
  27684. };
  27685. /**
  27686. * Clear the processed materials smart array preventing retention point in material dispose.
  27687. */
  27688. Scene.prototype.freeProcessedMaterials = function () {
  27689. this._processedMaterials.dispose();
  27690. };
  27691. /**
  27692. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27693. */
  27694. Scene.prototype.freeActiveMeshes = function () {
  27695. this._activeMeshes.dispose();
  27696. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27697. this.activeCamera._activeMeshes.dispose();
  27698. }
  27699. if (this.activeCameras) {
  27700. for (var i = 0; i < this.activeCameras.length; i++) {
  27701. var activeCamera = this.activeCameras[i];
  27702. if (activeCamera && activeCamera._activeMeshes) {
  27703. activeCamera._activeMeshes.dispose();
  27704. }
  27705. }
  27706. }
  27707. };
  27708. /**
  27709. * Clear the info related to rendering groups preventing retention points during dispose.
  27710. */
  27711. Scene.prototype.freeRenderingGroups = function () {
  27712. if (this._renderingManager) {
  27713. this._renderingManager.freeRenderingGroups();
  27714. }
  27715. if (this.textures) {
  27716. for (var i = 0; i < this.textures.length; i++) {
  27717. var texture = this.textures[i];
  27718. if (texture && texture.renderList) {
  27719. texture.freeRenderingGroups();
  27720. }
  27721. }
  27722. }
  27723. };
  27724. /** @hidden */
  27725. Scene.prototype._isInIntermediateRendering = function () {
  27726. return this._intermediateRendering;
  27727. };
  27728. /**
  27729. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27730. * @returns the current scene
  27731. */
  27732. Scene.prototype.freezeActiveMeshes = function () {
  27733. if (!this.activeCamera) {
  27734. return this;
  27735. }
  27736. if (!this._frustumPlanes) {
  27737. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27738. }
  27739. this._evaluateActiveMeshes();
  27740. this._activeMeshesFrozen = true;
  27741. return this;
  27742. };
  27743. /**
  27744. * Use this function to restart evaluating active meshes on every frame
  27745. * @returns the current scene
  27746. */
  27747. Scene.prototype.unfreezeActiveMeshes = function () {
  27748. this._activeMeshesFrozen = false;
  27749. return this;
  27750. };
  27751. Scene.prototype._evaluateActiveMeshes = function () {
  27752. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27753. return;
  27754. }
  27755. if (!this.activeCamera) {
  27756. return;
  27757. }
  27758. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27759. this.activeCamera._activeMeshes.reset();
  27760. this._activeMeshes.reset();
  27761. this._renderingManager.reset();
  27762. this._processedMaterials.reset();
  27763. this._activeParticleSystems.reset();
  27764. this._activeSkeletons.reset();
  27765. this._softwareSkinnedMeshes.reset();
  27766. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27767. var step = _a[_i];
  27768. step.action();
  27769. }
  27770. // Determine mesh candidates
  27771. var meshes = this.getActiveMeshCandidates();
  27772. // Check each mesh
  27773. var len = meshes.length;
  27774. for (var i = 0; i < len; i++) {
  27775. var mesh = meshes.data[i];
  27776. if (mesh.isBlocked) {
  27777. continue;
  27778. }
  27779. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27780. if (!mesh.isReady() || !mesh.isEnabled()) {
  27781. continue;
  27782. }
  27783. mesh.computeWorldMatrix();
  27784. // Intersections
  27785. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27786. this._meshesForIntersections.pushNoDuplicate(mesh);
  27787. }
  27788. // Switch to current LOD
  27789. var meshLOD = mesh.getLOD(this.activeCamera);
  27790. if (meshLOD === undefined || meshLOD === null) {
  27791. continue;
  27792. }
  27793. mesh._preActivate();
  27794. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27795. this._activeMeshes.push(mesh);
  27796. this.activeCamera._activeMeshes.push(mesh);
  27797. mesh._activate(this._renderId);
  27798. if (meshLOD !== mesh) {
  27799. meshLOD._activate(this._renderId);
  27800. }
  27801. this._activeMesh(mesh, meshLOD);
  27802. }
  27803. }
  27804. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27805. // Particle systems
  27806. if (this.particlesEnabled) {
  27807. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27808. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27809. var particleSystem = this.particleSystems[particleIndex];
  27810. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27811. continue;
  27812. }
  27813. var emitter = particleSystem.emitter;
  27814. if (!emitter.position || emitter.isEnabled()) {
  27815. this._activeParticleSystems.push(particleSystem);
  27816. particleSystem.animate();
  27817. this._renderingManager.dispatchParticles(particleSystem);
  27818. }
  27819. }
  27820. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27821. }
  27822. };
  27823. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27824. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27825. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27826. mesh.skeleton.prepare();
  27827. }
  27828. if (!mesh.computeBonesUsingShaders) {
  27829. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27830. }
  27831. }
  27832. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27833. var step = _a[_i];
  27834. step.action(sourceMesh, mesh);
  27835. }
  27836. if (mesh !== undefined && mesh !== null
  27837. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27838. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27839. var len = subMeshes.length;
  27840. for (var i = 0; i < len; i++) {
  27841. var subMesh = subMeshes.data[i];
  27842. this._evaluateSubMesh(subMesh, mesh);
  27843. }
  27844. }
  27845. };
  27846. /**
  27847. * Update the transform matrix to update from the current active camera
  27848. * @param force defines a boolean used to force the update even if cache is up to date
  27849. */
  27850. Scene.prototype.updateTransformMatrix = function (force) {
  27851. if (!this.activeCamera) {
  27852. return;
  27853. }
  27854. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27855. };
  27856. /**
  27857. * 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)
  27858. * @param alternateCamera defines the camera to use
  27859. */
  27860. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27861. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27862. };
  27863. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27864. if (camera && camera._skipRendering) {
  27865. return;
  27866. }
  27867. var engine = this._engine;
  27868. this.activeCamera = camera;
  27869. if (!this.activeCamera)
  27870. throw new Error("Active camera not set");
  27871. // Viewport
  27872. engine.setViewport(this.activeCamera.viewport);
  27873. // Camera
  27874. this.resetCachedMaterial();
  27875. this._renderId++;
  27876. this.updateTransformMatrix();
  27877. if (camera._alternateCamera) {
  27878. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27879. this._alternateRendering = true;
  27880. }
  27881. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27882. // Meshes
  27883. this._evaluateActiveMeshes();
  27884. // Software skinning
  27885. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27886. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27887. mesh.applySkeleton(mesh.skeleton);
  27888. }
  27889. // Render targets
  27890. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27891. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27892. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27893. }
  27894. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27895. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27896. }
  27897. // Collects render targets from external components.
  27898. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27899. var step = _a[_i];
  27900. step.action(this._renderTargets);
  27901. }
  27902. if (this.renderTargetsEnabled) {
  27903. this._intermediateRendering = true;
  27904. if (this._renderTargets.length > 0) {
  27905. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27906. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27907. var renderTarget = this._renderTargets.data[renderIndex];
  27908. if (renderTarget._shouldRender()) {
  27909. this._renderId++;
  27910. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27911. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27912. }
  27913. }
  27914. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27915. this._renderId++;
  27916. }
  27917. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27918. var step = _c[_b];
  27919. step.action(this.activeCamera);
  27920. }
  27921. this._intermediateRendering = false;
  27922. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27923. }
  27924. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27925. // Prepare Frame
  27926. if (this.postProcessManager) {
  27927. this.postProcessManager._prepareFrame();
  27928. }
  27929. // Before Camera Draw
  27930. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27931. var step = _e[_d];
  27932. step.action(this.activeCamera);
  27933. }
  27934. // Render
  27935. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27936. this._renderingManager.render(null, null, true, true);
  27937. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27938. // After Camera Draw
  27939. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27940. var step = _g[_f];
  27941. step.action(this.activeCamera);
  27942. }
  27943. // Finalize frame
  27944. if (this.postProcessManager) {
  27945. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27946. }
  27947. // Reset some special arrays
  27948. this._renderTargets.reset();
  27949. this._alternateRendering = false;
  27950. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27951. };
  27952. Scene.prototype._processSubCameras = function (camera) {
  27953. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27954. this._renderForCamera(camera);
  27955. return;
  27956. }
  27957. // rig cameras
  27958. for (var index = 0; index < camera._rigCameras.length; index++) {
  27959. this._renderForCamera(camera._rigCameras[index], camera);
  27960. }
  27961. this.activeCamera = camera;
  27962. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27963. };
  27964. Scene.prototype._checkIntersections = function () {
  27965. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27966. var sourceMesh = this._meshesForIntersections.data[index];
  27967. if (!sourceMesh.actionManager) {
  27968. continue;
  27969. }
  27970. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27971. var action = sourceMesh.actionManager.actions[actionIndex];
  27972. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27973. var parameters = action.getTriggerParameter();
  27974. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27975. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27976. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27977. if (areIntersecting && currentIntersectionInProgress === -1) {
  27978. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27979. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27980. sourceMesh._intersectionsInProgress.push(otherMesh);
  27981. }
  27982. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27983. sourceMesh._intersectionsInProgress.push(otherMesh);
  27984. }
  27985. }
  27986. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27987. //They intersected, and now they don't.
  27988. //is this trigger an exit trigger? execute an event.
  27989. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27990. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27991. }
  27992. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27993. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27994. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27995. return otherMesh === parameterMesh;
  27996. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27997. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27998. }
  27999. }
  28000. }
  28001. }
  28002. }
  28003. };
  28004. /** @hidden */
  28005. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28006. // Do nothing. Code will be replaced if physics engine component is referenced
  28007. };
  28008. /**
  28009. * Render the scene
  28010. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28011. */
  28012. Scene.prototype.render = function (updateCameras) {
  28013. if (updateCameras === void 0) { updateCameras = true; }
  28014. if (this.isDisposed) {
  28015. return;
  28016. }
  28017. this._frameId++;
  28018. // Register components that have been associated lately to the scene.
  28019. this._registerTransientComponents();
  28020. this._activeParticles.fetchNewFrame();
  28021. this._totalVertices.fetchNewFrame();
  28022. this._activeIndices.fetchNewFrame();
  28023. this._activeBones.fetchNewFrame();
  28024. this._meshesForIntersections.reset();
  28025. this.resetCachedMaterial();
  28026. this.onBeforeAnimationsObservable.notifyObservers(this);
  28027. // Actions
  28028. if (this.actionManager) {
  28029. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28030. }
  28031. if (this._engine.isDeterministicLockStep()) {
  28032. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28033. var defaultFPS = (60.0 / 1000.0);
  28034. var defaultFrameTime = this.getDeterministicFrameTime();
  28035. var stepsTaken = 0;
  28036. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28037. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28038. internalSteps = Math.min(internalSteps, maxSubSteps);
  28039. do {
  28040. this.onBeforeStepObservable.notifyObservers(this);
  28041. // Animations
  28042. this._animationRatio = defaultFrameTime * defaultFPS;
  28043. this._animate();
  28044. this.onAfterAnimationsObservable.notifyObservers(this);
  28045. // Physics
  28046. this._advancePhysicsEngineStep(defaultFrameTime);
  28047. this.onAfterStepObservable.notifyObservers(this);
  28048. this._currentStepId++;
  28049. stepsTaken++;
  28050. deltaTime -= defaultFrameTime;
  28051. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28052. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28053. }
  28054. else {
  28055. // Animations
  28056. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28057. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28058. this._animate();
  28059. this.onAfterAnimationsObservable.notifyObservers(this);
  28060. // Physics
  28061. this._advancePhysicsEngineStep(deltaTime);
  28062. }
  28063. // Before camera update steps
  28064. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28065. var step = _a[_i];
  28066. step.action();
  28067. }
  28068. // Update Cameras
  28069. if (updateCameras) {
  28070. if (this.activeCameras.length > 0) {
  28071. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28072. var camera = this.activeCameras[cameraIndex];
  28073. camera.update();
  28074. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28075. // rig cameras
  28076. for (var index = 0; index < camera._rigCameras.length; index++) {
  28077. camera._rigCameras[index].update();
  28078. }
  28079. }
  28080. }
  28081. }
  28082. else if (this.activeCamera) {
  28083. this.activeCamera.update();
  28084. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28085. // rig cameras
  28086. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28087. this.activeCamera._rigCameras[index].update();
  28088. }
  28089. }
  28090. }
  28091. }
  28092. // Before render
  28093. this.onBeforeRenderObservable.notifyObservers(this);
  28094. // Customs render targets
  28095. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28096. var engine = this.getEngine();
  28097. var currentActiveCamera = this.activeCamera;
  28098. if (this.renderTargetsEnabled) {
  28099. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28100. this._intermediateRendering = true;
  28101. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28102. var renderTarget = this.customRenderTargets[customIndex];
  28103. if (renderTarget._shouldRender()) {
  28104. this._renderId++;
  28105. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28106. if (!this.activeCamera)
  28107. throw new Error("Active camera not set");
  28108. // Viewport
  28109. engine.setViewport(this.activeCamera.viewport);
  28110. // Camera
  28111. this.updateTransformMatrix();
  28112. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28113. }
  28114. }
  28115. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28116. this._intermediateRendering = false;
  28117. this._renderId++;
  28118. }
  28119. // Restore back buffer
  28120. if (this.customRenderTargets.length > 0) {
  28121. engine.restoreDefaultFramebuffer();
  28122. }
  28123. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28124. this.activeCamera = currentActiveCamera;
  28125. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28126. var step = _c[_b];
  28127. step.action();
  28128. }
  28129. // Clear
  28130. if (this.autoClearDepthAndStencil || this.autoClear) {
  28131. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28132. }
  28133. // Collects render targets from external components.
  28134. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28135. var step = _e[_d];
  28136. step.action(this._renderTargets);
  28137. }
  28138. // Multi-cameras?
  28139. if (this.activeCameras.length > 0) {
  28140. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28141. if (cameraIndex > 0) {
  28142. this._engine.clear(null, false, true, true);
  28143. }
  28144. this._processSubCameras(this.activeCameras[cameraIndex]);
  28145. }
  28146. }
  28147. else {
  28148. if (!this.activeCamera) {
  28149. throw new Error("No camera defined");
  28150. }
  28151. this._processSubCameras(this.activeCamera);
  28152. }
  28153. // Intersection checks
  28154. this._checkIntersections();
  28155. // Executes the after render stage actions.
  28156. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28157. var step = _g[_f];
  28158. step.action();
  28159. }
  28160. // After render
  28161. if (this.afterRender) {
  28162. this.afterRender();
  28163. }
  28164. this.onAfterRenderObservable.notifyObservers(this);
  28165. // Cleaning
  28166. if (this._toBeDisposed.length) {
  28167. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28168. var data = this._toBeDisposed[index];
  28169. if (data) {
  28170. data.dispose();
  28171. }
  28172. }
  28173. this._toBeDisposed = [];
  28174. }
  28175. if (this.dumpNextRenderTargets) {
  28176. this.dumpNextRenderTargets = false;
  28177. }
  28178. this._activeBones.addCount(0, true);
  28179. this._activeIndices.addCount(0, true);
  28180. this._activeParticles.addCount(0, true);
  28181. };
  28182. /**
  28183. * Freeze all materials
  28184. * A frozen material will not be updatable but should be faster to render
  28185. */
  28186. Scene.prototype.freezeMaterials = function () {
  28187. for (var i = 0; i < this.materials.length; i++) {
  28188. this.materials[i].freeze();
  28189. }
  28190. };
  28191. /**
  28192. * Unfreeze all materials
  28193. * A frozen material will not be updatable but should be faster to render
  28194. */
  28195. Scene.prototype.unfreezeMaterials = function () {
  28196. for (var i = 0; i < this.materials.length; i++) {
  28197. this.materials[i].unfreeze();
  28198. }
  28199. };
  28200. /**
  28201. * Releases all held ressources
  28202. */
  28203. Scene.prototype.dispose = function () {
  28204. this.beforeRender = null;
  28205. this.afterRender = null;
  28206. this.skeletons = [];
  28207. this.morphTargetManagers = [];
  28208. this._transientComponents = [];
  28209. this._isReadyForMeshStage.clear();
  28210. this._beforeEvaluateActiveMeshStage.clear();
  28211. this._evaluateSubMeshStage.clear();
  28212. this._activeMeshStage.clear();
  28213. this._cameraDrawRenderTargetStage.clear();
  28214. this._beforeCameraDrawStage.clear();
  28215. this._beforeRenderingGroupDrawStage.clear();
  28216. this._beforeRenderingMeshStage.clear();
  28217. this._afterRenderingMeshStage.clear();
  28218. this._afterRenderingGroupDrawStage.clear();
  28219. this._afterCameraDrawStage.clear();
  28220. this._afterRenderStage.clear();
  28221. this._beforeCameraUpdateStage.clear();
  28222. this._beforeClearStage.clear();
  28223. this._gatherRenderTargetsStage.clear();
  28224. this._gatherActiveCameraRenderTargetsStage.clear();
  28225. this._pointerMoveStage.clear();
  28226. this._pointerDownStage.clear();
  28227. this._pointerUpStage.clear();
  28228. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28229. var component = _a[_i];
  28230. component.dispose();
  28231. }
  28232. this.importedMeshesFiles = new Array();
  28233. this.stopAllAnimations();
  28234. this.resetCachedMaterial();
  28235. // Smart arrays
  28236. if (this.activeCamera) {
  28237. this.activeCamera._activeMeshes.dispose();
  28238. this.activeCamera = null;
  28239. }
  28240. this._activeMeshes.dispose();
  28241. this._renderingManager.dispose();
  28242. this._processedMaterials.dispose();
  28243. this._activeParticleSystems.dispose();
  28244. this._activeSkeletons.dispose();
  28245. this._softwareSkinnedMeshes.dispose();
  28246. this._renderTargets.dispose();
  28247. this._registeredForLateAnimationBindings.dispose();
  28248. this._meshesForIntersections.dispose();
  28249. this._toBeDisposed = [];
  28250. // Abort active requests
  28251. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28252. var request = _c[_b];
  28253. request.abort();
  28254. }
  28255. // Events
  28256. this.onDisposeObservable.notifyObservers(this);
  28257. this.onDisposeObservable.clear();
  28258. this.onBeforeRenderObservable.clear();
  28259. this.onAfterRenderObservable.clear();
  28260. this.onBeforeRenderTargetsRenderObservable.clear();
  28261. this.onAfterRenderTargetsRenderObservable.clear();
  28262. this.onAfterStepObservable.clear();
  28263. this.onBeforeStepObservable.clear();
  28264. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28265. this.onAfterActiveMeshesEvaluationObservable.clear();
  28266. this.onBeforeParticlesRenderingObservable.clear();
  28267. this.onAfterParticlesRenderingObservable.clear();
  28268. this.onBeforeDrawPhaseObservable.clear();
  28269. this.onAfterDrawPhaseObservable.clear();
  28270. this.onBeforeAnimationsObservable.clear();
  28271. this.onAfterAnimationsObservable.clear();
  28272. this.onDataLoadedObservable.clear();
  28273. this.onBeforeRenderingGroupObservable.clear();
  28274. this.onAfterRenderingGroupObservable.clear();
  28275. this.onMeshImportedObservable.clear();
  28276. this.onBeforeCameraRenderObservable.clear();
  28277. this.onAfterCameraRenderObservable.clear();
  28278. this.onReadyObservable.clear();
  28279. this.onNewCameraAddedObservable.clear();
  28280. this.onCameraRemovedObservable.clear();
  28281. this.onNewLightAddedObservable.clear();
  28282. this.onLightRemovedObservable.clear();
  28283. this.onNewGeometryAddedObservable.clear();
  28284. this.onGeometryRemovedObservable.clear();
  28285. this.onNewTransformNodeAddedObservable.clear();
  28286. this.onTransformNodeRemovedObservable.clear();
  28287. this.onNewMeshAddedObservable.clear();
  28288. this.onMeshRemovedObservable.clear();
  28289. this.onNewMaterialAddedObservable.clear();
  28290. this.onMaterialRemovedObservable.clear();
  28291. this.onNewTextureAddedObservable.clear();
  28292. this.onTextureRemovedObservable.clear();
  28293. this.onPrePointerObservable.clear();
  28294. this.onPointerObservable.clear();
  28295. this.onPreKeyboardObservable.clear();
  28296. this.onKeyboardObservable.clear();
  28297. this.detachControl();
  28298. // Detach cameras
  28299. var canvas = this._engine.getRenderingCanvas();
  28300. if (canvas) {
  28301. var index;
  28302. for (index = 0; index < this.cameras.length; index++) {
  28303. this.cameras[index].detachControl(canvas);
  28304. }
  28305. }
  28306. // Release animation groups
  28307. while (this.animationGroups.length) {
  28308. this.animationGroups[0].dispose();
  28309. }
  28310. // Release lights
  28311. while (this.lights.length) {
  28312. this.lights[0].dispose();
  28313. }
  28314. // Release meshes
  28315. while (this.meshes.length) {
  28316. this.meshes[0].dispose(true);
  28317. }
  28318. while (this.transformNodes.length) {
  28319. this.removeTransformNode(this.transformNodes[0]);
  28320. }
  28321. // Release cameras
  28322. while (this.cameras.length) {
  28323. this.cameras[0].dispose();
  28324. }
  28325. // Release materials
  28326. if (this.defaultMaterial) {
  28327. this.defaultMaterial.dispose();
  28328. }
  28329. while (this.multiMaterials.length) {
  28330. this.multiMaterials[0].dispose();
  28331. }
  28332. while (this.materials.length) {
  28333. this.materials[0].dispose();
  28334. }
  28335. // Release particles
  28336. while (this.particleSystems.length) {
  28337. this.particleSystems[0].dispose();
  28338. }
  28339. // Release postProcesses
  28340. while (this.postProcesses.length) {
  28341. this.postProcesses[0].dispose();
  28342. }
  28343. // Release textures
  28344. while (this.textures.length) {
  28345. this.textures[0].dispose();
  28346. }
  28347. // Release UBO
  28348. this._sceneUbo.dispose();
  28349. if (this._alternateSceneUbo) {
  28350. this._alternateSceneUbo.dispose();
  28351. }
  28352. // Post-processes
  28353. this.postProcessManager.dispose();
  28354. // Remove from engine
  28355. index = this._engine.scenes.indexOf(this);
  28356. if (index > -1) {
  28357. this._engine.scenes.splice(index, 1);
  28358. }
  28359. this._engine.wipeCaches(true);
  28360. this._isDisposed = true;
  28361. };
  28362. Object.defineProperty(Scene.prototype, "isDisposed", {
  28363. /**
  28364. * Gets if the scene is already disposed
  28365. */
  28366. get: function () {
  28367. return this._isDisposed;
  28368. },
  28369. enumerable: true,
  28370. configurable: true
  28371. });
  28372. /**
  28373. * Call this function to reduce memory footprint of the scene.
  28374. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28375. */
  28376. Scene.prototype.clearCachedVertexData = function () {
  28377. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28378. var mesh = this.meshes[meshIndex];
  28379. var geometry = mesh.geometry;
  28380. if (geometry) {
  28381. geometry._indices = [];
  28382. for (var vbName in geometry._vertexBuffers) {
  28383. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28384. continue;
  28385. }
  28386. geometry._vertexBuffers[vbName]._buffer._data = null;
  28387. }
  28388. }
  28389. }
  28390. };
  28391. /**
  28392. * This function will remove the local cached buffer data from texture.
  28393. * It will save memory but will prevent the texture from being rebuilt
  28394. */
  28395. Scene.prototype.cleanCachedTextureBuffer = function () {
  28396. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28397. var baseTexture = _a[_i];
  28398. var buffer = baseTexture._buffer;
  28399. if (buffer) {
  28400. baseTexture._buffer = null;
  28401. }
  28402. }
  28403. };
  28404. /**
  28405. * Get the world extend vectors with an optional filter
  28406. *
  28407. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28408. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28409. */
  28410. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28411. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28412. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28413. filterPredicate = filterPredicate || (function () { return true; });
  28414. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28415. mesh.computeWorldMatrix(true);
  28416. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28417. return;
  28418. }
  28419. var boundingInfo = mesh.getBoundingInfo();
  28420. var minBox = boundingInfo.boundingBox.minimumWorld;
  28421. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28422. BABYLON.Tools.CheckExtends(minBox, min, max);
  28423. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28424. });
  28425. return {
  28426. min: min,
  28427. max: max
  28428. };
  28429. };
  28430. // Picking
  28431. /**
  28432. * Creates a ray that can be used to pick in the scene
  28433. * @param x defines the x coordinate of the origin (on-screen)
  28434. * @param y defines the y coordinate of the origin (on-screen)
  28435. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28436. * @param camera defines the camera to use for the picking
  28437. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28438. * @returns a Ray
  28439. */
  28440. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28441. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28442. var result = BABYLON.Ray.Zero();
  28443. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28444. return result;
  28445. };
  28446. /**
  28447. * Creates a ray that can be used to pick in the scene
  28448. * @param x defines the x coordinate of the origin (on-screen)
  28449. * @param y defines the y coordinate of the origin (on-screen)
  28450. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28451. * @param result defines the ray where to store the picking ray
  28452. * @param camera defines the camera to use for the picking
  28453. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28454. * @returns the current scene
  28455. */
  28456. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28457. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28458. var engine = this._engine;
  28459. if (!camera) {
  28460. if (!this.activeCamera)
  28461. throw new Error("Active camera not set");
  28462. camera = this.activeCamera;
  28463. }
  28464. var cameraViewport = camera.viewport;
  28465. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28466. // Moving coordinates to local viewport world
  28467. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28468. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28469. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28470. return this;
  28471. };
  28472. /**
  28473. * Creates a ray that can be used to pick in the scene
  28474. * @param x defines the x coordinate of the origin (on-screen)
  28475. * @param y defines the y coordinate of the origin (on-screen)
  28476. * @param camera defines the camera to use for the picking
  28477. * @returns a Ray
  28478. */
  28479. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28480. var result = BABYLON.Ray.Zero();
  28481. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28482. return result;
  28483. };
  28484. /**
  28485. * Creates a ray that can be used to pick in the scene
  28486. * @param x defines the x coordinate of the origin (on-screen)
  28487. * @param y defines the y coordinate of the origin (on-screen)
  28488. * @param result defines the ray where to store the picking ray
  28489. * @param camera defines the camera to use for the picking
  28490. * @returns the current scene
  28491. */
  28492. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28493. if (!BABYLON.PickingInfo) {
  28494. return this;
  28495. }
  28496. var engine = this._engine;
  28497. if (!camera) {
  28498. if (!this.activeCamera)
  28499. throw new Error("Active camera not set");
  28500. camera = this.activeCamera;
  28501. }
  28502. var cameraViewport = camera.viewport;
  28503. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28504. var identity = BABYLON.Matrix.Identity();
  28505. // Moving coordinates to local viewport world
  28506. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28507. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28508. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28509. return this;
  28510. };
  28511. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28512. if (!BABYLON.PickingInfo) {
  28513. return null;
  28514. }
  28515. var pickingInfo = null;
  28516. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28517. var mesh = this.meshes[meshIndex];
  28518. if (predicate) {
  28519. if (!predicate(mesh)) {
  28520. continue;
  28521. }
  28522. }
  28523. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28524. continue;
  28525. }
  28526. var world = mesh.getWorldMatrix();
  28527. var ray = rayFunction(world);
  28528. var result = mesh.intersects(ray, fastCheck);
  28529. if (!result || !result.hit)
  28530. continue;
  28531. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28532. continue;
  28533. pickingInfo = result;
  28534. if (fastCheck) {
  28535. break;
  28536. }
  28537. }
  28538. return pickingInfo || new BABYLON.PickingInfo();
  28539. };
  28540. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28541. if (!BABYLON.PickingInfo) {
  28542. return null;
  28543. }
  28544. var pickingInfos = new Array();
  28545. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28546. var mesh = this.meshes[meshIndex];
  28547. if (predicate) {
  28548. if (!predicate(mesh)) {
  28549. continue;
  28550. }
  28551. }
  28552. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28553. continue;
  28554. }
  28555. var world = mesh.getWorldMatrix();
  28556. var ray = rayFunction(world);
  28557. var result = mesh.intersects(ray, false);
  28558. if (!result || !result.hit)
  28559. continue;
  28560. pickingInfos.push(result);
  28561. }
  28562. return pickingInfos;
  28563. };
  28564. /** Launch a ray to try to pick a mesh in the scene
  28565. * @param x position on screen
  28566. * @param y position on screen
  28567. * @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
  28568. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28569. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28570. * @returns a PickingInfo
  28571. */
  28572. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28573. var _this = this;
  28574. if (!BABYLON.PickingInfo) {
  28575. return null;
  28576. }
  28577. var result = this._internalPick(function (world) {
  28578. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28579. return _this._tempPickingRay;
  28580. }, predicate, fastCheck);
  28581. if (result) {
  28582. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28583. }
  28584. return result;
  28585. };
  28586. /** Use the given ray to pick a mesh in the scene
  28587. * @param ray The ray to use to pick meshes
  28588. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28589. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28590. * @returns a PickingInfo
  28591. */
  28592. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28593. var _this = this;
  28594. var result = this._internalPick(function (world) {
  28595. if (!_this._pickWithRayInverseMatrix) {
  28596. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28597. }
  28598. world.invertToRef(_this._pickWithRayInverseMatrix);
  28599. if (!_this._cachedRayForTransform) {
  28600. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28601. }
  28602. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28603. return _this._cachedRayForTransform;
  28604. }, predicate, fastCheck);
  28605. if (result) {
  28606. result.ray = ray;
  28607. }
  28608. return result;
  28609. };
  28610. /**
  28611. * Launch a ray to try to pick a mesh in the scene
  28612. * @param x X position on screen
  28613. * @param y Y position on screen
  28614. * @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
  28615. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28616. * @returns an array of PickingInfo
  28617. */
  28618. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28619. var _this = this;
  28620. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28621. };
  28622. /**
  28623. * Launch a ray to try to pick a mesh in the scene
  28624. * @param ray Ray to use
  28625. * @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
  28626. * @returns an array of PickingInfo
  28627. */
  28628. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28629. var _this = this;
  28630. return this._internalMultiPick(function (world) {
  28631. if (!_this._pickWithRayInverseMatrix) {
  28632. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28633. }
  28634. world.invertToRef(_this._pickWithRayInverseMatrix);
  28635. if (!_this._cachedRayForTransform) {
  28636. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28637. }
  28638. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28639. return _this._cachedRayForTransform;
  28640. }, predicate);
  28641. };
  28642. /**
  28643. * Force the value of meshUnderPointer
  28644. * @param mesh defines the mesh to use
  28645. */
  28646. Scene.prototype.setPointerOverMesh = function (mesh) {
  28647. if (this._pointerOverMesh === mesh) {
  28648. return;
  28649. }
  28650. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28651. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28652. }
  28653. this._pointerOverMesh = mesh;
  28654. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28655. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28656. }
  28657. };
  28658. /**
  28659. * Gets the mesh under the pointer
  28660. * @returns a Mesh or null if no mesh is under the pointer
  28661. */
  28662. Scene.prototype.getPointerOverMesh = function () {
  28663. return this._pointerOverMesh;
  28664. };
  28665. // Misc.
  28666. /** @hidden */
  28667. Scene.prototype._rebuildGeometries = function () {
  28668. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28669. var geometry = _a[_i];
  28670. geometry._rebuild();
  28671. }
  28672. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28673. var mesh = _c[_b];
  28674. mesh._rebuild();
  28675. }
  28676. if (this.postProcessManager) {
  28677. this.postProcessManager._rebuild();
  28678. }
  28679. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28680. var component = _e[_d];
  28681. component.rebuild();
  28682. }
  28683. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28684. var system = _g[_f];
  28685. system.rebuild();
  28686. }
  28687. };
  28688. /** @hidden */
  28689. Scene.prototype._rebuildTextures = function () {
  28690. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28691. var texture = _a[_i];
  28692. texture._rebuild();
  28693. }
  28694. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28695. };
  28696. // Tags
  28697. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28698. if (tagsQuery === undefined) {
  28699. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28700. return list;
  28701. }
  28702. var listByTags = [];
  28703. forEach = forEach || (function (item) { return; });
  28704. for (var i in list) {
  28705. var item = list[i];
  28706. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28707. listByTags.push(item);
  28708. forEach(item);
  28709. }
  28710. }
  28711. return listByTags;
  28712. };
  28713. /**
  28714. * Get a list of meshes by tags
  28715. * @param tagsQuery defines the tags query to use
  28716. * @param forEach defines a predicate used to filter results
  28717. * @returns an array of Mesh
  28718. */
  28719. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28720. return this._getByTags(this.meshes, tagsQuery, forEach);
  28721. };
  28722. /**
  28723. * Get a list of cameras by tags
  28724. * @param tagsQuery defines the tags query to use
  28725. * @param forEach defines a predicate used to filter results
  28726. * @returns an array of Camera
  28727. */
  28728. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28729. return this._getByTags(this.cameras, tagsQuery, forEach);
  28730. };
  28731. /**
  28732. * Get a list of lights by tags
  28733. * @param tagsQuery defines the tags query to use
  28734. * @param forEach defines a predicate used to filter results
  28735. * @returns an array of Light
  28736. */
  28737. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28738. return this._getByTags(this.lights, tagsQuery, forEach);
  28739. };
  28740. /**
  28741. * Get a list of materials by tags
  28742. * @param tagsQuery defines the tags query to use
  28743. * @param forEach defines a predicate used to filter results
  28744. * @returns an array of Material
  28745. */
  28746. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28747. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28748. };
  28749. /**
  28750. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28751. * This allowed control for front to back rendering or reversly depending of the special needs.
  28752. *
  28753. * @param renderingGroupId The rendering group id corresponding to its index
  28754. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28755. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28756. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28757. */
  28758. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28759. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28760. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28761. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28762. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28763. };
  28764. /**
  28765. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28766. *
  28767. * @param renderingGroupId The rendering group id corresponding to its index
  28768. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28769. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28770. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28771. */
  28772. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28773. if (depth === void 0) { depth = true; }
  28774. if (stencil === void 0) { stencil = true; }
  28775. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28776. };
  28777. /**
  28778. * Gets the current auto clear configuration for one rendering group of the rendering
  28779. * manager.
  28780. * @param index the rendering group index to get the information for
  28781. * @returns The auto clear setup for the requested rendering group
  28782. */
  28783. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28784. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28785. };
  28786. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28787. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28788. get: function () {
  28789. return this._blockMaterialDirtyMechanism;
  28790. },
  28791. set: function (value) {
  28792. if (this._blockMaterialDirtyMechanism === value) {
  28793. return;
  28794. }
  28795. this._blockMaterialDirtyMechanism = value;
  28796. if (!value) { // Do a complete update
  28797. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28798. }
  28799. },
  28800. enumerable: true,
  28801. configurable: true
  28802. });
  28803. /**
  28804. * Will flag all materials as dirty to trigger new shader compilation
  28805. * @param flag defines the flag used to specify which material part must be marked as dirty
  28806. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28807. */
  28808. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28809. if (this._blockMaterialDirtyMechanism) {
  28810. return;
  28811. }
  28812. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28813. var material = _a[_i];
  28814. if (predicate && !predicate(material)) {
  28815. continue;
  28816. }
  28817. material.markAsDirty(flag);
  28818. }
  28819. };
  28820. /** @hidden */
  28821. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28822. var _this = this;
  28823. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28824. this._activeRequests.push(request);
  28825. request.onCompleteObservable.add(function (request) {
  28826. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28827. });
  28828. return request;
  28829. };
  28830. /** @hidden */
  28831. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28832. var _this = this;
  28833. return new Promise(function (resolve, reject) {
  28834. _this._loadFile(url, function (data) {
  28835. resolve(data);
  28836. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28837. reject(exception);
  28838. });
  28839. });
  28840. };
  28841. // Statics
  28842. Scene._uniqueIdCounter = 0;
  28843. /** The fog is deactivated */
  28844. Scene.FOGMODE_NONE = 0;
  28845. /** The fog density is following an exponential function */
  28846. Scene.FOGMODE_EXP = 1;
  28847. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28848. Scene.FOGMODE_EXP2 = 2;
  28849. /** The fog density is following a linear function. */
  28850. Scene.FOGMODE_LINEAR = 3;
  28851. /**
  28852. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28853. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28854. */
  28855. Scene.MinDeltaTime = 1.0;
  28856. /**
  28857. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28858. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28859. */
  28860. Scene.MaxDeltaTime = 1000.0;
  28861. /** The distance in pixel that you have to move to prevent some events */
  28862. Scene.DragMovementThreshold = 10; // in pixels
  28863. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28864. Scene.LongPressDelay = 500; // in milliseconds
  28865. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28866. Scene.DoubleClickDelay = 300; // in milliseconds
  28867. /** If you need to check double click without raising a single click at first click, enable this flag */
  28868. Scene.ExclusiveDoubleClickMode = false;
  28869. return Scene;
  28870. }(BABYLON.AbstractScene));
  28871. BABYLON.Scene = Scene;
  28872. })(BABYLON || (BABYLON = {}));
  28873. //# sourceMappingURL=babylon.scene.js.map
  28874. var BABYLON;
  28875. (function (BABYLON) {
  28876. /**
  28877. * Set of assets to keep when moving a scene into an asset container.
  28878. */
  28879. var KeepAssets = /** @class */ (function (_super) {
  28880. __extends(KeepAssets, _super);
  28881. function KeepAssets() {
  28882. return _super !== null && _super.apply(this, arguments) || this;
  28883. }
  28884. return KeepAssets;
  28885. }(BABYLON.AbstractScene));
  28886. BABYLON.KeepAssets = KeepAssets;
  28887. /**
  28888. * Container with a set of assets that can be added or removed from a scene.
  28889. */
  28890. var AssetContainer = /** @class */ (function (_super) {
  28891. __extends(AssetContainer, _super);
  28892. /**
  28893. * Instantiates an AssetContainer.
  28894. * @param scene The scene the AssetContainer belongs to.
  28895. */
  28896. function AssetContainer(scene) {
  28897. var _this = _super.call(this) || this;
  28898. _this.scene = scene;
  28899. return _this;
  28900. }
  28901. /**
  28902. * Adds all the assets from the container to the scene.
  28903. */
  28904. AssetContainer.prototype.addAllToScene = function () {
  28905. var _this = this;
  28906. this.cameras.forEach(function (o) {
  28907. _this.scene.addCamera(o);
  28908. });
  28909. this.lights.forEach(function (o) {
  28910. _this.scene.addLight(o);
  28911. });
  28912. this.meshes.forEach(function (o) {
  28913. _this.scene.addMesh(o);
  28914. });
  28915. this.skeletons.forEach(function (o) {
  28916. _this.scene.addSkeleton(o);
  28917. });
  28918. this.animations.forEach(function (o) {
  28919. _this.scene.addAnimation(o);
  28920. });
  28921. this.animationGroups.forEach(function (o) {
  28922. _this.scene.addAnimationGroup(o);
  28923. });
  28924. this.multiMaterials.forEach(function (o) {
  28925. _this.scene.addMultiMaterial(o);
  28926. });
  28927. this.materials.forEach(function (o) {
  28928. _this.scene.addMaterial(o);
  28929. });
  28930. this.morphTargetManagers.forEach(function (o) {
  28931. _this.scene.addMorphTargetManager(o);
  28932. });
  28933. this.geometries.forEach(function (o) {
  28934. _this.scene.addGeometry(o);
  28935. });
  28936. this.transformNodes.forEach(function (o) {
  28937. _this.scene.addTransformNode(o);
  28938. });
  28939. this.actionManagers.forEach(function (o) {
  28940. _this.scene.addActionManager(o);
  28941. });
  28942. this.textures.forEach(function (o) {
  28943. _this.scene.addTexture(o);
  28944. });
  28945. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28946. var component = _a[_i];
  28947. component.addFromContainer(this.scene);
  28948. }
  28949. };
  28950. /**
  28951. * Removes all the assets in the container from the scene
  28952. */
  28953. AssetContainer.prototype.removeAllFromScene = function () {
  28954. var _this = this;
  28955. this.cameras.forEach(function (o) {
  28956. _this.scene.removeCamera(o);
  28957. });
  28958. this.lights.forEach(function (o) {
  28959. _this.scene.removeLight(o);
  28960. });
  28961. this.meshes.forEach(function (o) {
  28962. _this.scene.removeMesh(o);
  28963. });
  28964. this.skeletons.forEach(function (o) {
  28965. _this.scene.removeSkeleton(o);
  28966. });
  28967. this.animations.forEach(function (o) {
  28968. _this.scene.removeAnimation(o);
  28969. });
  28970. this.animationGroups.forEach(function (o) {
  28971. _this.scene.removeAnimationGroup(o);
  28972. });
  28973. this.multiMaterials.forEach(function (o) {
  28974. _this.scene.removeMultiMaterial(o);
  28975. });
  28976. this.materials.forEach(function (o) {
  28977. _this.scene.removeMaterial(o);
  28978. });
  28979. this.morphTargetManagers.forEach(function (o) {
  28980. _this.scene.removeMorphTargetManager(o);
  28981. });
  28982. this.geometries.forEach(function (o) {
  28983. _this.scene.removeGeometry(o);
  28984. });
  28985. this.transformNodes.forEach(function (o) {
  28986. _this.scene.removeTransformNode(o);
  28987. });
  28988. this.actionManagers.forEach(function (o) {
  28989. _this.scene.removeActionManager(o);
  28990. });
  28991. this.textures.forEach(function (o) {
  28992. _this.scene.removeTexture(o);
  28993. });
  28994. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28995. var component = _a[_i];
  28996. component.removeFromContainer(this.scene);
  28997. }
  28998. };
  28999. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29000. if (!sourceAssets) {
  29001. return;
  29002. }
  29003. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29004. var asset = sourceAssets_1[_i];
  29005. var move = true;
  29006. if (keepAssets) {
  29007. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29008. var keepAsset = keepAssets_1[_a];
  29009. if (asset === keepAsset) {
  29010. move = false;
  29011. break;
  29012. }
  29013. }
  29014. }
  29015. if (move) {
  29016. targetAssets.push(asset);
  29017. }
  29018. }
  29019. };
  29020. /**
  29021. * Removes all the assets contained in the scene and adds them to the container.
  29022. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29023. */
  29024. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29025. if (keepAssets === undefined) {
  29026. keepAssets = new KeepAssets();
  29027. }
  29028. for (var key in this) {
  29029. if (this.hasOwnProperty(key)) {
  29030. this[key] = this[key] || [];
  29031. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29032. }
  29033. }
  29034. this.removeAllFromScene();
  29035. };
  29036. /**
  29037. * 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.
  29038. * @returns the root mesh
  29039. */
  29040. AssetContainer.prototype.createRootMesh = function () {
  29041. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29042. this.meshes.forEach(function (m) {
  29043. if (!m.parent) {
  29044. rootMesh.addChild(m);
  29045. }
  29046. });
  29047. this.meshes.unshift(rootMesh);
  29048. return rootMesh;
  29049. };
  29050. return AssetContainer;
  29051. }(BABYLON.AbstractScene));
  29052. BABYLON.AssetContainer = AssetContainer;
  29053. })(BABYLON || (BABYLON = {}));
  29054. //# sourceMappingURL=babylon.assetContainer.js.map
  29055. var BABYLON;
  29056. (function (BABYLON) {
  29057. var Buffer = /** @class */ (function () {
  29058. /**
  29059. * Constructor
  29060. * @param engine the engine
  29061. * @param data the data to use for this buffer
  29062. * @param updatable whether the data is updatable
  29063. * @param stride the stride (optional)
  29064. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29065. * @param instanced whether the buffer is instanced (optional)
  29066. * @param useBytes set to true if the stride in in bytes (optional)
  29067. */
  29068. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29069. if (stride === void 0) { stride = 0; }
  29070. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29071. if (instanced === void 0) { instanced = false; }
  29072. if (useBytes === void 0) { useBytes = false; }
  29073. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29074. this._engine = engine.getScene().getEngine();
  29075. }
  29076. else {
  29077. this._engine = engine;
  29078. }
  29079. this._updatable = updatable;
  29080. this._instanced = instanced;
  29081. this._data = data;
  29082. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29083. if (!postponeInternalCreation) { // by default
  29084. this.create();
  29085. }
  29086. }
  29087. /**
  29088. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29089. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29090. * @param offset defines offset in the buffer (0 by default)
  29091. * @param size defines the size in floats of attributes (position is 3 for instance)
  29092. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29093. * @param instanced defines if the vertex buffer contains indexed data
  29094. * @param useBytes defines if the offset and stride are in bytes
  29095. * @returns the new vertex buffer
  29096. */
  29097. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29098. if (useBytes === void 0) { useBytes = false; }
  29099. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29100. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29101. // a lot of these parameters are ignored as they are overriden by the buffer
  29102. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29103. };
  29104. // Properties
  29105. Buffer.prototype.isUpdatable = function () {
  29106. return this._updatable;
  29107. };
  29108. Buffer.prototype.getData = function () {
  29109. return this._data;
  29110. };
  29111. Buffer.prototype.getBuffer = function () {
  29112. return this._buffer;
  29113. };
  29114. /**
  29115. * Gets the stride in float32 units (i.e. byte stride / 4).
  29116. * May not be an integer if the byte stride is not divisible by 4.
  29117. * DEPRECATED. Use byteStride instead.
  29118. * @returns the stride in float32 units
  29119. */
  29120. Buffer.prototype.getStrideSize = function () {
  29121. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29122. };
  29123. // Methods
  29124. Buffer.prototype.create = function (data) {
  29125. if (data === void 0) { data = null; }
  29126. if (!data && this._buffer) {
  29127. return; // nothing to do
  29128. }
  29129. data = data || this._data;
  29130. if (!data) {
  29131. return;
  29132. }
  29133. if (!this._buffer) { // create buffer
  29134. if (this._updatable) {
  29135. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29136. this._data = data;
  29137. }
  29138. else {
  29139. this._buffer = this._engine.createVertexBuffer(data);
  29140. }
  29141. }
  29142. else if (this._updatable) { // update buffer
  29143. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29144. this._data = data;
  29145. }
  29146. };
  29147. /** @hidden */
  29148. Buffer.prototype._rebuild = function () {
  29149. this._buffer = null;
  29150. this.create(this._data);
  29151. };
  29152. Buffer.prototype.update = function (data) {
  29153. this.create(data);
  29154. };
  29155. /**
  29156. * Updates the data directly.
  29157. * @param data the new data
  29158. * @param offset the new offset
  29159. * @param vertexCount the vertex count (optional)
  29160. * @param useBytes set to true if the offset is in bytes
  29161. */
  29162. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29163. if (useBytes === void 0) { useBytes = false; }
  29164. if (!this._buffer) {
  29165. return;
  29166. }
  29167. if (this._updatable) { // update buffer
  29168. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29169. this._data = null;
  29170. }
  29171. };
  29172. Buffer.prototype.dispose = function () {
  29173. if (!this._buffer) {
  29174. return;
  29175. }
  29176. if (this._engine._releaseBuffer(this._buffer)) {
  29177. this._buffer = null;
  29178. }
  29179. };
  29180. return Buffer;
  29181. }());
  29182. BABYLON.Buffer = Buffer;
  29183. })(BABYLON || (BABYLON = {}));
  29184. //# sourceMappingURL=babylon.buffer.js.map
  29185. var BABYLON;
  29186. (function (BABYLON) {
  29187. var VertexBuffer = /** @class */ (function () {
  29188. /**
  29189. * Constructor
  29190. * @param engine the engine
  29191. * @param data the data to use for this vertex buffer
  29192. * @param kind the vertex buffer kind
  29193. * @param updatable whether the data is updatable
  29194. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29195. * @param stride the stride (optional)
  29196. * @param instanced whether the buffer is instanced (optional)
  29197. * @param offset the offset of the data (optional)
  29198. * @param size the number of components (optional)
  29199. * @param type the type of the component (optional)
  29200. * @param normalized whether the data contains normalized data (optional)
  29201. * @param useBytes set to true if stride and offset are in bytes (optional)
  29202. */
  29203. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29204. if (normalized === void 0) { normalized = false; }
  29205. if (useBytes === void 0) { useBytes = false; }
  29206. if (data instanceof BABYLON.Buffer) {
  29207. this._buffer = data;
  29208. this._ownsBuffer = false;
  29209. }
  29210. else {
  29211. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29212. this._ownsBuffer = true;
  29213. }
  29214. this._kind = kind;
  29215. if (type == undefined) {
  29216. var data_1 = this.getData();
  29217. this.type = VertexBuffer.FLOAT;
  29218. if (data_1 instanceof Int8Array)
  29219. this.type = VertexBuffer.BYTE;
  29220. else if (data_1 instanceof Uint8Array)
  29221. this.type = VertexBuffer.UNSIGNED_BYTE;
  29222. else if (data_1 instanceof Int16Array)
  29223. this.type = VertexBuffer.SHORT;
  29224. else if (data_1 instanceof Uint16Array)
  29225. this.type = VertexBuffer.UNSIGNED_SHORT;
  29226. else if (data_1 instanceof Int32Array)
  29227. this.type = VertexBuffer.INT;
  29228. else if (data_1 instanceof Uint32Array)
  29229. this.type = VertexBuffer.UNSIGNED_INT;
  29230. }
  29231. else {
  29232. this.type = type;
  29233. }
  29234. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29235. if (useBytes) {
  29236. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29237. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29238. this.byteOffset = offset || 0;
  29239. }
  29240. else {
  29241. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29242. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29243. this.byteOffset = (offset || 0) * typeByteLength;
  29244. }
  29245. this.normalized = normalized;
  29246. this._instanced = instanced !== undefined ? instanced : false;
  29247. this._instanceDivisor = instanced ? 1 : 0;
  29248. }
  29249. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29250. /**
  29251. * Gets or sets the instance divisor when in instanced mode
  29252. */
  29253. get: function () {
  29254. return this._instanceDivisor;
  29255. },
  29256. set: function (value) {
  29257. this._instanceDivisor = value;
  29258. if (value == 0) {
  29259. this._instanced = false;
  29260. }
  29261. else {
  29262. this._instanced = true;
  29263. }
  29264. },
  29265. enumerable: true,
  29266. configurable: true
  29267. });
  29268. /** @hidden */
  29269. VertexBuffer.prototype._rebuild = function () {
  29270. if (!this._buffer) {
  29271. return;
  29272. }
  29273. this._buffer._rebuild();
  29274. };
  29275. /**
  29276. * Returns the kind of the VertexBuffer (string).
  29277. */
  29278. VertexBuffer.prototype.getKind = function () {
  29279. return this._kind;
  29280. };
  29281. // Properties
  29282. /**
  29283. * Boolean : is the VertexBuffer updatable ?
  29284. */
  29285. VertexBuffer.prototype.isUpdatable = function () {
  29286. return this._buffer.isUpdatable();
  29287. };
  29288. /**
  29289. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29290. */
  29291. VertexBuffer.prototype.getData = function () {
  29292. return this._buffer.getData();
  29293. };
  29294. /**
  29295. * Returns the WebGLBuffer associated to the VertexBuffer.
  29296. */
  29297. VertexBuffer.prototype.getBuffer = function () {
  29298. return this._buffer.getBuffer();
  29299. };
  29300. /**
  29301. * Returns the stride as a multiple of the type byte length.
  29302. * DEPRECATED. Use byteStride instead.
  29303. */
  29304. VertexBuffer.prototype.getStrideSize = function () {
  29305. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29306. };
  29307. /**
  29308. * Returns the offset as a multiple of the type byte length.
  29309. * DEPRECATED. Use byteOffset instead.
  29310. */
  29311. VertexBuffer.prototype.getOffset = function () {
  29312. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29313. };
  29314. /**
  29315. * Returns the number of components per vertex attribute (integer).
  29316. */
  29317. VertexBuffer.prototype.getSize = function () {
  29318. return this._size;
  29319. };
  29320. /**
  29321. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29322. */
  29323. VertexBuffer.prototype.getIsInstanced = function () {
  29324. return this._instanced;
  29325. };
  29326. /**
  29327. * Returns the instancing divisor, zero for non-instanced (integer).
  29328. */
  29329. VertexBuffer.prototype.getInstanceDivisor = function () {
  29330. return this._instanceDivisor;
  29331. };
  29332. // Methods
  29333. /**
  29334. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29335. * Returns the created WebGLBuffer.
  29336. */
  29337. VertexBuffer.prototype.create = function (data) {
  29338. return this._buffer.create(data);
  29339. };
  29340. /**
  29341. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29342. * This function will create a new buffer if the current one is not updatable
  29343. * Returns the updated WebGLBuffer.
  29344. */
  29345. VertexBuffer.prototype.update = function (data) {
  29346. return this._buffer.update(data);
  29347. };
  29348. /**
  29349. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29350. * Returns the directly updated WebGLBuffer.
  29351. * @param data the new data
  29352. * @param offset the new offset
  29353. * @param useBytes set to true if the offset is in bytes
  29354. */
  29355. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29356. if (useBytes === void 0) { useBytes = false; }
  29357. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29358. };
  29359. /**
  29360. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29361. */
  29362. VertexBuffer.prototype.dispose = function () {
  29363. if (this._ownsBuffer) {
  29364. this._buffer.dispose();
  29365. }
  29366. };
  29367. /**
  29368. * Enumerates each value of this vertex buffer as numbers.
  29369. * @param count the number of values to enumerate
  29370. * @param callback the callback function called for each value
  29371. */
  29372. VertexBuffer.prototype.forEach = function (count, callback) {
  29373. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29374. };
  29375. Object.defineProperty(VertexBuffer, "PositionKind", {
  29376. get: function () {
  29377. return VertexBuffer._PositionKind;
  29378. },
  29379. enumerable: true,
  29380. configurable: true
  29381. });
  29382. Object.defineProperty(VertexBuffer, "NormalKind", {
  29383. get: function () {
  29384. return VertexBuffer._NormalKind;
  29385. },
  29386. enumerable: true,
  29387. configurable: true
  29388. });
  29389. Object.defineProperty(VertexBuffer, "TangentKind", {
  29390. get: function () {
  29391. return VertexBuffer._TangentKind;
  29392. },
  29393. enumerable: true,
  29394. configurable: true
  29395. });
  29396. Object.defineProperty(VertexBuffer, "UVKind", {
  29397. get: function () {
  29398. return VertexBuffer._UVKind;
  29399. },
  29400. enumerable: true,
  29401. configurable: true
  29402. });
  29403. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29404. get: function () {
  29405. return VertexBuffer._UV2Kind;
  29406. },
  29407. enumerable: true,
  29408. configurable: true
  29409. });
  29410. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29411. get: function () {
  29412. return VertexBuffer._UV3Kind;
  29413. },
  29414. enumerable: true,
  29415. configurable: true
  29416. });
  29417. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29418. get: function () {
  29419. return VertexBuffer._UV4Kind;
  29420. },
  29421. enumerable: true,
  29422. configurable: true
  29423. });
  29424. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29425. get: function () {
  29426. return VertexBuffer._UV5Kind;
  29427. },
  29428. enumerable: true,
  29429. configurable: true
  29430. });
  29431. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29432. get: function () {
  29433. return VertexBuffer._UV6Kind;
  29434. },
  29435. enumerable: true,
  29436. configurable: true
  29437. });
  29438. Object.defineProperty(VertexBuffer, "ColorKind", {
  29439. get: function () {
  29440. return VertexBuffer._ColorKind;
  29441. },
  29442. enumerable: true,
  29443. configurable: true
  29444. });
  29445. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29446. get: function () {
  29447. return VertexBuffer._MatricesIndicesKind;
  29448. },
  29449. enumerable: true,
  29450. configurable: true
  29451. });
  29452. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29453. get: function () {
  29454. return VertexBuffer._MatricesWeightsKind;
  29455. },
  29456. enumerable: true,
  29457. configurable: true
  29458. });
  29459. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29460. get: function () {
  29461. return VertexBuffer._MatricesIndicesExtraKind;
  29462. },
  29463. enumerable: true,
  29464. configurable: true
  29465. });
  29466. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29467. get: function () {
  29468. return VertexBuffer._MatricesWeightsExtraKind;
  29469. },
  29470. enumerable: true,
  29471. configurable: true
  29472. });
  29473. /**
  29474. * Deduces the stride given a kind.
  29475. * @param kind The kind string to deduce
  29476. * @returns The deduced stride
  29477. */
  29478. VertexBuffer.DeduceStride = function (kind) {
  29479. switch (kind) {
  29480. case VertexBuffer.UVKind:
  29481. case VertexBuffer.UV2Kind:
  29482. case VertexBuffer.UV3Kind:
  29483. case VertexBuffer.UV4Kind:
  29484. case VertexBuffer.UV5Kind:
  29485. case VertexBuffer.UV6Kind:
  29486. return 2;
  29487. case VertexBuffer.NormalKind:
  29488. case VertexBuffer.PositionKind:
  29489. return 3;
  29490. case VertexBuffer.ColorKind:
  29491. case VertexBuffer.MatricesIndicesKind:
  29492. case VertexBuffer.MatricesIndicesExtraKind:
  29493. case VertexBuffer.MatricesWeightsKind:
  29494. case VertexBuffer.MatricesWeightsExtraKind:
  29495. case VertexBuffer.TangentKind:
  29496. return 4;
  29497. default:
  29498. throw new Error("Invalid kind '" + kind + "'");
  29499. }
  29500. };
  29501. /**
  29502. * Gets the byte length of the given type.
  29503. * @param type the type
  29504. * @returns the number of bytes
  29505. */
  29506. VertexBuffer.GetTypeByteLength = function (type) {
  29507. switch (type) {
  29508. case VertexBuffer.BYTE:
  29509. case VertexBuffer.UNSIGNED_BYTE:
  29510. return 1;
  29511. case VertexBuffer.SHORT:
  29512. case VertexBuffer.UNSIGNED_SHORT:
  29513. return 2;
  29514. case VertexBuffer.INT:
  29515. case VertexBuffer.FLOAT:
  29516. return 4;
  29517. default:
  29518. throw new Error("Invalid type '" + type + "'");
  29519. }
  29520. };
  29521. /**
  29522. * Enumerates each value of the given parameters as numbers.
  29523. * @param data the data to enumerate
  29524. * @param byteOffset the byte offset of the data
  29525. * @param byteStride the byte stride of the data
  29526. * @param componentCount the number of components per element
  29527. * @param componentType the type of the component
  29528. * @param count the total number of components
  29529. * @param normalized whether the data is normalized
  29530. * @param callback the callback function called for each value
  29531. */
  29532. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29533. if (data instanceof Array) {
  29534. var offset = byteOffset / 4;
  29535. var stride = byteStride / 4;
  29536. for (var index = 0; index < count; index += componentCount) {
  29537. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29538. callback(data[offset + componentIndex], index + componentIndex);
  29539. }
  29540. offset += stride;
  29541. }
  29542. }
  29543. else {
  29544. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29545. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29546. for (var index = 0; index < count; index += componentCount) {
  29547. var componentByteOffset = byteOffset;
  29548. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29549. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29550. callback(value, index + componentIndex);
  29551. componentByteOffset += componentByteLength;
  29552. }
  29553. byteOffset += byteStride;
  29554. }
  29555. }
  29556. };
  29557. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29558. switch (type) {
  29559. case VertexBuffer.BYTE: {
  29560. var value = dataView.getInt8(byteOffset);
  29561. if (normalized) {
  29562. value = Math.max(value / 127, -1);
  29563. }
  29564. return value;
  29565. }
  29566. case VertexBuffer.UNSIGNED_BYTE: {
  29567. var value = dataView.getUint8(byteOffset);
  29568. if (normalized) {
  29569. value = value / 255;
  29570. }
  29571. return value;
  29572. }
  29573. case VertexBuffer.SHORT: {
  29574. var value = dataView.getInt16(byteOffset, true);
  29575. if (normalized) {
  29576. value = Math.max(value / 16383, -1);
  29577. }
  29578. return value;
  29579. }
  29580. case VertexBuffer.UNSIGNED_SHORT: {
  29581. var value = dataView.getUint16(byteOffset, true);
  29582. if (normalized) {
  29583. value = value / 65535;
  29584. }
  29585. return value;
  29586. }
  29587. case VertexBuffer.FLOAT: {
  29588. return dataView.getFloat32(byteOffset, true);
  29589. }
  29590. default: {
  29591. throw new Error("Invalid component type " + type);
  29592. }
  29593. }
  29594. };
  29595. /**
  29596. * The byte type.
  29597. */
  29598. VertexBuffer.BYTE = 5120;
  29599. /**
  29600. * The unsigned byte type.
  29601. */
  29602. VertexBuffer.UNSIGNED_BYTE = 5121;
  29603. /**
  29604. * The short type.
  29605. */
  29606. VertexBuffer.SHORT = 5122;
  29607. /**
  29608. * The unsigned short type.
  29609. */
  29610. VertexBuffer.UNSIGNED_SHORT = 5123;
  29611. /**
  29612. * The integer type.
  29613. */
  29614. VertexBuffer.INT = 5124;
  29615. /**
  29616. * The unsigned integer type.
  29617. */
  29618. VertexBuffer.UNSIGNED_INT = 5125;
  29619. /**
  29620. * The float type.
  29621. */
  29622. VertexBuffer.FLOAT = 5126;
  29623. // Enums
  29624. VertexBuffer._PositionKind = "position";
  29625. VertexBuffer._NormalKind = "normal";
  29626. VertexBuffer._TangentKind = "tangent";
  29627. VertexBuffer._UVKind = "uv";
  29628. VertexBuffer._UV2Kind = "uv2";
  29629. VertexBuffer._UV3Kind = "uv3";
  29630. VertexBuffer._UV4Kind = "uv4";
  29631. VertexBuffer._UV5Kind = "uv5";
  29632. VertexBuffer._UV6Kind = "uv6";
  29633. VertexBuffer._ColorKind = "color";
  29634. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29635. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29636. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29637. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29638. return VertexBuffer;
  29639. }());
  29640. BABYLON.VertexBuffer = VertexBuffer;
  29641. })(BABYLON || (BABYLON = {}));
  29642. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29643. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29644. var BABYLON;
  29645. (function (BABYLON) {
  29646. /**
  29647. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29648. */
  29649. var DummyInternalTextureTracker = /** @class */ (function () {
  29650. function DummyInternalTextureTracker() {
  29651. /**
  29652. * Gets or set the previous tracker in the list
  29653. */
  29654. this.previous = null;
  29655. /**
  29656. * Gets or set the next tracker in the list
  29657. */
  29658. this.next = null;
  29659. }
  29660. return DummyInternalTextureTracker;
  29661. }());
  29662. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29663. })(BABYLON || (BABYLON = {}));
  29664. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29665. var BABYLON;
  29666. (function (BABYLON) {
  29667. /**
  29668. * Class used to store data associated with WebGL texture data for the engine
  29669. * This class should not be used directly
  29670. */
  29671. var InternalTexture = /** @class */ (function () {
  29672. /**
  29673. * Creates a new InternalTexture
  29674. * @param engine defines the engine to use
  29675. * @param dataSource defines the type of data that will be used
  29676. */
  29677. function InternalTexture(engine, dataSource) {
  29678. /**
  29679. * Observable called when the texture is loaded
  29680. */
  29681. this.onLoadedObservable = new BABYLON.Observable();
  29682. /**
  29683. * Gets or set the previous tracker in the list
  29684. */
  29685. this.previous = null;
  29686. /**
  29687. * Gets or set the next tracker in the list
  29688. */
  29689. this.next = null;
  29690. // Private
  29691. /** @hidden */
  29692. this._initialSlot = -1;
  29693. /** @hidden */
  29694. this._designatedSlot = -1;
  29695. /** @hidden */
  29696. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29697. /** @hidden */
  29698. this._comparisonFunction = 0;
  29699. /** @hidden */
  29700. this._sphericalPolynomial = null;
  29701. /** @hidden */
  29702. this._lodGenerationScale = 0;
  29703. /** @hidden */
  29704. this._lodGenerationOffset = 0;
  29705. /** @hidden */
  29706. this._isRGBD = false;
  29707. /** @hidden */
  29708. this._references = 1;
  29709. this._engine = engine;
  29710. this._dataSource = dataSource;
  29711. this._webGLTexture = engine._createTexture();
  29712. }
  29713. /**
  29714. * Gets the Engine the texture belongs to.
  29715. * @returns The babylon engine
  29716. */
  29717. InternalTexture.prototype.getEngine = function () {
  29718. return this._engine;
  29719. };
  29720. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29721. /**
  29722. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29723. */
  29724. get: function () {
  29725. return this._dataSource;
  29726. },
  29727. enumerable: true,
  29728. configurable: true
  29729. });
  29730. /**
  29731. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29732. */
  29733. InternalTexture.prototype.incrementReferences = function () {
  29734. this._references++;
  29735. };
  29736. /**
  29737. * Change the size of the texture (not the size of the content)
  29738. * @param width defines the new width
  29739. * @param height defines the new height
  29740. * @param depth defines the new depth (1 by default)
  29741. */
  29742. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29743. if (depth === void 0) { depth = 1; }
  29744. this.width = width;
  29745. this.height = height;
  29746. this.depth = depth;
  29747. this.baseWidth = width;
  29748. this.baseHeight = height;
  29749. this.baseDepth = depth;
  29750. this._size = width * height * depth;
  29751. };
  29752. /** @hidden */
  29753. InternalTexture.prototype._rebuild = function () {
  29754. var _this = this;
  29755. var proxy;
  29756. this.isReady = false;
  29757. this._cachedCoordinatesMode = null;
  29758. this._cachedWrapU = null;
  29759. this._cachedWrapV = null;
  29760. this._cachedAnisotropicFilteringLevel = null;
  29761. switch (this._dataSource) {
  29762. case InternalTexture.DATASOURCE_TEMP:
  29763. return;
  29764. case InternalTexture.DATASOURCE_URL:
  29765. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29766. _this.isReady = true;
  29767. }, null, this._buffer, undefined, this.format);
  29768. proxy._swapAndDie(this);
  29769. return;
  29770. case InternalTexture.DATASOURCE_RAW:
  29771. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29772. proxy._swapAndDie(this);
  29773. this.isReady = true;
  29774. return;
  29775. case InternalTexture.DATASOURCE_RAW3D:
  29776. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29777. proxy._swapAndDie(this);
  29778. this.isReady = true;
  29779. return;
  29780. case InternalTexture.DATASOURCE_DYNAMIC:
  29781. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29782. proxy._swapAndDie(this);
  29783. // The engine will make sure to update content so no need to flag it as isReady = true
  29784. return;
  29785. case InternalTexture.DATASOURCE_RENDERTARGET:
  29786. var options = new BABYLON.RenderTargetCreationOptions();
  29787. options.generateDepthBuffer = this._generateDepthBuffer;
  29788. options.generateMipMaps = this.generateMipMaps;
  29789. options.generateStencilBuffer = this._generateStencilBuffer;
  29790. options.samplingMode = this.samplingMode;
  29791. options.type = this.type;
  29792. if (this.isCube) {
  29793. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29794. }
  29795. else {
  29796. var size = {
  29797. width: this.width,
  29798. height: this.height
  29799. };
  29800. proxy = this._engine.createRenderTargetTexture(size, options);
  29801. }
  29802. proxy._swapAndDie(this);
  29803. this.isReady = true;
  29804. return;
  29805. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29806. var depthTextureOptions = {
  29807. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29808. comparisonFunction: this._comparisonFunction,
  29809. generateStencil: this._generateStencilBuffer,
  29810. isCube: this.isCube
  29811. };
  29812. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29813. proxy._swapAndDie(this);
  29814. this.isReady = true;
  29815. return;
  29816. case InternalTexture.DATASOURCE_CUBE:
  29817. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29818. _this.isReady = true;
  29819. }, null, this.format, this._extension);
  29820. proxy._swapAndDie(this);
  29821. return;
  29822. case InternalTexture.DATASOURCE_CUBERAW:
  29823. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29824. proxy._swapAndDie(this);
  29825. this.isReady = true;
  29826. return;
  29827. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29828. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29829. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29830. _this.isReady = true;
  29831. });
  29832. proxy._swapAndDie(this);
  29833. return;
  29834. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29835. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29836. if (proxy) {
  29837. proxy._swapAndDie(_this);
  29838. }
  29839. _this.isReady = true;
  29840. }, null, this.format, this._extension);
  29841. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29842. return;
  29843. }
  29844. };
  29845. /** @hidden */
  29846. InternalTexture.prototype._swapAndDie = function (target) {
  29847. target._webGLTexture = this._webGLTexture;
  29848. if (this._framebuffer) {
  29849. target._framebuffer = this._framebuffer;
  29850. }
  29851. if (this._depthStencilBuffer) {
  29852. target._depthStencilBuffer = this._depthStencilBuffer;
  29853. }
  29854. if (this._lodTextureHigh) {
  29855. if (target._lodTextureHigh) {
  29856. target._lodTextureHigh.dispose();
  29857. }
  29858. target._lodTextureHigh = this._lodTextureHigh;
  29859. }
  29860. if (this._lodTextureMid) {
  29861. if (target._lodTextureMid) {
  29862. target._lodTextureMid.dispose();
  29863. }
  29864. target._lodTextureMid = this._lodTextureMid;
  29865. }
  29866. if (this._lodTextureLow) {
  29867. if (target._lodTextureLow) {
  29868. target._lodTextureLow.dispose();
  29869. }
  29870. target._lodTextureLow = this._lodTextureLow;
  29871. }
  29872. var cache = this._engine.getLoadedTexturesCache();
  29873. var index = cache.indexOf(this);
  29874. if (index !== -1) {
  29875. cache.splice(index, 1);
  29876. }
  29877. };
  29878. /**
  29879. * Dispose the current allocated resources
  29880. */
  29881. InternalTexture.prototype.dispose = function () {
  29882. if (!this._webGLTexture) {
  29883. return;
  29884. }
  29885. this._references--;
  29886. if (this._references === 0) {
  29887. this._engine._releaseTexture(this);
  29888. this._webGLTexture = null;
  29889. this.previous = null;
  29890. this.next = null;
  29891. }
  29892. };
  29893. /**
  29894. * The source of the texture data is unknown
  29895. */
  29896. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29897. /**
  29898. * Texture data comes from an URL
  29899. */
  29900. InternalTexture.DATASOURCE_URL = 1;
  29901. /**
  29902. * Texture data is only used for temporary storage
  29903. */
  29904. InternalTexture.DATASOURCE_TEMP = 2;
  29905. /**
  29906. * Texture data comes from raw data (ArrayBuffer)
  29907. */
  29908. InternalTexture.DATASOURCE_RAW = 3;
  29909. /**
  29910. * Texture content is dynamic (video or dynamic texture)
  29911. */
  29912. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29913. /**
  29914. * Texture content is generated by rendering to it
  29915. */
  29916. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29917. /**
  29918. * Texture content is part of a multi render target process
  29919. */
  29920. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29921. /**
  29922. * Texture data comes from a cube data file
  29923. */
  29924. InternalTexture.DATASOURCE_CUBE = 7;
  29925. /**
  29926. * Texture data comes from a raw cube data
  29927. */
  29928. InternalTexture.DATASOURCE_CUBERAW = 8;
  29929. /**
  29930. * Texture data come from a prefiltered cube data file
  29931. */
  29932. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29933. /**
  29934. * Texture content is raw 3D data
  29935. */
  29936. InternalTexture.DATASOURCE_RAW3D = 10;
  29937. /**
  29938. * Texture content is a depth texture
  29939. */
  29940. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29941. /**
  29942. * Texture data comes from a raw cube data encoded with RGBD
  29943. */
  29944. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29945. return InternalTexture;
  29946. }());
  29947. BABYLON.InternalTexture = InternalTexture;
  29948. })(BABYLON || (BABYLON = {}));
  29949. //# sourceMappingURL=babylon.internalTexture.js.map
  29950. var BABYLON;
  29951. (function (BABYLON) {
  29952. var BaseTexture = /** @class */ (function () {
  29953. function BaseTexture(scene) {
  29954. this._hasAlpha = false;
  29955. this.getAlphaFromRGB = false;
  29956. this.level = 1;
  29957. this.coordinatesIndex = 0;
  29958. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29959. /**
  29960. * | Value | Type | Description |
  29961. * | ----- | ------------------ | ----------- |
  29962. * | 0 | CLAMP_ADDRESSMODE | |
  29963. * | 1 | WRAP_ADDRESSMODE | |
  29964. * | 2 | MIRROR_ADDRESSMODE | |
  29965. */
  29966. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29967. /**
  29968. * | Value | Type | Description |
  29969. * | ----- | ------------------ | ----------- |
  29970. * | 0 | CLAMP_ADDRESSMODE | |
  29971. * | 1 | WRAP_ADDRESSMODE | |
  29972. * | 2 | MIRROR_ADDRESSMODE | |
  29973. */
  29974. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29975. /**
  29976. * | Value | Type | Description |
  29977. * | ----- | ------------------ | ----------- |
  29978. * | 0 | CLAMP_ADDRESSMODE | |
  29979. * | 1 | WRAP_ADDRESSMODE | |
  29980. * | 2 | MIRROR_ADDRESSMODE | |
  29981. */
  29982. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29983. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29984. this.isCube = false;
  29985. this.is3D = false;
  29986. this.gammaSpace = true;
  29987. this.invertZ = false;
  29988. this.lodLevelInAlpha = false;
  29989. this.isRenderTarget = false;
  29990. this.animations = new Array();
  29991. /**
  29992. * An event triggered when the texture is disposed.
  29993. */
  29994. this.onDisposeObservable = new BABYLON.Observable();
  29995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29996. this._cachedSize = BABYLON.Size.Zero();
  29997. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29998. if (this._scene) {
  29999. this._scene.textures.push(this);
  30000. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30001. }
  30002. this._uid = null;
  30003. }
  30004. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30005. get: function () {
  30006. return this._hasAlpha;
  30007. },
  30008. set: function (value) {
  30009. if (this._hasAlpha === value) {
  30010. return;
  30011. }
  30012. this._hasAlpha = value;
  30013. if (this._scene) {
  30014. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30015. }
  30016. },
  30017. enumerable: true,
  30018. configurable: true
  30019. });
  30020. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30021. get: function () {
  30022. return this._coordinatesMode;
  30023. },
  30024. /**
  30025. * How a texture is mapped.
  30026. *
  30027. * | Value | Type | Description |
  30028. * | ----- | ----------------------------------- | ----------- |
  30029. * | 0 | EXPLICIT_MODE | |
  30030. * | 1 | SPHERICAL_MODE | |
  30031. * | 2 | PLANAR_MODE | |
  30032. * | 3 | CUBIC_MODE | |
  30033. * | 4 | PROJECTION_MODE | |
  30034. * | 5 | SKYBOX_MODE | |
  30035. * | 6 | INVCUBIC_MODE | |
  30036. * | 7 | EQUIRECTANGULAR_MODE | |
  30037. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30038. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30039. */
  30040. set: function (value) {
  30041. if (this._coordinatesMode === value) {
  30042. return;
  30043. }
  30044. this._coordinatesMode = value;
  30045. if (this._scene) {
  30046. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30047. }
  30048. },
  30049. enumerable: true,
  30050. configurable: true
  30051. });
  30052. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30053. /**
  30054. * Gets whether or not the texture contains RGBD data.
  30055. */
  30056. get: function () {
  30057. return this._texture != null && this._texture._isRGBD;
  30058. },
  30059. enumerable: true,
  30060. configurable: true
  30061. });
  30062. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30063. get: function () {
  30064. if (this._texture)
  30065. return this._texture._lodGenerationOffset;
  30066. return 0.0;
  30067. },
  30068. set: function (value) {
  30069. if (this._texture)
  30070. this._texture._lodGenerationOffset = value;
  30071. },
  30072. enumerable: true,
  30073. configurable: true
  30074. });
  30075. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30076. get: function () {
  30077. if (this._texture)
  30078. return this._texture._lodGenerationScale;
  30079. return 0.0;
  30080. },
  30081. set: function (value) {
  30082. if (this._texture)
  30083. this._texture._lodGenerationScale = value;
  30084. },
  30085. enumerable: true,
  30086. configurable: true
  30087. });
  30088. Object.defineProperty(BaseTexture.prototype, "uid", {
  30089. get: function () {
  30090. if (!this._uid) {
  30091. this._uid = BABYLON.Tools.RandomId();
  30092. }
  30093. return this._uid;
  30094. },
  30095. enumerable: true,
  30096. configurable: true
  30097. });
  30098. BaseTexture.prototype.toString = function () {
  30099. return this.name;
  30100. };
  30101. BaseTexture.prototype.getClassName = function () {
  30102. return "BaseTexture";
  30103. };
  30104. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30105. set: function (callback) {
  30106. if (this._onDisposeObserver) {
  30107. this.onDisposeObservable.remove(this._onDisposeObserver);
  30108. }
  30109. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30110. },
  30111. enumerable: true,
  30112. configurable: true
  30113. });
  30114. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30115. get: function () {
  30116. return true;
  30117. },
  30118. enumerable: true,
  30119. configurable: true
  30120. });
  30121. BaseTexture.prototype.getScene = function () {
  30122. return this._scene;
  30123. };
  30124. BaseTexture.prototype.getTextureMatrix = function () {
  30125. return BABYLON.Matrix.IdentityReadOnly;
  30126. };
  30127. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30128. return BABYLON.Matrix.IdentityReadOnly;
  30129. };
  30130. BaseTexture.prototype.getInternalTexture = function () {
  30131. return this._texture;
  30132. };
  30133. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30134. return !this.isBlocking || this.isReady();
  30135. };
  30136. BaseTexture.prototype.isReady = function () {
  30137. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30138. this.delayLoad();
  30139. return false;
  30140. }
  30141. if (this._texture) {
  30142. return this._texture.isReady;
  30143. }
  30144. return false;
  30145. };
  30146. BaseTexture.prototype.getSize = function () {
  30147. if (this._texture) {
  30148. if (this._texture.width) {
  30149. this._cachedSize.width = this._texture.width;
  30150. this._cachedSize.height = this._texture.height;
  30151. return this._cachedSize;
  30152. }
  30153. if (this._texture._size) {
  30154. this._cachedSize.width = this._texture._size;
  30155. this._cachedSize.height = this._texture._size;
  30156. return this._cachedSize;
  30157. }
  30158. }
  30159. return this._cachedSize;
  30160. };
  30161. BaseTexture.prototype.getBaseSize = function () {
  30162. if (!this.isReady() || !this._texture)
  30163. return BABYLON.Size.Zero();
  30164. if (this._texture._size) {
  30165. return new BABYLON.Size(this._texture._size, this._texture._size);
  30166. }
  30167. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30168. };
  30169. BaseTexture.prototype.scale = function (ratio) {
  30170. };
  30171. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30172. get: function () {
  30173. return false;
  30174. },
  30175. enumerable: true,
  30176. configurable: true
  30177. });
  30178. /** @hidden */
  30179. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30180. if (!this._scene) {
  30181. return null;
  30182. }
  30183. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30184. for (var index = 0; index < texturesCache.length; index++) {
  30185. var texturesCacheEntry = texturesCache[index];
  30186. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30187. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30188. texturesCacheEntry.incrementReferences();
  30189. return texturesCacheEntry;
  30190. }
  30191. }
  30192. }
  30193. return null;
  30194. };
  30195. /** @hidden */
  30196. BaseTexture.prototype._rebuild = function () {
  30197. };
  30198. BaseTexture.prototype.delayLoad = function () {
  30199. };
  30200. BaseTexture.prototype.clone = function () {
  30201. return null;
  30202. };
  30203. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30204. get: function () {
  30205. if (!this._texture) {
  30206. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30207. }
  30208. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30209. },
  30210. enumerable: true,
  30211. configurable: true
  30212. });
  30213. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30214. get: function () {
  30215. if (!this._texture) {
  30216. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30217. }
  30218. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30219. },
  30220. enumerable: true,
  30221. configurable: true
  30222. });
  30223. /**
  30224. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30225. * This will returns an RGBA array buffer containing either in values (0-255) or
  30226. * float values (0-1) depending of the underlying buffer type.
  30227. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30228. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30229. * @param buffer defines a user defined buffer to fill with data (can be null)
  30230. * @returns The Array buffer containing the pixels data.
  30231. */
  30232. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30233. if (faceIndex === void 0) { faceIndex = 0; }
  30234. if (level === void 0) { level = 0; }
  30235. if (buffer === void 0) { buffer = null; }
  30236. if (!this._texture) {
  30237. return null;
  30238. }
  30239. var size = this.getSize();
  30240. var width = size.width;
  30241. var height = size.height;
  30242. var scene = this.getScene();
  30243. if (!scene) {
  30244. return null;
  30245. }
  30246. var engine = scene.getEngine();
  30247. if (level != 0) {
  30248. width = width / Math.pow(2, level);
  30249. height = height / Math.pow(2, level);
  30250. width = Math.round(width);
  30251. height = Math.round(height);
  30252. }
  30253. if (this._texture.isCube) {
  30254. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30255. }
  30256. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30257. };
  30258. BaseTexture.prototype.releaseInternalTexture = function () {
  30259. if (this._texture) {
  30260. this._texture.dispose();
  30261. this._texture = null;
  30262. }
  30263. };
  30264. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30265. get: function () {
  30266. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30267. return null;
  30268. }
  30269. if (!this._texture._sphericalPolynomial) {
  30270. this._texture._sphericalPolynomial =
  30271. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30272. }
  30273. return this._texture._sphericalPolynomial;
  30274. },
  30275. set: function (value) {
  30276. if (this._texture) {
  30277. this._texture._sphericalPolynomial = value;
  30278. }
  30279. },
  30280. enumerable: true,
  30281. configurable: true
  30282. });
  30283. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30284. get: function () {
  30285. if (this._texture) {
  30286. return this._texture._lodTextureHigh;
  30287. }
  30288. return null;
  30289. },
  30290. enumerable: true,
  30291. configurable: true
  30292. });
  30293. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30294. get: function () {
  30295. if (this._texture) {
  30296. return this._texture._lodTextureMid;
  30297. }
  30298. return null;
  30299. },
  30300. enumerable: true,
  30301. configurable: true
  30302. });
  30303. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30304. get: function () {
  30305. if (this._texture) {
  30306. return this._texture._lodTextureLow;
  30307. }
  30308. return null;
  30309. },
  30310. enumerable: true,
  30311. configurable: true
  30312. });
  30313. BaseTexture.prototype.dispose = function () {
  30314. if (!this._scene) {
  30315. return;
  30316. }
  30317. // Animations
  30318. this._scene.stopAnimation(this);
  30319. // Remove from scene
  30320. this._scene._removePendingData(this);
  30321. var index = this._scene.textures.indexOf(this);
  30322. if (index >= 0) {
  30323. this._scene.textures.splice(index, 1);
  30324. }
  30325. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30326. if (this._texture === undefined) {
  30327. return;
  30328. }
  30329. // Release
  30330. this.releaseInternalTexture();
  30331. // Callback
  30332. this.onDisposeObservable.notifyObservers(this);
  30333. this.onDisposeObservable.clear();
  30334. };
  30335. BaseTexture.prototype.serialize = function () {
  30336. if (!this.name) {
  30337. return null;
  30338. }
  30339. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30340. // Animations
  30341. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30342. return serializationObject;
  30343. };
  30344. BaseTexture.WhenAllReady = function (textures, callback) {
  30345. var numRemaining = textures.length;
  30346. if (numRemaining === 0) {
  30347. callback();
  30348. return;
  30349. }
  30350. var _loop_1 = function () {
  30351. texture = textures[i];
  30352. if (texture.isReady()) {
  30353. if (--numRemaining === 0) {
  30354. callback();
  30355. }
  30356. }
  30357. else {
  30358. onLoadObservable = texture.onLoadObservable;
  30359. var onLoadCallback_1 = function () {
  30360. onLoadObservable.removeCallback(onLoadCallback_1);
  30361. if (--numRemaining === 0) {
  30362. callback();
  30363. }
  30364. };
  30365. onLoadObservable.add(onLoadCallback_1);
  30366. }
  30367. };
  30368. var texture, onLoadObservable;
  30369. for (var i = 0; i < textures.length; i++) {
  30370. _loop_1();
  30371. }
  30372. };
  30373. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30374. __decorate([
  30375. BABYLON.serialize()
  30376. ], BaseTexture.prototype, "name", void 0);
  30377. __decorate([
  30378. BABYLON.serialize("hasAlpha")
  30379. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30380. __decorate([
  30381. BABYLON.serialize()
  30382. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30383. __decorate([
  30384. BABYLON.serialize()
  30385. ], BaseTexture.prototype, "level", void 0);
  30386. __decorate([
  30387. BABYLON.serialize()
  30388. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30389. __decorate([
  30390. BABYLON.serialize("coordinatesMode")
  30391. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30392. __decorate([
  30393. BABYLON.serialize()
  30394. ], BaseTexture.prototype, "wrapU", void 0);
  30395. __decorate([
  30396. BABYLON.serialize()
  30397. ], BaseTexture.prototype, "wrapV", void 0);
  30398. __decorate([
  30399. BABYLON.serialize()
  30400. ], BaseTexture.prototype, "wrapR", void 0);
  30401. __decorate([
  30402. BABYLON.serialize()
  30403. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30404. __decorate([
  30405. BABYLON.serialize()
  30406. ], BaseTexture.prototype, "isCube", void 0);
  30407. __decorate([
  30408. BABYLON.serialize()
  30409. ], BaseTexture.prototype, "is3D", void 0);
  30410. __decorate([
  30411. BABYLON.serialize()
  30412. ], BaseTexture.prototype, "gammaSpace", void 0);
  30413. __decorate([
  30414. BABYLON.serialize()
  30415. ], BaseTexture.prototype, "invertZ", void 0);
  30416. __decorate([
  30417. BABYLON.serialize()
  30418. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30419. __decorate([
  30420. BABYLON.serialize()
  30421. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30422. __decorate([
  30423. BABYLON.serialize()
  30424. ], BaseTexture.prototype, "lodGenerationScale", null);
  30425. __decorate([
  30426. BABYLON.serialize()
  30427. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30428. return BaseTexture;
  30429. }());
  30430. BABYLON.BaseTexture = BaseTexture;
  30431. })(BABYLON || (BABYLON = {}));
  30432. //# sourceMappingURL=babylon.baseTexture.js.map
  30433. var BABYLON;
  30434. (function (BABYLON) {
  30435. var Texture = /** @class */ (function (_super) {
  30436. __extends(Texture, _super);
  30437. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30438. if (noMipmap === void 0) { noMipmap = false; }
  30439. if (invertY === void 0) { invertY = true; }
  30440. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30441. if (onLoad === void 0) { onLoad = null; }
  30442. if (onError === void 0) { onError = null; }
  30443. if (buffer === void 0) { buffer = null; }
  30444. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30445. var _this = _super.call(this, scene) || this;
  30446. _this.uOffset = 0;
  30447. _this.vOffset = 0;
  30448. _this.uScale = 1.0;
  30449. _this.vScale = 1.0;
  30450. _this.uAng = 0;
  30451. _this.vAng = 0;
  30452. _this.wAng = 0;
  30453. /**
  30454. * Defines the center of rotation (U)
  30455. */
  30456. _this.uRotationCenter = 0.5;
  30457. /**
  30458. * Defines the center of rotation (V)
  30459. */
  30460. _this.vRotationCenter = 0.5;
  30461. /**
  30462. * Defines the center of rotation (W)
  30463. */
  30464. _this.wRotationCenter = 0.5;
  30465. _this._isBlocking = true;
  30466. _this.name = url || "";
  30467. _this.url = url;
  30468. _this._noMipmap = noMipmap;
  30469. _this._invertY = invertY;
  30470. _this._samplingMode = samplingMode;
  30471. _this._buffer = buffer;
  30472. _this._deleteBuffer = deleteBuffer;
  30473. if (format) {
  30474. _this._format = format;
  30475. }
  30476. scene = _this.getScene();
  30477. if (!scene) {
  30478. return _this;
  30479. }
  30480. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30481. var load = function () {
  30482. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30483. _this.onLoadObservable.notifyObservers(_this);
  30484. }
  30485. if (onLoad) {
  30486. onLoad();
  30487. }
  30488. if (!_this.isBlocking && scene) {
  30489. scene.resetCachedMaterial();
  30490. }
  30491. };
  30492. if (!_this.url) {
  30493. _this._delayedOnLoad = load;
  30494. _this._delayedOnError = onError;
  30495. return _this;
  30496. }
  30497. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30498. if (!_this._texture) {
  30499. if (!scene.useDelayedTextureLoading) {
  30500. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30501. if (deleteBuffer) {
  30502. delete _this._buffer;
  30503. }
  30504. }
  30505. else {
  30506. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30507. _this._delayedOnLoad = load;
  30508. _this._delayedOnError = onError;
  30509. }
  30510. }
  30511. else {
  30512. if (_this._texture.isReady) {
  30513. BABYLON.Tools.SetImmediate(function () { return load(); });
  30514. }
  30515. else {
  30516. _this._texture.onLoadedObservable.add(load);
  30517. }
  30518. }
  30519. return _this;
  30520. }
  30521. Object.defineProperty(Texture.prototype, "noMipmap", {
  30522. get: function () {
  30523. return this._noMipmap;
  30524. },
  30525. enumerable: true,
  30526. configurable: true
  30527. });
  30528. Object.defineProperty(Texture.prototype, "isBlocking", {
  30529. get: function () {
  30530. return this._isBlocking;
  30531. },
  30532. set: function (value) {
  30533. this._isBlocking = value;
  30534. },
  30535. enumerable: true,
  30536. configurable: true
  30537. });
  30538. Object.defineProperty(Texture.prototype, "samplingMode", {
  30539. get: function () {
  30540. return this._samplingMode;
  30541. },
  30542. enumerable: true,
  30543. configurable: true
  30544. });
  30545. /**
  30546. * Update the url (and optional buffer) of this texture if url was null during construction.
  30547. * @param url the url of the texture
  30548. * @param buffer the buffer of the texture (defaults to null)
  30549. */
  30550. Texture.prototype.updateURL = function (url, buffer) {
  30551. if (buffer === void 0) { buffer = null; }
  30552. if (this.url) {
  30553. throw new Error("URL is already set");
  30554. }
  30555. this.url = url;
  30556. this._buffer = buffer;
  30557. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30558. this.delayLoad();
  30559. };
  30560. Texture.prototype.delayLoad = function () {
  30561. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30562. return;
  30563. }
  30564. var scene = this.getScene();
  30565. if (!scene) {
  30566. return;
  30567. }
  30568. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30569. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30570. if (!this._texture) {
  30571. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30572. if (this._deleteBuffer) {
  30573. delete this._buffer;
  30574. }
  30575. }
  30576. else {
  30577. if (this._delayedOnLoad) {
  30578. if (this._texture.isReady) {
  30579. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30580. }
  30581. else {
  30582. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30583. }
  30584. }
  30585. }
  30586. this._delayedOnLoad = null;
  30587. this._delayedOnError = null;
  30588. };
  30589. /**
  30590. * Default is Trilinear mode.
  30591. *
  30592. * | Value | Type | Description |
  30593. * | ----- | ------------------ | ----------- |
  30594. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30595. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30596. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30597. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30598. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30599. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30600. * | 7 | NEAREST_LINEAR | |
  30601. * | 8 | NEAREST_NEAREST | |
  30602. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30603. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30604. * | 11 | LINEAR_LINEAR | |
  30605. * | 12 | LINEAR_NEAREST | |
  30606. *
  30607. * > _mag_: magnification filter (close to the viewer)
  30608. * > _min_: minification filter (far from the viewer)
  30609. * > _mip_: filter used between mip map levels
  30610. *
  30611. */
  30612. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30613. if (!this._texture) {
  30614. return;
  30615. }
  30616. var scene = this.getScene();
  30617. if (!scene) {
  30618. return;
  30619. }
  30620. this._samplingMode = samplingMode;
  30621. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30622. };
  30623. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30624. x *= this.uScale;
  30625. y *= this.vScale;
  30626. x -= this.uRotationCenter * this.uScale;
  30627. y -= this.vRotationCenter * this.vScale;
  30628. z -= this.wRotationCenter;
  30629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30630. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30631. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30632. t.z += this.wRotationCenter;
  30633. };
  30634. Texture.prototype.getTextureMatrix = function () {
  30635. var _this = this;
  30636. if (this.uOffset === this._cachedUOffset &&
  30637. this.vOffset === this._cachedVOffset &&
  30638. this.uScale === this._cachedUScale &&
  30639. this.vScale === this._cachedVScale &&
  30640. this.uAng === this._cachedUAng &&
  30641. this.vAng === this._cachedVAng &&
  30642. this.wAng === this._cachedWAng) {
  30643. return this._cachedTextureMatrix;
  30644. }
  30645. this._cachedUOffset = this.uOffset;
  30646. this._cachedVOffset = this.vOffset;
  30647. this._cachedUScale = this.uScale;
  30648. this._cachedVScale = this.vScale;
  30649. this._cachedUAng = this.uAng;
  30650. this._cachedVAng = this.vAng;
  30651. this._cachedWAng = this.wAng;
  30652. if (!this._cachedTextureMatrix) {
  30653. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30654. this._rowGenerationMatrix = new BABYLON.Matrix();
  30655. this._t0 = BABYLON.Vector3.Zero();
  30656. this._t1 = BABYLON.Vector3.Zero();
  30657. this._t2 = BABYLON.Vector3.Zero();
  30658. }
  30659. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30660. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30661. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30662. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30663. this._t1.subtractInPlace(this._t0);
  30664. this._t2.subtractInPlace(this._t0);
  30665. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30666. this._cachedTextureMatrix.m[0] = this._t1.x;
  30667. this._cachedTextureMatrix.m[1] = this._t1.y;
  30668. this._cachedTextureMatrix.m[2] = this._t1.z;
  30669. this._cachedTextureMatrix.m[4] = this._t2.x;
  30670. this._cachedTextureMatrix.m[5] = this._t2.y;
  30671. this._cachedTextureMatrix.m[6] = this._t2.z;
  30672. this._cachedTextureMatrix.m[8] = this._t0.x;
  30673. this._cachedTextureMatrix.m[9] = this._t0.y;
  30674. this._cachedTextureMatrix.m[10] = this._t0.z;
  30675. var scene = this.getScene();
  30676. if (!scene) {
  30677. return this._cachedTextureMatrix;
  30678. }
  30679. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30680. return mat.hasTexture(_this);
  30681. });
  30682. return this._cachedTextureMatrix;
  30683. };
  30684. Texture.prototype.getReflectionTextureMatrix = function () {
  30685. var _this = this;
  30686. var scene = this.getScene();
  30687. if (!scene) {
  30688. return this._cachedTextureMatrix;
  30689. }
  30690. if (this.uOffset === this._cachedUOffset &&
  30691. this.vOffset === this._cachedVOffset &&
  30692. this.uScale === this._cachedUScale &&
  30693. this.vScale === this._cachedVScale &&
  30694. this.coordinatesMode === this._cachedCoordinatesMode) {
  30695. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30696. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30697. return this._cachedTextureMatrix;
  30698. }
  30699. }
  30700. else {
  30701. return this._cachedTextureMatrix;
  30702. }
  30703. }
  30704. if (!this._cachedTextureMatrix) {
  30705. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30706. }
  30707. if (!this._projectionModeMatrix) {
  30708. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30709. }
  30710. this._cachedUOffset = this.uOffset;
  30711. this._cachedVOffset = this.vOffset;
  30712. this._cachedUScale = this.uScale;
  30713. this._cachedVScale = this.vScale;
  30714. this._cachedCoordinatesMode = this.coordinatesMode;
  30715. switch (this.coordinatesMode) {
  30716. case Texture.PLANAR_MODE:
  30717. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30718. this._cachedTextureMatrix[0] = this.uScale;
  30719. this._cachedTextureMatrix[5] = this.vScale;
  30720. this._cachedTextureMatrix[12] = this.uOffset;
  30721. this._cachedTextureMatrix[13] = this.vOffset;
  30722. break;
  30723. case Texture.PROJECTION_MODE:
  30724. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30725. this._projectionModeMatrix.m[0] = 0.5;
  30726. this._projectionModeMatrix.m[5] = -0.5;
  30727. this._projectionModeMatrix.m[10] = 0.0;
  30728. this._projectionModeMatrix.m[12] = 0.5;
  30729. this._projectionModeMatrix.m[13] = 0.5;
  30730. this._projectionModeMatrix.m[14] = 1.0;
  30731. this._projectionModeMatrix.m[15] = 1.0;
  30732. var projectionMatrix = scene.getProjectionMatrix();
  30733. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30734. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30735. break;
  30736. default:
  30737. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30738. break;
  30739. }
  30740. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30741. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30742. });
  30743. return this._cachedTextureMatrix;
  30744. };
  30745. Texture.prototype.clone = function () {
  30746. var _this = this;
  30747. return BABYLON.SerializationHelper.Clone(function () {
  30748. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30749. }, this);
  30750. };
  30751. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30752. get: function () {
  30753. if (!this._onLoadObservable) {
  30754. this._onLoadObservable = new BABYLON.Observable();
  30755. }
  30756. return this._onLoadObservable;
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Texture.prototype.serialize = function () {
  30762. var serializationObject = _super.prototype.serialize.call(this);
  30763. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30764. serializationObject.base64String = this._buffer;
  30765. serializationObject.name = serializationObject.name.replace("data:", "");
  30766. }
  30767. serializationObject.invertY = this._invertY;
  30768. serializationObject.samplingMode = this.samplingMode;
  30769. return serializationObject;
  30770. };
  30771. Texture.prototype.getClassName = function () {
  30772. return "Texture";
  30773. };
  30774. Texture.prototype.dispose = function () {
  30775. _super.prototype.dispose.call(this);
  30776. if (this._onLoadObservable) {
  30777. this._onLoadObservable.clear();
  30778. this._onLoadObservable = null;
  30779. }
  30780. this._delayedOnLoad = null;
  30781. this._delayedOnError = null;
  30782. };
  30783. // Statics
  30784. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30785. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30786. if (onLoad === void 0) { onLoad = null; }
  30787. if (onError === void 0) { onError = null; }
  30788. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30789. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30790. };
  30791. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30792. if (parsedTexture.customType) {
  30793. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30794. // Update Sampling Mode
  30795. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30796. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30797. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30798. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30799. }
  30800. }
  30801. return parsedCustomTexture;
  30802. }
  30803. if (parsedTexture.isCube) {
  30804. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30805. }
  30806. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30807. return null;
  30808. }
  30809. var texture = BABYLON.SerializationHelper.Parse(function () {
  30810. var generateMipMaps = true;
  30811. if (parsedTexture.noMipmap) {
  30812. generateMipMaps = false;
  30813. }
  30814. if (parsedTexture.mirrorPlane) {
  30815. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30816. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30817. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30818. return mirrorTexture;
  30819. }
  30820. else if (parsedTexture.isRenderTarget) {
  30821. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30822. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30823. return renderTargetTexture;
  30824. }
  30825. else {
  30826. var texture;
  30827. if (parsedTexture.base64String) {
  30828. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30829. }
  30830. else {
  30831. var url = rootUrl + parsedTexture.name;
  30832. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30833. url = parsedTexture.url;
  30834. }
  30835. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30836. }
  30837. return texture;
  30838. }
  30839. }, parsedTexture, scene);
  30840. // Update Sampling Mode
  30841. if (parsedTexture.samplingMode) {
  30842. var sampling = parsedTexture.samplingMode;
  30843. if (texture._samplingMode !== sampling) {
  30844. texture.updateSamplingMode(sampling);
  30845. }
  30846. }
  30847. // Animations
  30848. if (parsedTexture.animations) {
  30849. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30850. var parsedAnimation = parsedTexture.animations[animationIndex];
  30851. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30852. }
  30853. }
  30854. return texture;
  30855. };
  30856. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30857. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30858. if (noMipmap === void 0) { noMipmap = false; }
  30859. if (invertY === void 0) { invertY = true; }
  30860. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30861. if (onLoad === void 0) { onLoad = null; }
  30862. if (onError === void 0) { onError = null; }
  30863. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30864. if (name.substr(0, 5) !== "data:") {
  30865. name = "data:" + name;
  30866. }
  30867. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30868. };
  30869. // Constants
  30870. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30871. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30872. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30873. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30874. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30875. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30876. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30877. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30878. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30879. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30880. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30881. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30882. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30883. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30884. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30885. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30886. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30887. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30888. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30889. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30890. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30891. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30892. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30893. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30894. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30895. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30896. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30897. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30898. /**
  30899. * 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
  30900. */
  30901. Texture.UseSerializedUrlIfAny = false;
  30902. __decorate([
  30903. BABYLON.serialize()
  30904. ], Texture.prototype, "url", void 0);
  30905. __decorate([
  30906. BABYLON.serialize()
  30907. ], Texture.prototype, "uOffset", void 0);
  30908. __decorate([
  30909. BABYLON.serialize()
  30910. ], Texture.prototype, "vOffset", void 0);
  30911. __decorate([
  30912. BABYLON.serialize()
  30913. ], Texture.prototype, "uScale", void 0);
  30914. __decorate([
  30915. BABYLON.serialize()
  30916. ], Texture.prototype, "vScale", void 0);
  30917. __decorate([
  30918. BABYLON.serialize()
  30919. ], Texture.prototype, "uAng", void 0);
  30920. __decorate([
  30921. BABYLON.serialize()
  30922. ], Texture.prototype, "vAng", void 0);
  30923. __decorate([
  30924. BABYLON.serialize()
  30925. ], Texture.prototype, "wAng", void 0);
  30926. __decorate([
  30927. BABYLON.serialize()
  30928. ], Texture.prototype, "uRotationCenter", void 0);
  30929. __decorate([
  30930. BABYLON.serialize()
  30931. ], Texture.prototype, "vRotationCenter", void 0);
  30932. __decorate([
  30933. BABYLON.serialize()
  30934. ], Texture.prototype, "wRotationCenter", void 0);
  30935. __decorate([
  30936. BABYLON.serialize()
  30937. ], Texture.prototype, "isBlocking", null);
  30938. return Texture;
  30939. }(BABYLON.BaseTexture));
  30940. BABYLON.Texture = Texture;
  30941. })(BABYLON || (BABYLON = {}));
  30942. //# sourceMappingURL=babylon.texture.js.map
  30943. var BABYLON;
  30944. (function (BABYLON) {
  30945. /**
  30946. * @hidden
  30947. **/
  30948. var _InstancesBatch = /** @class */ (function () {
  30949. function _InstancesBatch() {
  30950. this.mustReturn = false;
  30951. this.visibleInstances = new Array();
  30952. this.renderSelf = new Array();
  30953. }
  30954. return _InstancesBatch;
  30955. }());
  30956. BABYLON._InstancesBatch = _InstancesBatch;
  30957. /**
  30958. * Class used to represent renderable models
  30959. */
  30960. var Mesh = /** @class */ (function (_super) {
  30961. __extends(Mesh, _super);
  30962. /**
  30963. * @constructor
  30964. * @param name The value used by scene.getMeshByName() to do a lookup.
  30965. * @param scene The scene to add this mesh to.
  30966. * @param parent The parent of this mesh, if it has one
  30967. * @param source An optional Mesh from which geometry is shared, cloned.
  30968. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30969. * When false, achieved by calling a clone(), also passing False.
  30970. * This will make creation of children, recursive.
  30971. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30972. */
  30973. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30974. if (scene === void 0) { scene = null; }
  30975. if (parent === void 0) { parent = null; }
  30976. if (source === void 0) { source = null; }
  30977. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30978. var _this = _super.call(this, name, scene) || this;
  30979. // Members
  30980. /**
  30981. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30982. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30983. */
  30984. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30985. /**
  30986. * Gets the list of instances created from this mesh
  30987. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30988. */
  30989. _this.instances = new Array();
  30990. _this._LODLevels = new Array();
  30991. /** @hidden */
  30992. _this._visibleInstances = {};
  30993. _this._renderIdForInstances = new Array();
  30994. _this._batchCache = new _InstancesBatch();
  30995. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30996. // Use by builder only to know what orientation were the mesh build in.
  30997. /** @hidden */
  30998. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30999. /**
  31000. * Use this property to change the original side orientation defined at construction time
  31001. */
  31002. _this.overrideMaterialSideOrientation = null;
  31003. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31004. // Will be used to save a source mesh reference, If any
  31005. _this._source = null;
  31006. scene = _this.getScene();
  31007. if (source) {
  31008. // Geometry
  31009. if (source._geometry) {
  31010. source._geometry.applyToMesh(_this);
  31011. }
  31012. // Deep copy
  31013. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31014. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31015. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31016. ], ["_poseMatrix"]);
  31017. // Source mesh
  31018. _this._source = source;
  31019. // Construction Params
  31020. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31021. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31022. var myAnyThis = _this;
  31023. var myAnySource = source;
  31024. myAnyThis._closePath = myAnySource._closePath;
  31025. myAnyThis._idx = myAnySource._idx;
  31026. myAnyThis.dashSize = myAnySource.dashSize;
  31027. myAnyThis.gapSize = myAnySource.gapSize;
  31028. myAnyThis.path3D = myAnySource.path3D;
  31029. myAnyThis.pathArray = myAnySource.pathArray;
  31030. myAnyThis.arc = myAnySource.arc;
  31031. myAnyThis.radius = myAnySource.radius;
  31032. // Animation ranges
  31033. if (_this._source._ranges) {
  31034. var ranges = _this._source._ranges;
  31035. for (var name in ranges) {
  31036. if (!ranges.hasOwnProperty(name)) {
  31037. continue;
  31038. }
  31039. if (!ranges[name]) {
  31040. continue;
  31041. }
  31042. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31043. }
  31044. }
  31045. // Metadata
  31046. if (source.metadata && source.metadata.clone) {
  31047. _this.metadata = source.metadata.clone();
  31048. }
  31049. else {
  31050. _this.metadata = source.metadata;
  31051. }
  31052. // Tags
  31053. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31054. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31055. }
  31056. // Parent
  31057. _this.parent = source.parent;
  31058. // Pivot
  31059. _this.setPivotMatrix(source.getPivotMatrix());
  31060. _this.id = name + "." + source.id;
  31061. // Material
  31062. _this.material = source.material;
  31063. var index;
  31064. if (!doNotCloneChildren) {
  31065. // Children
  31066. var directDescendants = source.getDescendants(true);
  31067. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31068. var child = directDescendants[index_1];
  31069. if (child.clone) {
  31070. child.clone(name + "." + child.name, _this);
  31071. }
  31072. }
  31073. }
  31074. // Physics clone
  31075. var physicsEngine = _this.getScene().getPhysicsEngine();
  31076. if (clonePhysicsImpostor && physicsEngine) {
  31077. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31078. if (impostor) {
  31079. _this.physicsImpostor = impostor.clone(_this);
  31080. }
  31081. }
  31082. // Particles
  31083. for (index = 0; index < scene.particleSystems.length; index++) {
  31084. var system = scene.particleSystems[index];
  31085. if (system.emitter === source) {
  31086. system.clone(system.name, _this);
  31087. }
  31088. }
  31089. _this.refreshBoundingInfo();
  31090. _this.computeWorldMatrix(true);
  31091. }
  31092. // Parent
  31093. if (parent !== null) {
  31094. _this.parent = parent;
  31095. }
  31096. return _this;
  31097. }
  31098. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31099. /**
  31100. * An event triggered before rendering the mesh
  31101. */
  31102. get: function () {
  31103. if (!this._onBeforeRenderObservable) {
  31104. this._onBeforeRenderObservable = new BABYLON.Observable();
  31105. }
  31106. return this._onBeforeRenderObservable;
  31107. },
  31108. enumerable: true,
  31109. configurable: true
  31110. });
  31111. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31112. /**
  31113. * An event triggered after rendering the mesh
  31114. */
  31115. get: function () {
  31116. if (!this._onAfterRenderObservable) {
  31117. this._onAfterRenderObservable = new BABYLON.Observable();
  31118. }
  31119. return this._onAfterRenderObservable;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31125. /**
  31126. * An event triggered before drawing the mesh
  31127. */
  31128. get: function () {
  31129. if (!this._onBeforeDrawObservable) {
  31130. this._onBeforeDrawObservable = new BABYLON.Observable();
  31131. }
  31132. return this._onBeforeDrawObservable;
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31138. /**
  31139. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31140. */
  31141. set: function (callback) {
  31142. if (this._onBeforeDrawObserver) {
  31143. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31144. }
  31145. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31146. },
  31147. enumerable: true,
  31148. configurable: true
  31149. });
  31150. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31151. /**
  31152. * Gets or sets the morph target manager
  31153. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31154. */
  31155. get: function () {
  31156. return this._morphTargetManager;
  31157. },
  31158. set: function (value) {
  31159. if (this._morphTargetManager === value) {
  31160. return;
  31161. }
  31162. this._morphTargetManager = value;
  31163. this._syncGeometryWithMorphTargetManager();
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. Object.defineProperty(Mesh.prototype, "source", {
  31169. /**
  31170. * Gets the source mesh (the one used to clone this one from)
  31171. */
  31172. get: function () {
  31173. return this._source;
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31179. /**
  31180. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31181. */
  31182. get: function () {
  31183. return this._unIndexed;
  31184. },
  31185. set: function (value) {
  31186. if (this._unIndexed !== value) {
  31187. this._unIndexed = value;
  31188. this._markSubMeshesAsAttributesDirty();
  31189. }
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. // Methods
  31195. /**
  31196. * Gets the class name
  31197. * @returns the string "Mesh".
  31198. */
  31199. Mesh.prototype.getClassName = function () {
  31200. return "Mesh";
  31201. };
  31202. /**
  31203. * Returns a description of this mesh
  31204. * @param fullDetails define if full details about this mesh must be used
  31205. * @returns a descriptive string representing this mesh
  31206. */
  31207. Mesh.prototype.toString = function (fullDetails) {
  31208. var ret = _super.prototype.toString.call(this, fullDetails);
  31209. ret += ", n vertices: " + this.getTotalVertices();
  31210. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31211. if (this.animations) {
  31212. for (var i = 0; i < this.animations.length; i++) {
  31213. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31214. }
  31215. }
  31216. if (fullDetails) {
  31217. if (this._geometry) {
  31218. var ib = this.getIndices();
  31219. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31220. if (vb && ib) {
  31221. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31222. }
  31223. }
  31224. else {
  31225. ret += ", flat shading: UNKNOWN";
  31226. }
  31227. }
  31228. return ret;
  31229. };
  31230. /** @hidden */
  31231. Mesh.prototype._unBindEffect = function () {
  31232. _super.prototype._unBindEffect.call(this);
  31233. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31234. var instance = _a[_i];
  31235. instance._unBindEffect();
  31236. }
  31237. };
  31238. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31239. /**
  31240. * Gets a boolean indicating if this mesh has LOD
  31241. */
  31242. get: function () {
  31243. return this._LODLevels.length > 0;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. /**
  31249. * Gets the list of MeshLODLevel associated with the current mesh
  31250. * @returns an array of MeshLODLevel
  31251. */
  31252. Mesh.prototype.getLODLevels = function () {
  31253. return this._LODLevels;
  31254. };
  31255. Mesh.prototype._sortLODLevels = function () {
  31256. this._LODLevels.sort(function (a, b) {
  31257. if (a.distance < b.distance) {
  31258. return 1;
  31259. }
  31260. if (a.distance > b.distance) {
  31261. return -1;
  31262. }
  31263. return 0;
  31264. });
  31265. };
  31266. /**
  31267. * Add a mesh as LOD level triggered at the given distance.
  31268. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31269. * @param distance The distance from the center of the object to show this level
  31270. * @param mesh The mesh to be added as LOD level (can be null)
  31271. * @return This mesh (for chaining)
  31272. */
  31273. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31274. if (mesh && mesh._masterMesh) {
  31275. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31276. return this;
  31277. }
  31278. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31279. this._LODLevels.push(level);
  31280. if (mesh) {
  31281. mesh._masterMesh = this;
  31282. }
  31283. this._sortLODLevels();
  31284. return this;
  31285. };
  31286. /**
  31287. * Returns the LOD level mesh at the passed distance or null if not found.
  31288. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31289. * @param distance The distance from the center of the object to show this level
  31290. * @returns a Mesh or `null`
  31291. */
  31292. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31293. for (var index = 0; index < this._LODLevels.length; index++) {
  31294. var level = this._LODLevels[index];
  31295. if (level.distance === distance) {
  31296. return level.mesh;
  31297. }
  31298. }
  31299. return null;
  31300. };
  31301. /**
  31302. * Remove a mesh from the LOD array
  31303. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31304. * @param mesh defines the mesh to be removed
  31305. * @return This mesh (for chaining)
  31306. */
  31307. Mesh.prototype.removeLODLevel = function (mesh) {
  31308. for (var index = 0; index < this._LODLevels.length; index++) {
  31309. if (this._LODLevels[index].mesh === mesh) {
  31310. this._LODLevels.splice(index, 1);
  31311. if (mesh) {
  31312. mesh._masterMesh = null;
  31313. }
  31314. }
  31315. }
  31316. this._sortLODLevels();
  31317. return this;
  31318. };
  31319. /**
  31320. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31321. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31322. * @param camera defines the camera to use to compute distance
  31323. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31324. * @return This mesh (for chaining)
  31325. */
  31326. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31327. if (!this._LODLevels || this._LODLevels.length === 0) {
  31328. return this;
  31329. }
  31330. var bSphere;
  31331. if (boundingSphere) {
  31332. bSphere = boundingSphere;
  31333. }
  31334. else {
  31335. var boundingInfo = this.getBoundingInfo();
  31336. bSphere = boundingInfo.boundingSphere;
  31337. }
  31338. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31339. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31340. if (this.onLODLevelSelection) {
  31341. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31342. }
  31343. return this;
  31344. }
  31345. for (var index = 0; index < this._LODLevels.length; index++) {
  31346. var level = this._LODLevels[index];
  31347. if (level.distance < distanceToCamera) {
  31348. if (level.mesh) {
  31349. level.mesh._preActivate();
  31350. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31351. }
  31352. if (this.onLODLevelSelection) {
  31353. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31354. }
  31355. return level.mesh;
  31356. }
  31357. }
  31358. if (this.onLODLevelSelection) {
  31359. this.onLODLevelSelection(distanceToCamera, this, this);
  31360. }
  31361. return this;
  31362. };
  31363. Object.defineProperty(Mesh.prototype, "geometry", {
  31364. /**
  31365. * Gets the mesh internal Geometry object
  31366. */
  31367. get: function () {
  31368. return this._geometry;
  31369. },
  31370. enumerable: true,
  31371. configurable: true
  31372. });
  31373. /**
  31374. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31375. * @returns the total number of vertices
  31376. */
  31377. Mesh.prototype.getTotalVertices = function () {
  31378. if (this._geometry === null || this._geometry === undefined) {
  31379. return 0;
  31380. }
  31381. return this._geometry.getTotalVertices();
  31382. };
  31383. /**
  31384. * Returns the content of an associated vertex buffer
  31385. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31386. * - BABYLON.VertexBuffer.PositionKind
  31387. * - BABYLON.VertexBuffer.UVKind
  31388. * - BABYLON.VertexBuffer.UV2Kind
  31389. * - BABYLON.VertexBuffer.UV3Kind
  31390. * - BABYLON.VertexBuffer.UV4Kind
  31391. * - BABYLON.VertexBuffer.UV5Kind
  31392. * - BABYLON.VertexBuffer.UV6Kind
  31393. * - BABYLON.VertexBuffer.ColorKind
  31394. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31395. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31396. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31397. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31398. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  31399. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31400. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31401. */
  31402. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31403. if (!this._geometry) {
  31404. return null;
  31405. }
  31406. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31407. };
  31408. /**
  31409. * Returns the mesh VertexBuffer object from the requested `kind`
  31410. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31411. * - BABYLON.VertexBuffer.PositionKind
  31412. * - BABYLON.VertexBuffer.UVKind
  31413. * - BABYLON.VertexBuffer.UV2Kind
  31414. * - BABYLON.VertexBuffer.UV3Kind
  31415. * - BABYLON.VertexBuffer.UV4Kind
  31416. * - BABYLON.VertexBuffer.UV5Kind
  31417. * - BABYLON.VertexBuffer.UV6Kind
  31418. * - BABYLON.VertexBuffer.ColorKind
  31419. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31420. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31421. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31422. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31423. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31424. */
  31425. Mesh.prototype.getVertexBuffer = function (kind) {
  31426. if (!this._geometry) {
  31427. return null;
  31428. }
  31429. return this._geometry.getVertexBuffer(kind);
  31430. };
  31431. /**
  31432. * Tests if a specific vertex buffer is associated with this mesh
  31433. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31434. * - BABYLON.VertexBuffer.PositionKind
  31435. * - BABYLON.VertexBuffer.UVKind
  31436. * - BABYLON.VertexBuffer.UV2Kind
  31437. * - BABYLON.VertexBuffer.UV3Kind
  31438. * - BABYLON.VertexBuffer.UV4Kind
  31439. * - BABYLON.VertexBuffer.UV5Kind
  31440. * - BABYLON.VertexBuffer.UV6Kind
  31441. * - BABYLON.VertexBuffer.ColorKind
  31442. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31443. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31444. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31445. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31446. * @returns a boolean
  31447. */
  31448. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31449. if (!this._geometry) {
  31450. if (this._delayInfo) {
  31451. return this._delayInfo.indexOf(kind) !== -1;
  31452. }
  31453. return false;
  31454. }
  31455. return this._geometry.isVerticesDataPresent(kind);
  31456. };
  31457. /**
  31458. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31459. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31460. * - BABYLON.VertexBuffer.PositionKind
  31461. * - BABYLON.VertexBuffer.UVKind
  31462. * - BABYLON.VertexBuffer.UV2Kind
  31463. * - BABYLON.VertexBuffer.UV3Kind
  31464. * - BABYLON.VertexBuffer.UV4Kind
  31465. * - BABYLON.VertexBuffer.UV5Kind
  31466. * - BABYLON.VertexBuffer.UV6Kind
  31467. * - BABYLON.VertexBuffer.ColorKind
  31468. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31469. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31470. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31471. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31472. * @returns a boolean
  31473. */
  31474. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31475. if (!this._geometry) {
  31476. if (this._delayInfo) {
  31477. return this._delayInfo.indexOf(kind) !== -1;
  31478. }
  31479. return false;
  31480. }
  31481. return this._geometry.isVertexBufferUpdatable(kind);
  31482. };
  31483. /**
  31484. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31485. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31486. * - BABYLON.VertexBuffer.PositionKind
  31487. * - BABYLON.VertexBuffer.UVKind
  31488. * - BABYLON.VertexBuffer.UV2Kind
  31489. * - BABYLON.VertexBuffer.UV3Kind
  31490. * - BABYLON.VertexBuffer.UV4Kind
  31491. * - BABYLON.VertexBuffer.UV5Kind
  31492. * - BABYLON.VertexBuffer.UV6Kind
  31493. * - BABYLON.VertexBuffer.ColorKind
  31494. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31495. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31496. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31497. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31498. * @returns an array of strings
  31499. */
  31500. Mesh.prototype.getVerticesDataKinds = function () {
  31501. if (!this._geometry) {
  31502. var result = new Array();
  31503. if (this._delayInfo) {
  31504. this._delayInfo.forEach(function (kind, index, array) {
  31505. result.push(kind);
  31506. });
  31507. }
  31508. return result;
  31509. }
  31510. return this._geometry.getVerticesDataKinds();
  31511. };
  31512. /**
  31513. * Returns a positive integer : the total number of indices in this mesh geometry.
  31514. * @returns the numner of indices or zero if the mesh has no geometry.
  31515. */
  31516. Mesh.prototype.getTotalIndices = function () {
  31517. if (!this._geometry) {
  31518. return 0;
  31519. }
  31520. return this._geometry.getTotalIndices();
  31521. };
  31522. /**
  31523. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31524. * @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.
  31525. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31526. * @returns the indices array or an empty array if the mesh has no geometry
  31527. */
  31528. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31529. if (!this._geometry) {
  31530. return [];
  31531. }
  31532. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31533. };
  31534. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31535. get: function () {
  31536. return this._masterMesh !== null && this._masterMesh !== undefined;
  31537. },
  31538. enumerable: true,
  31539. configurable: true
  31540. });
  31541. /**
  31542. * Determine if the current mesh is ready to be rendered
  31543. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31544. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31545. * @returns true if all associated assets are ready (material, textures, shaders)
  31546. */
  31547. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31548. if (completeCheck === void 0) { completeCheck = false; }
  31549. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31550. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31551. return false;
  31552. }
  31553. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31554. return false;
  31555. }
  31556. if (!this.subMeshes || this.subMeshes.length === 0) {
  31557. return true;
  31558. }
  31559. if (!completeCheck) {
  31560. return true;
  31561. }
  31562. var engine = this.getEngine();
  31563. var scene = this.getScene();
  31564. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31565. this.computeWorldMatrix();
  31566. var mat = this.material || scene.defaultMaterial;
  31567. if (mat) {
  31568. if (mat.storeEffectOnSubMeshes) {
  31569. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31570. var subMesh = _a[_i];
  31571. var effectiveMaterial = subMesh.getMaterial();
  31572. if (effectiveMaterial) {
  31573. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31574. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31575. return false;
  31576. }
  31577. }
  31578. else {
  31579. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31580. return false;
  31581. }
  31582. }
  31583. }
  31584. }
  31585. }
  31586. else {
  31587. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31588. return false;
  31589. }
  31590. }
  31591. }
  31592. // Shadows
  31593. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31594. var light = _c[_b];
  31595. var generator = light.getShadowGenerator();
  31596. if (generator) {
  31597. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31598. var subMesh = _e[_d];
  31599. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31600. return false;
  31601. }
  31602. }
  31603. }
  31604. }
  31605. // LOD
  31606. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31607. var lod = _g[_f];
  31608. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31609. return false;
  31610. }
  31611. }
  31612. return true;
  31613. };
  31614. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31615. /**
  31616. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  31617. */
  31618. get: function () {
  31619. return this._areNormalsFrozen;
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. /**
  31625. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  31626. * @returns the current mesh
  31627. */
  31628. Mesh.prototype.freezeNormals = function () {
  31629. this._areNormalsFrozen = true;
  31630. return this;
  31631. };
  31632. /**
  31633. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  31634. * @returns the current mesh
  31635. */
  31636. Mesh.prototype.unfreezeNormals = function () {
  31637. this._areNormalsFrozen = false;
  31638. return this;
  31639. };
  31640. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31641. /**
  31642. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31643. */
  31644. set: function (count) {
  31645. this._overridenInstanceCount = count;
  31646. },
  31647. enumerable: true,
  31648. configurable: true
  31649. });
  31650. // Methods
  31651. /** @hidden */
  31652. Mesh.prototype._preActivate = function () {
  31653. var sceneRenderId = this.getScene().getRenderId();
  31654. if (this._preActivateId === sceneRenderId) {
  31655. return this;
  31656. }
  31657. this._preActivateId = sceneRenderId;
  31658. this._visibleInstances = null;
  31659. return this;
  31660. };
  31661. /** @hidden */
  31662. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31663. if (this._visibleInstances) {
  31664. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31665. }
  31666. return this;
  31667. };
  31668. /** @hidden */
  31669. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31670. if (!this._visibleInstances) {
  31671. this._visibleInstances = {};
  31672. this._visibleInstances.defaultRenderId = renderId;
  31673. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31674. }
  31675. if (!this._visibleInstances[renderId]) {
  31676. this._visibleInstances[renderId] = new Array();
  31677. }
  31678. this._visibleInstances[renderId].push(instance);
  31679. return this;
  31680. };
  31681. /**
  31682. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31683. * This means the mesh underlying bounding box and sphere are recomputed.
  31684. * @returns the current mesh
  31685. */
  31686. Mesh.prototype.refreshBoundingInfo = function () {
  31687. return this._refreshBoundingInfo(false);
  31688. };
  31689. /** @hidden */
  31690. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31691. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31692. return this;
  31693. }
  31694. var data = this._getPositionData(applySkeleton);
  31695. if (data) {
  31696. var bias = this.geometry ? this.geometry.boundingBias : null;
  31697. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31698. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31699. }
  31700. if (this.subMeshes) {
  31701. for (var index = 0; index < this.subMeshes.length; index++) {
  31702. this.subMeshes[index].refreshBoundingInfo();
  31703. }
  31704. }
  31705. this._updateBoundingInfo();
  31706. return this;
  31707. };
  31708. Mesh.prototype._getPositionData = function (applySkeleton) {
  31709. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31710. if (data && applySkeleton && this.skeleton) {
  31711. data = BABYLON.Tools.Slice(data);
  31712. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31713. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31714. if (matricesWeightsData && matricesIndicesData) {
  31715. var needExtras = this.numBoneInfluencers > 4;
  31716. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31717. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31718. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31719. var tempVector = BABYLON.Tmp.Vector3[0];
  31720. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31721. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31722. var matWeightIdx = 0;
  31723. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31724. finalMatrix.reset();
  31725. var inf;
  31726. var weight;
  31727. for (inf = 0; inf < 4; inf++) {
  31728. weight = matricesWeightsData[matWeightIdx + inf];
  31729. if (weight > 0) {
  31730. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31731. finalMatrix.addToSelf(tempMatrix);
  31732. }
  31733. }
  31734. if (needExtras) {
  31735. for (inf = 0; inf < 4; inf++) {
  31736. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31737. if (weight > 0) {
  31738. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31739. finalMatrix.addToSelf(tempMatrix);
  31740. }
  31741. }
  31742. }
  31743. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31744. tempVector.toArray(data, index);
  31745. }
  31746. }
  31747. }
  31748. return data;
  31749. };
  31750. /** @hidden */
  31751. Mesh.prototype._createGlobalSubMesh = function (force) {
  31752. var totalVertices = this.getTotalVertices();
  31753. if (!totalVertices || !this.getIndices()) {
  31754. return null;
  31755. }
  31756. // Check if we need to recreate the submeshes
  31757. if (this.subMeshes && this.subMeshes.length > 0) {
  31758. var ib = this.getIndices();
  31759. if (!ib) {
  31760. return null;
  31761. }
  31762. var totalIndices = ib.length;
  31763. var needToRecreate = false;
  31764. if (force) {
  31765. needToRecreate = true;
  31766. }
  31767. else {
  31768. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31769. var submesh = _a[_i];
  31770. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31771. needToRecreate = true;
  31772. break;
  31773. }
  31774. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31775. needToRecreate = true;
  31776. break;
  31777. }
  31778. }
  31779. }
  31780. if (!needToRecreate) {
  31781. return this.subMeshes[0];
  31782. }
  31783. }
  31784. this.releaseSubMeshes();
  31785. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31786. };
  31787. /**
  31788. * This function will subdivide the mesh into multiple submeshes
  31789. * @param count defines the expected number of submeshes
  31790. */
  31791. Mesh.prototype.subdivide = function (count) {
  31792. if (count < 1) {
  31793. return;
  31794. }
  31795. var totalIndices = this.getTotalIndices();
  31796. var subdivisionSize = (totalIndices / count) | 0;
  31797. var offset = 0;
  31798. // Ensure that subdivisionSize is a multiple of 3
  31799. while (subdivisionSize % 3 !== 0) {
  31800. subdivisionSize++;
  31801. }
  31802. this.releaseSubMeshes();
  31803. for (var index = 0; index < count; index++) {
  31804. if (offset >= totalIndices) {
  31805. break;
  31806. }
  31807. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31808. offset += subdivisionSize;
  31809. }
  31810. this.synchronizeInstances();
  31811. };
  31812. /**
  31813. * Copy a FloatArray into a specific associated vertex buffer
  31814. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31815. * - BABYLON.VertexBuffer.PositionKind
  31816. * - BABYLON.VertexBuffer.UVKind
  31817. * - BABYLON.VertexBuffer.UV2Kind
  31818. * - BABYLON.VertexBuffer.UV3Kind
  31819. * - BABYLON.VertexBuffer.UV4Kind
  31820. * - BABYLON.VertexBuffer.UV5Kind
  31821. * - BABYLON.VertexBuffer.UV6Kind
  31822. * - BABYLON.VertexBuffer.ColorKind
  31823. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31824. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31825. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31826. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31827. * @param data defines the data source
  31828. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31829. * @param stride defines the data stride size (can be null)
  31830. * @returns the current mesh
  31831. */
  31832. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31833. if (updatable === void 0) { updatable = false; }
  31834. if (!this._geometry) {
  31835. var vertexData = new BABYLON.VertexData();
  31836. vertexData.set(data, kind);
  31837. var scene = this.getScene();
  31838. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31839. }
  31840. else {
  31841. this._geometry.setVerticesData(kind, data, updatable, stride);
  31842. }
  31843. return this;
  31844. };
  31845. /**
  31846. * Flags an associated vertex buffer as updatable
  31847. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31848. * - BABYLON.VertexBuffer.PositionKind
  31849. * - BABYLON.VertexBuffer.UVKind
  31850. * - BABYLON.VertexBuffer.UV2Kind
  31851. * - BABYLON.VertexBuffer.UV3Kind
  31852. * - BABYLON.VertexBuffer.UV4Kind
  31853. * - BABYLON.VertexBuffer.UV5Kind
  31854. * - BABYLON.VertexBuffer.UV6Kind
  31855. * - BABYLON.VertexBuffer.ColorKind
  31856. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31857. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31858. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31859. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31860. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31861. */
  31862. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31863. if (updatable === void 0) { updatable = true; }
  31864. var vb = this.getVertexBuffer(kind);
  31865. if (!vb || vb.isUpdatable() === updatable) {
  31866. return;
  31867. }
  31868. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31869. };
  31870. /**
  31871. * Sets the mesh global Vertex Buffer
  31872. * @param buffer defines the buffer to use
  31873. * @returns the current mesh
  31874. */
  31875. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31876. if (!this._geometry) {
  31877. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31878. }
  31879. this._geometry.setVerticesBuffer(buffer);
  31880. return this;
  31881. };
  31882. /**
  31883. * Update a specific associated vertex buffer
  31884. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31885. * - BABYLON.VertexBuffer.PositionKind
  31886. * - BABYLON.VertexBuffer.UVKind
  31887. * - BABYLON.VertexBuffer.UV2Kind
  31888. * - BABYLON.VertexBuffer.UV3Kind
  31889. * - BABYLON.VertexBuffer.UV4Kind
  31890. * - BABYLON.VertexBuffer.UV5Kind
  31891. * - BABYLON.VertexBuffer.UV6Kind
  31892. * - BABYLON.VertexBuffer.ColorKind
  31893. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31894. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31895. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31896. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31897. * @param data defines the data source
  31898. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31899. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  31900. * @returns the current mesh
  31901. */
  31902. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31903. if (!this._geometry) {
  31904. return this;
  31905. }
  31906. if (!makeItUnique) {
  31907. this._geometry.updateVerticesData(kind, data, updateExtends);
  31908. }
  31909. else {
  31910. this.makeGeometryUnique();
  31911. this.updateVerticesData(kind, data, updateExtends, false);
  31912. }
  31913. return this;
  31914. };
  31915. /**
  31916. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31917. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31918. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31919. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31920. * @returns the current mesh
  31921. */
  31922. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31923. if (computeNormals === void 0) { computeNormals = true; }
  31924. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31925. if (!positions) {
  31926. return this;
  31927. }
  31928. positionFunction(positions);
  31929. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31930. if (computeNormals) {
  31931. var indices = this.getIndices();
  31932. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31933. if (!normals) {
  31934. return this;
  31935. }
  31936. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31937. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31938. }
  31939. return this;
  31940. };
  31941. /**
  31942. * Creates a un-shared specific occurence of the geometry for the mesh.
  31943. * @returns the current mesh
  31944. */
  31945. Mesh.prototype.makeGeometryUnique = function () {
  31946. if (!this._geometry) {
  31947. return this;
  31948. }
  31949. var oldGeometry = this._geometry;
  31950. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31951. oldGeometry.releaseForMesh(this, true);
  31952. geometry.applyToMesh(this);
  31953. return this;
  31954. };
  31955. /**
  31956. * Set the index buffer of this mesh
  31957. * @param indices defines the source data
  31958. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31959. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31960. * @returns the current mesh
  31961. */
  31962. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31963. if (totalVertices === void 0) { totalVertices = null; }
  31964. if (updatable === void 0) { updatable = false; }
  31965. if (!this._geometry) {
  31966. var vertexData = new BABYLON.VertexData();
  31967. vertexData.indices = indices;
  31968. var scene = this.getScene();
  31969. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31970. }
  31971. else {
  31972. this._geometry.setIndices(indices, totalVertices, updatable);
  31973. }
  31974. return this;
  31975. };
  31976. /**
  31977. * Update the current index buffer
  31978. * @param indices defines the source data
  31979. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31980. * @returns the current mesh
  31981. */
  31982. Mesh.prototype.updateIndices = function (indices, offset) {
  31983. if (!this._geometry) {
  31984. return this;
  31985. }
  31986. this._geometry.updateIndices(indices, offset);
  31987. return this;
  31988. };
  31989. /**
  31990. * Invert the geometry to move from a right handed system to a left handed one.
  31991. * @returns the current mesh
  31992. */
  31993. Mesh.prototype.toLeftHanded = function () {
  31994. if (!this._geometry) {
  31995. return this;
  31996. }
  31997. this._geometry.toLeftHanded();
  31998. return this;
  31999. };
  32000. /** @hidden */
  32001. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32002. if (!this._geometry) {
  32003. return this;
  32004. }
  32005. var engine = this.getScene().getEngine();
  32006. // Wireframe
  32007. var indexToBind;
  32008. if (this._unIndexed) {
  32009. indexToBind = null;
  32010. }
  32011. else {
  32012. switch (fillMode) {
  32013. case BABYLON.Material.PointFillMode:
  32014. indexToBind = null;
  32015. break;
  32016. case BABYLON.Material.WireFrameFillMode:
  32017. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32018. break;
  32019. default:
  32020. case BABYLON.Material.TriangleFillMode:
  32021. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32022. break;
  32023. }
  32024. }
  32025. // VBOs
  32026. this._geometry._bind(effect, indexToBind);
  32027. return this;
  32028. };
  32029. /** @hidden */
  32030. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32031. if (alternate === void 0) { alternate = false; }
  32032. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32033. return this;
  32034. }
  32035. if (this._onBeforeDrawObservable) {
  32036. this._onBeforeDrawObservable.notifyObservers(this);
  32037. }
  32038. var scene = this.getScene();
  32039. var engine = scene.getEngine();
  32040. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32041. // or triangles as points
  32042. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32043. }
  32044. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32045. // Triangles as wireframe
  32046. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32047. }
  32048. else {
  32049. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32050. }
  32051. if (scene._isAlternateRenderingEnabled && !alternate) {
  32052. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32053. if (!effect || !scene.activeCamera) {
  32054. return this;
  32055. }
  32056. scene._switchToAlternateCameraConfiguration(true);
  32057. this._effectiveMaterial.bindView(effect);
  32058. this._effectiveMaterial.bindViewProjection(effect);
  32059. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32060. this._draw(subMesh, fillMode, instancesCount, true);
  32061. engine.setViewport(scene.activeCamera.viewport);
  32062. scene._switchToAlternateCameraConfiguration(false);
  32063. this._effectiveMaterial.bindView(effect);
  32064. this._effectiveMaterial.bindViewProjection(effect);
  32065. }
  32066. return this;
  32067. };
  32068. /**
  32069. * Registers for this mesh a javascript function called just before the rendering process
  32070. * @param func defines the function to call before rendering this mesh
  32071. * @returns the current mesh
  32072. */
  32073. Mesh.prototype.registerBeforeRender = function (func) {
  32074. this.onBeforeRenderObservable.add(func);
  32075. return this;
  32076. };
  32077. /**
  32078. * Disposes a previously registered javascript function called before the rendering
  32079. * @param func defines the function to remove
  32080. * @returns the current mesh
  32081. */
  32082. Mesh.prototype.unregisterBeforeRender = function (func) {
  32083. this.onBeforeRenderObservable.removeCallback(func);
  32084. return this;
  32085. };
  32086. /**
  32087. * Registers for this mesh a javascript function called just after the rendering is complete
  32088. * @param func defines the function to call after rendering this mesh
  32089. * @returns the current mesh
  32090. */
  32091. Mesh.prototype.registerAfterRender = function (func) {
  32092. this.onAfterRenderObservable.add(func);
  32093. return this;
  32094. };
  32095. /**
  32096. * Disposes a previously registered javascript function called after the rendering.
  32097. * @param func defines the function to remove
  32098. * @returns the current mesh
  32099. */
  32100. Mesh.prototype.unregisterAfterRender = function (func) {
  32101. this.onAfterRenderObservable.removeCallback(func);
  32102. return this;
  32103. };
  32104. /** @hidden */
  32105. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32106. var scene = this.getScene();
  32107. this._batchCache.mustReturn = false;
  32108. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32109. this._batchCache.visibleInstances[subMeshId] = null;
  32110. if (this._visibleInstances) {
  32111. var currentRenderId = scene.getRenderId();
  32112. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32113. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32114. var selfRenderId = this._renderId;
  32115. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32116. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32117. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32118. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32119. }
  32120. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32121. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32122. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32123. this._batchCache.mustReturn = true;
  32124. return this._batchCache;
  32125. }
  32126. if (currentRenderId !== selfRenderId) {
  32127. this._batchCache.renderSelf[subMeshId] = false;
  32128. }
  32129. }
  32130. this._renderIdForInstances[subMeshId] = currentRenderId;
  32131. }
  32132. return this._batchCache;
  32133. };
  32134. /** @hidden */
  32135. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32136. var visibleInstances = batch.visibleInstances[subMesh._id];
  32137. if (!visibleInstances) {
  32138. return this;
  32139. }
  32140. var matricesCount = visibleInstances.length + 1;
  32141. var bufferSize = matricesCount * 16 * 4;
  32142. var currentInstancesBufferSize = this._instancesBufferSize;
  32143. var instancesBuffer = this._instancesBuffer;
  32144. while (this._instancesBufferSize < bufferSize) {
  32145. this._instancesBufferSize *= 2;
  32146. }
  32147. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32148. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32149. }
  32150. var offset = 0;
  32151. var instancesCount = 0;
  32152. var world = this.getWorldMatrix();
  32153. if (batch.renderSelf[subMesh._id]) {
  32154. world.copyToArray(this._instancesData, offset);
  32155. offset += 16;
  32156. instancesCount++;
  32157. }
  32158. if (visibleInstances) {
  32159. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32160. var instance = visibleInstances[instanceIndex];
  32161. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32162. offset += 16;
  32163. instancesCount++;
  32164. }
  32165. }
  32166. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32167. if (instancesBuffer) {
  32168. instancesBuffer.dispose();
  32169. }
  32170. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32171. this._instancesBuffer = instancesBuffer;
  32172. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32173. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32174. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32175. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32176. }
  32177. else {
  32178. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32179. }
  32180. this._bind(subMesh, effect, fillMode);
  32181. this._draw(subMesh, fillMode, instancesCount);
  32182. engine.unbindInstanceAttributes();
  32183. return this;
  32184. };
  32185. /** @hidden */
  32186. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32187. var scene = this.getScene();
  32188. var engine = scene.getEngine();
  32189. if (hardwareInstancedRendering) {
  32190. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32191. }
  32192. else {
  32193. if (batch.renderSelf[subMesh._id]) {
  32194. // Draw
  32195. if (onBeforeDraw) {
  32196. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32197. }
  32198. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32199. }
  32200. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32201. if (visibleInstancesForSubMesh) {
  32202. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32203. var instance = visibleInstancesForSubMesh[instanceIndex];
  32204. // World
  32205. var world = instance.getWorldMatrix();
  32206. if (onBeforeDraw) {
  32207. onBeforeDraw(true, world, effectiveMaterial);
  32208. }
  32209. // Draw
  32210. this._draw(subMesh, fillMode);
  32211. }
  32212. }
  32213. }
  32214. return this;
  32215. };
  32216. /**
  32217. * 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
  32218. * @param subMesh defines the subMesh to render
  32219. * @param enableAlphaMode defines if alpha mode can be changed
  32220. * @returns the current mesh
  32221. */
  32222. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32223. this._checkOcclusionQuery();
  32224. if (this._isOccluded) {
  32225. return this;
  32226. }
  32227. var scene = this.getScene();
  32228. // Managing instances
  32229. var batch = this._getInstancesRenderList(subMesh._id);
  32230. if (batch.mustReturn) {
  32231. return this;
  32232. }
  32233. // Checking geometry state
  32234. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32235. return this;
  32236. }
  32237. if (this._onBeforeRenderObservable) {
  32238. this._onBeforeRenderObservable.notifyObservers(this);
  32239. }
  32240. var engine = scene.getEngine();
  32241. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32242. // Material
  32243. var material = subMesh.getMaterial();
  32244. if (!material) {
  32245. return this;
  32246. }
  32247. this._effectiveMaterial = material;
  32248. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32249. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32250. return this;
  32251. }
  32252. }
  32253. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32254. return this;
  32255. }
  32256. // Alpha mode
  32257. if (enableAlphaMode) {
  32258. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32259. }
  32260. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32261. var step = _a[_i];
  32262. step.action(this, subMesh, batch);
  32263. }
  32264. var effect;
  32265. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32266. effect = subMesh.effect;
  32267. }
  32268. else {
  32269. effect = this._effectiveMaterial.getEffect();
  32270. }
  32271. if (!effect) {
  32272. return this;
  32273. }
  32274. var sideOrientation = this.overrideMaterialSideOrientation;
  32275. if (sideOrientation == null) {
  32276. sideOrientation = this._effectiveMaterial.sideOrientation;
  32277. if (this._getWorldMatrixDeterminant() < 0) {
  32278. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32279. }
  32280. }
  32281. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32282. if (this._effectiveMaterial.forceDepthWrite) {
  32283. engine.setDepthWrite(true);
  32284. }
  32285. // Bind
  32286. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32287. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32288. this._bind(subMesh, effect, fillMode);
  32289. }
  32290. var world = this.getWorldMatrix();
  32291. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32292. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32293. }
  32294. else {
  32295. this._effectiveMaterial.bind(world, this);
  32296. }
  32297. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32298. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32299. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32300. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32301. }
  32302. // Draw
  32303. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32304. // Unbind
  32305. this._effectiveMaterial.unbind();
  32306. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32307. var step = _c[_b];
  32308. step.action(this, subMesh, batch);
  32309. }
  32310. if (this._onAfterRenderObservable) {
  32311. this._onAfterRenderObservable.notifyObservers(this);
  32312. }
  32313. return this;
  32314. };
  32315. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32316. if (isInstance && effectiveMaterial) {
  32317. effectiveMaterial.bindOnlyWorldMatrix(world);
  32318. }
  32319. };
  32320. /**
  32321. * Normalize matrix weights so that all vertices have a total weight set to 1
  32322. */
  32323. Mesh.prototype.cleanMatrixWeights = function () {
  32324. var epsilon = 1e-3;
  32325. var noInfluenceBoneIndex = 0.0;
  32326. if (this.skeleton) {
  32327. noInfluenceBoneIndex = this.skeleton.bones.length;
  32328. }
  32329. else {
  32330. return;
  32331. }
  32332. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32333. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32334. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32335. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32336. var influencers = this.numBoneInfluencers;
  32337. var size = matricesWeights.length;
  32338. for (var i = 0; i < size; i += 4) {
  32339. var weight = 0.0;
  32340. var firstZeroWeight = -1;
  32341. for (var j = 0; j < 4; j++) {
  32342. var w = matricesWeights[i + j];
  32343. weight += w;
  32344. if (w < epsilon && firstZeroWeight < 0) {
  32345. firstZeroWeight = j;
  32346. }
  32347. }
  32348. if (matricesWeightsExtra) {
  32349. for (var j = 0; j < 4; j++) {
  32350. var w = matricesWeightsExtra[i + j];
  32351. weight += w;
  32352. if (w < epsilon && firstZeroWeight < 0) {
  32353. firstZeroWeight = j + 4;
  32354. }
  32355. }
  32356. }
  32357. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32358. firstZeroWeight = influencers - 1;
  32359. }
  32360. if (weight > epsilon) {
  32361. var mweight = 1.0 / weight;
  32362. for (var j = 0; j < 4; j++) {
  32363. matricesWeights[i + j] *= mweight;
  32364. }
  32365. if (matricesWeightsExtra) {
  32366. for (var j = 0; j < 4; j++) {
  32367. matricesWeightsExtra[i + j] *= mweight;
  32368. }
  32369. }
  32370. }
  32371. else {
  32372. if (firstZeroWeight >= 4) {
  32373. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32374. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32375. }
  32376. else {
  32377. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32378. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32379. }
  32380. }
  32381. }
  32382. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32383. if (matricesIndicesExtra) {
  32384. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32385. }
  32386. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32387. if (matricesWeightsExtra) {
  32388. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32389. }
  32390. };
  32391. /** @hidden */
  32392. Mesh.prototype._checkDelayState = function () {
  32393. var scene = this.getScene();
  32394. if (this._geometry) {
  32395. this._geometry.load(scene);
  32396. }
  32397. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32398. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32399. this._queueLoad(scene);
  32400. }
  32401. return this;
  32402. };
  32403. Mesh.prototype._queueLoad = function (scene) {
  32404. var _this = this;
  32405. scene._addPendingData(this);
  32406. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32407. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32408. if (data instanceof ArrayBuffer) {
  32409. _this._delayLoadingFunction(data, _this);
  32410. }
  32411. else {
  32412. _this._delayLoadingFunction(JSON.parse(data), _this);
  32413. }
  32414. _this.instances.forEach(function (instance) {
  32415. instance._syncSubMeshes();
  32416. });
  32417. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32418. scene._removePendingData(_this);
  32419. }, function () { }, scene.database, getBinaryData);
  32420. return this;
  32421. };
  32422. /**
  32423. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32424. * A mesh is in the frustum if its bounding box intersects the frustum
  32425. * @param frustumPlanes defines the frustum to test
  32426. * @returns true if the mesh is in the frustum planes
  32427. */
  32428. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32429. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32430. return false;
  32431. }
  32432. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32433. return false;
  32434. }
  32435. this._checkDelayState();
  32436. return true;
  32437. };
  32438. /**
  32439. * Sets the mesh material by the material or multiMaterial `id` property
  32440. * @param id is a string identifying the material or the multiMaterial
  32441. * @returns the current mesh
  32442. */
  32443. Mesh.prototype.setMaterialByID = function (id) {
  32444. var materials = this.getScene().materials;
  32445. var index;
  32446. for (index = materials.length - 1; index > -1; index--) {
  32447. if (materials[index].id === id) {
  32448. this.material = materials[index];
  32449. return this;
  32450. }
  32451. }
  32452. // Multi
  32453. var multiMaterials = this.getScene().multiMaterials;
  32454. for (index = multiMaterials.length - 1; index > -1; index--) {
  32455. if (multiMaterials[index].id === id) {
  32456. this.material = multiMaterials[index];
  32457. return this;
  32458. }
  32459. }
  32460. return this;
  32461. };
  32462. /**
  32463. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32464. * @returns an array of IAnimatable
  32465. */
  32466. Mesh.prototype.getAnimatables = function () {
  32467. var results = new Array();
  32468. if (this.material) {
  32469. results.push(this.material);
  32470. }
  32471. if (this.skeleton) {
  32472. results.push(this.skeleton);
  32473. }
  32474. return results;
  32475. };
  32476. /**
  32477. * Modifies the mesh geometry according to the passed transformation matrix.
  32478. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32479. * The mesh normals are modified using the same transformation.
  32480. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32481. * @param transform defines the transform matrix to use
  32482. * @see http://doc.babylonjs.com/resources/baking_transformations
  32483. * @returns the current mesh
  32484. */
  32485. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32486. // Position
  32487. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32488. return this;
  32489. }
  32490. var submeshes = this.subMeshes.splice(0);
  32491. this._resetPointsArrayCache();
  32492. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32493. var temp = new Array();
  32494. var index;
  32495. for (index = 0; index < data.length; index += 3) {
  32496. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32497. }
  32498. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32499. // Normals
  32500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32501. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32502. temp = [];
  32503. for (index = 0; index < data.length; index += 3) {
  32504. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32505. }
  32506. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32507. }
  32508. // flip faces?
  32509. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32510. this.flipFaces();
  32511. }
  32512. // Restore submeshes
  32513. this.releaseSubMeshes();
  32514. this.subMeshes = submeshes;
  32515. return this;
  32516. };
  32517. /**
  32518. * Modifies the mesh geometry according to its own current World Matrix.
  32519. * The mesh World Matrix is then reset.
  32520. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32521. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32522. * @see http://doc.babylonjs.com/resources/baking_transformations
  32523. * @returns the current mesh
  32524. */
  32525. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32526. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32527. this.scaling.copyFromFloats(1, 1, 1);
  32528. this.position.copyFromFloats(0, 0, 0);
  32529. this.rotation.copyFromFloats(0, 0, 0);
  32530. //only if quaternion is already set
  32531. if (this.rotationQuaternion) {
  32532. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32533. }
  32534. this._worldMatrix = BABYLON.Matrix.Identity();
  32535. return this;
  32536. };
  32537. Object.defineProperty(Mesh.prototype, "_positions", {
  32538. // Cache
  32539. /** @hidden */
  32540. get: function () {
  32541. if (this._geometry) {
  32542. return this._geometry._positions;
  32543. }
  32544. return null;
  32545. },
  32546. enumerable: true,
  32547. configurable: true
  32548. });
  32549. /** @hidden */
  32550. Mesh.prototype._resetPointsArrayCache = function () {
  32551. if (this._geometry) {
  32552. this._geometry._resetPointsArrayCache();
  32553. }
  32554. return this;
  32555. };
  32556. /** @hidden */
  32557. Mesh.prototype._generatePointsArray = function () {
  32558. if (this._geometry) {
  32559. return this._geometry._generatePointsArray();
  32560. }
  32561. return false;
  32562. };
  32563. /**
  32564. * Returns a new Mesh object generated from the current mesh properties.
  32565. * This method must not get confused with createInstance()
  32566. * @param name is a string, the name given to the new mesh
  32567. * @param newParent can be any Node object (default `null`)
  32568. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32569. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32570. * @returns a new mesh
  32571. */
  32572. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32573. if (name === void 0) { name = ""; }
  32574. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32575. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32576. };
  32577. /**
  32578. * Releases resources associated with this mesh.
  32579. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32580. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32581. */
  32582. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32583. var _this = this;
  32584. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32585. this.morphTargetManager = null;
  32586. if (this._geometry) {
  32587. this._geometry.releaseForMesh(this, true);
  32588. }
  32589. if (this._onBeforeDrawObservable) {
  32590. this._onBeforeDrawObservable.clear();
  32591. }
  32592. if (this._onBeforeRenderObservable) {
  32593. this._onBeforeRenderObservable.clear();
  32594. }
  32595. if (this._onAfterRenderObservable) {
  32596. this._onAfterRenderObservable.clear();
  32597. }
  32598. // Sources
  32599. var meshes = this.getScene().meshes;
  32600. meshes.forEach(function (abstractMesh) {
  32601. var mesh = abstractMesh;
  32602. if (mesh._source && mesh._source === _this) {
  32603. mesh._source = null;
  32604. }
  32605. });
  32606. this._source = null;
  32607. // Instances
  32608. if (this._instancesBuffer) {
  32609. this._instancesBuffer.dispose();
  32610. this._instancesBuffer = null;
  32611. }
  32612. while (this.instances.length) {
  32613. this.instances[0].dispose();
  32614. }
  32615. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32616. };
  32617. /**
  32618. * Modifies the mesh geometry according to a displacement map.
  32619. * 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.
  32620. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32621. * @param url is a string, the URL from the image file is to be downloaded.
  32622. * @param minHeight is the lower limit of the displacement.
  32623. * @param maxHeight is the upper limit of the displacement.
  32624. * @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.
  32625. * @param uvOffset is an optional vector2 used to offset UV.
  32626. * @param uvScale is an optional vector2 used to scale UV.
  32627. * @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.
  32628. * @returns the Mesh.
  32629. */
  32630. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32631. var _this = this;
  32632. if (forceUpdate === void 0) { forceUpdate = false; }
  32633. var scene = this.getScene();
  32634. var onload = function (img) {
  32635. // Getting height map data
  32636. var canvas = document.createElement("canvas");
  32637. var context = canvas.getContext("2d");
  32638. var heightMapWidth = img.width;
  32639. var heightMapHeight = img.height;
  32640. canvas.width = heightMapWidth;
  32641. canvas.height = heightMapHeight;
  32642. context.drawImage(img, 0, 0);
  32643. // Create VertexData from map data
  32644. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32645. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32646. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32647. //execute success callback, if set
  32648. if (onSuccess) {
  32649. onSuccess(_this);
  32650. }
  32651. };
  32652. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32653. return this;
  32654. };
  32655. /**
  32656. * Modifies the mesh geometry according to a displacementMap buffer.
  32657. * 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.
  32658. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32659. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32660. * @param heightMapWidth is the width of the buffer image.
  32661. * @param heightMapHeight is the height of the buffer image.
  32662. * @param minHeight is the lower limit of the displacement.
  32663. * @param maxHeight is the upper limit of the displacement.
  32664. * @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.
  32665. * @param uvOffset is an optional vector2 used to offset UV.
  32666. * @param uvScale is an optional vector2 used to scale UV.
  32667. * @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.
  32668. * @returns the Mesh.
  32669. */
  32670. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32671. if (forceUpdate === void 0) { forceUpdate = false; }
  32672. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32673. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32674. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32675. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32676. return this;
  32677. }
  32678. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32679. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32680. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32681. var position = BABYLON.Vector3.Zero();
  32682. var normal = BABYLON.Vector3.Zero();
  32683. var uv = BABYLON.Vector2.Zero();
  32684. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32685. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32686. for (var index = 0; index < positions.length; index += 3) {
  32687. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32688. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32689. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32690. // Compute height
  32691. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32692. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32693. var pos = (u + v * heightMapWidth) * 4;
  32694. var r = buffer[pos] / 255.0;
  32695. var g = buffer[pos + 1] / 255.0;
  32696. var b = buffer[pos + 2] / 255.0;
  32697. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32698. normal.normalize();
  32699. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32700. position = position.add(normal);
  32701. position.toArray(positions, index);
  32702. }
  32703. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32704. if (forceUpdate) {
  32705. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32706. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32707. }
  32708. else {
  32709. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32710. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32711. }
  32712. return this;
  32713. };
  32714. /**
  32715. * Modify the mesh to get a flat shading rendering.
  32716. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32717. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32718. * @returns current mesh
  32719. */
  32720. Mesh.prototype.convertToFlatShadedMesh = function () {
  32721. var kinds = this.getVerticesDataKinds();
  32722. var vbs = {};
  32723. var data = {};
  32724. var newdata = {};
  32725. var updatableNormals = false;
  32726. var kindIndex;
  32727. var kind;
  32728. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32729. kind = kinds[kindIndex];
  32730. var vertexBuffer = this.getVertexBuffer(kind);
  32731. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32732. updatableNormals = vertexBuffer.isUpdatable();
  32733. kinds.splice(kindIndex, 1);
  32734. kindIndex--;
  32735. continue;
  32736. }
  32737. vbs[kind] = vertexBuffer;
  32738. data[kind] = vbs[kind].getData();
  32739. newdata[kind] = [];
  32740. }
  32741. // Save previous submeshes
  32742. var previousSubmeshes = this.subMeshes.slice(0);
  32743. var indices = this.getIndices();
  32744. var totalIndices = this.getTotalIndices();
  32745. // Generating unique vertices per face
  32746. var index;
  32747. for (index = 0; index < totalIndices; index++) {
  32748. var vertexIndex = indices[index];
  32749. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32750. kind = kinds[kindIndex];
  32751. var stride = vbs[kind].getStrideSize();
  32752. for (var offset = 0; offset < stride; offset++) {
  32753. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32754. }
  32755. }
  32756. }
  32757. // Updating faces & normal
  32758. var normals = [];
  32759. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32760. for (index = 0; index < totalIndices; index += 3) {
  32761. indices[index] = index;
  32762. indices[index + 1] = index + 1;
  32763. indices[index + 2] = index + 2;
  32764. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32765. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32766. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32767. var p1p2 = p1.subtract(p2);
  32768. var p3p2 = p3.subtract(p2);
  32769. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32770. // Store same normals for every vertex
  32771. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32772. normals.push(normal.x);
  32773. normals.push(normal.y);
  32774. normals.push(normal.z);
  32775. }
  32776. }
  32777. this.setIndices(indices);
  32778. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32779. // Updating vertex buffers
  32780. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32781. kind = kinds[kindIndex];
  32782. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32783. }
  32784. // Updating submeshes
  32785. this.releaseSubMeshes();
  32786. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32787. var previousOne = previousSubmeshes[submeshIndex];
  32788. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32789. }
  32790. this.synchronizeInstances();
  32791. return this;
  32792. };
  32793. /**
  32794. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32795. * In other words, more vertices, no more indices and a single bigger VBO.
  32796. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32797. * @returns current mesh
  32798. */
  32799. Mesh.prototype.convertToUnIndexedMesh = function () {
  32800. var kinds = this.getVerticesDataKinds();
  32801. var vbs = {};
  32802. var data = {};
  32803. var newdata = {};
  32804. var kindIndex;
  32805. var kind;
  32806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32807. kind = kinds[kindIndex];
  32808. var vertexBuffer = this.getVertexBuffer(kind);
  32809. vbs[kind] = vertexBuffer;
  32810. data[kind] = vbs[kind].getData();
  32811. newdata[kind] = [];
  32812. }
  32813. // Save previous submeshes
  32814. var previousSubmeshes = this.subMeshes.slice(0);
  32815. var indices = this.getIndices();
  32816. var totalIndices = this.getTotalIndices();
  32817. // Generating unique vertices per face
  32818. var index;
  32819. for (index = 0; index < totalIndices; index++) {
  32820. var vertexIndex = indices[index];
  32821. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32822. kind = kinds[kindIndex];
  32823. var stride = vbs[kind].getStrideSize();
  32824. for (var offset = 0; offset < stride; offset++) {
  32825. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32826. }
  32827. }
  32828. }
  32829. // Updating indices
  32830. for (index = 0; index < totalIndices; index += 3) {
  32831. indices[index] = index;
  32832. indices[index + 1] = index + 1;
  32833. indices[index + 2] = index + 2;
  32834. }
  32835. this.setIndices(indices);
  32836. // Updating vertex buffers
  32837. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32838. kind = kinds[kindIndex];
  32839. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32840. }
  32841. // Updating submeshes
  32842. this.releaseSubMeshes();
  32843. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32844. var previousOne = previousSubmeshes[submeshIndex];
  32845. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32846. }
  32847. this._unIndexed = true;
  32848. this.synchronizeInstances();
  32849. return this;
  32850. };
  32851. /**
  32852. * Inverses facet orientations.
  32853. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32854. * @param flipNormals will also inverts the normals
  32855. * @returns current mesh
  32856. */
  32857. Mesh.prototype.flipFaces = function (flipNormals) {
  32858. if (flipNormals === void 0) { flipNormals = false; }
  32859. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32860. var i;
  32861. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32862. for (i = 0; i < vertex_data.normals.length; i++) {
  32863. vertex_data.normals[i] *= -1;
  32864. }
  32865. }
  32866. if (vertex_data.indices) {
  32867. var temp;
  32868. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32869. // reassign indices
  32870. temp = vertex_data.indices[i + 1];
  32871. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32872. vertex_data.indices[i + 2] = temp;
  32873. }
  32874. }
  32875. vertex_data.applyToMesh(this);
  32876. return this;
  32877. };
  32878. // Instances
  32879. /**
  32880. * Creates a new InstancedMesh object from the mesh model.
  32881. * Warning : this method is not supported for Line mesh and LineSystem
  32882. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32883. * @param name defines the name of the new instance
  32884. * @returns a new InstancedMesh
  32885. */
  32886. Mesh.prototype.createInstance = function (name) {
  32887. return new BABYLON.InstancedMesh(name, this);
  32888. };
  32889. /**
  32890. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32891. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32892. * @returns the current mesh
  32893. */
  32894. Mesh.prototype.synchronizeInstances = function () {
  32895. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32896. var instance = this.instances[instanceIndex];
  32897. instance._syncSubMeshes();
  32898. }
  32899. return this;
  32900. };
  32901. /**
  32902. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32903. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32904. * This should be used together with the simplification to avoid disappearing triangles.
  32905. * @param successCallback an optional success callback to be called after the optimization finished.
  32906. * @returns the current mesh
  32907. */
  32908. Mesh.prototype.optimizeIndices = function (successCallback) {
  32909. var _this = this;
  32910. var indices = this.getIndices();
  32911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32912. if (!positions || !indices) {
  32913. return this;
  32914. }
  32915. var vectorPositions = new Array();
  32916. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32917. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32918. }
  32919. var dupes = new Array();
  32920. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32921. var realPos = vectorPositions.length - 1 - iteration;
  32922. var testedPosition = vectorPositions[realPos];
  32923. for (var j = 0; j < realPos; ++j) {
  32924. var againstPosition = vectorPositions[j];
  32925. if (testedPosition.equals(againstPosition)) {
  32926. dupes[realPos] = j;
  32927. break;
  32928. }
  32929. }
  32930. }, function () {
  32931. for (var i = 0; i < indices.length; ++i) {
  32932. indices[i] = dupes[indices[i]] || indices[i];
  32933. }
  32934. //indices are now reordered
  32935. var originalSubMeshes = _this.subMeshes.slice(0);
  32936. _this.setIndices(indices);
  32937. _this.subMeshes = originalSubMeshes;
  32938. if (successCallback) {
  32939. successCallback(_this);
  32940. }
  32941. });
  32942. return this;
  32943. };
  32944. /**
  32945. * Serialize current mesh
  32946. * @param serializationObject defines the object which will receive the serialization data
  32947. */
  32948. Mesh.prototype.serialize = function (serializationObject) {
  32949. serializationObject.name = this.name;
  32950. serializationObject.id = this.id;
  32951. serializationObject.type = this.getClassName();
  32952. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32953. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32954. }
  32955. serializationObject.position = this.position.asArray();
  32956. if (this.rotationQuaternion) {
  32957. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32958. }
  32959. else if (this.rotation) {
  32960. serializationObject.rotation = this.rotation.asArray();
  32961. }
  32962. serializationObject.scaling = this.scaling.asArray();
  32963. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32964. serializationObject.isEnabled = this.isEnabled(false);
  32965. serializationObject.isVisible = this.isVisible;
  32966. serializationObject.infiniteDistance = this.infiniteDistance;
  32967. serializationObject.pickable = this.isPickable;
  32968. serializationObject.receiveShadows = this.receiveShadows;
  32969. serializationObject.billboardMode = this.billboardMode;
  32970. serializationObject.visibility = this.visibility;
  32971. serializationObject.checkCollisions = this.checkCollisions;
  32972. serializationObject.isBlocker = this.isBlocker;
  32973. // Parent
  32974. if (this.parent) {
  32975. serializationObject.parentId = this.parent.id;
  32976. }
  32977. // Geometry
  32978. serializationObject.isUnIndexed = this.isUnIndexed;
  32979. var geometry = this._geometry;
  32980. if (geometry) {
  32981. var geometryId = geometry.id;
  32982. serializationObject.geometryId = geometryId;
  32983. // SubMeshes
  32984. serializationObject.subMeshes = [];
  32985. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32986. var subMesh = this.subMeshes[subIndex];
  32987. serializationObject.subMeshes.push({
  32988. materialIndex: subMesh.materialIndex,
  32989. verticesStart: subMesh.verticesStart,
  32990. verticesCount: subMesh.verticesCount,
  32991. indexStart: subMesh.indexStart,
  32992. indexCount: subMesh.indexCount
  32993. });
  32994. }
  32995. }
  32996. // Material
  32997. if (this.material) {
  32998. serializationObject.materialId = this.material.id;
  32999. }
  33000. else {
  33001. this.material = null;
  33002. }
  33003. // Morph targets
  33004. if (this.morphTargetManager) {
  33005. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33006. }
  33007. // Skeleton
  33008. if (this.skeleton) {
  33009. serializationObject.skeletonId = this.skeleton.id;
  33010. }
  33011. // Physics
  33012. //TODO implement correct serialization for physics impostors.
  33013. var impostor = this.getPhysicsImpostor();
  33014. if (impostor) {
  33015. serializationObject.physicsMass = impostor.getParam("mass");
  33016. serializationObject.physicsFriction = impostor.getParam("friction");
  33017. serializationObject.physicsRestitution = impostor.getParam("mass");
  33018. serializationObject.physicsImpostor = impostor.type;
  33019. }
  33020. // Metadata
  33021. if (this.metadata) {
  33022. serializationObject.metadata = this.metadata;
  33023. }
  33024. // Instances
  33025. serializationObject.instances = [];
  33026. for (var index = 0; index < this.instances.length; index++) {
  33027. var instance = this.instances[index];
  33028. if (instance.doNotSerialize) {
  33029. continue;
  33030. }
  33031. var serializationInstance = {
  33032. name: instance.name,
  33033. id: instance.id,
  33034. position: instance.position.asArray(),
  33035. scaling: instance.scaling.asArray()
  33036. };
  33037. if (instance.parent) {
  33038. serializationInstance.parentId = instance.parent.id;
  33039. }
  33040. if (instance.rotationQuaternion) {
  33041. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33042. }
  33043. else if (instance.rotation) {
  33044. serializationInstance.rotation = instance.rotation.asArray();
  33045. }
  33046. serializationObject.instances.push(serializationInstance);
  33047. // Animations
  33048. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33049. serializationInstance.ranges = instance.serializeAnimationRanges();
  33050. }
  33051. //
  33052. // Animations
  33053. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33054. serializationObject.ranges = this.serializeAnimationRanges();
  33055. // Layer mask
  33056. serializationObject.layerMask = this.layerMask;
  33057. // Alpha
  33058. serializationObject.alphaIndex = this.alphaIndex;
  33059. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33060. // Overlay
  33061. serializationObject.overlayAlpha = this.overlayAlpha;
  33062. serializationObject.overlayColor = this.overlayColor.asArray();
  33063. serializationObject.renderOverlay = this.renderOverlay;
  33064. // Fog
  33065. serializationObject.applyFog = this.applyFog;
  33066. // Action Manager
  33067. if (this.actionManager) {
  33068. serializationObject.actions = this.actionManager.serialize(this.name);
  33069. }
  33070. };
  33071. /** @hidden */
  33072. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33073. if (!this.geometry) {
  33074. return;
  33075. }
  33076. this._markSubMeshesAsAttributesDirty();
  33077. var morphTargetManager = this._morphTargetManager;
  33078. if (morphTargetManager && morphTargetManager.vertexCount) {
  33079. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33080. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33081. this.morphTargetManager = null;
  33082. return;
  33083. }
  33084. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33085. var morphTarget = morphTargetManager.getActiveTarget(index);
  33086. var positions = morphTarget.getPositions();
  33087. if (!positions) {
  33088. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33089. return;
  33090. }
  33091. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33092. var normals = morphTarget.getNormals();
  33093. if (normals) {
  33094. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33095. }
  33096. var tangents = morphTarget.getTangents();
  33097. if (tangents) {
  33098. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33099. }
  33100. }
  33101. }
  33102. else {
  33103. var index = 0;
  33104. // Positions
  33105. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33106. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33107. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33108. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33109. }
  33110. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33111. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33112. }
  33113. index++;
  33114. }
  33115. }
  33116. };
  33117. // Statics
  33118. /**
  33119. * Returns a new Mesh object parsed from the source provided.
  33120. * @param parsedMesh is the source
  33121. * @param scene defines the hosting scene
  33122. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33123. * @returns a new Mesh
  33124. */
  33125. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33126. var mesh;
  33127. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33128. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33129. }
  33130. else {
  33131. mesh = new Mesh(parsedMesh.name, scene);
  33132. }
  33133. mesh.id = parsedMesh.id;
  33134. if (BABYLON.Tags) {
  33135. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33136. }
  33137. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33138. if (parsedMesh.metadata !== undefined) {
  33139. mesh.metadata = parsedMesh.metadata;
  33140. }
  33141. if (parsedMesh.rotationQuaternion) {
  33142. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33143. }
  33144. else if (parsedMesh.rotation) {
  33145. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33146. }
  33147. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33148. if (parsedMesh.localMatrix) {
  33149. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33150. }
  33151. else if (parsedMesh.pivotMatrix) {
  33152. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33153. }
  33154. mesh.setEnabled(parsedMesh.isEnabled);
  33155. mesh.isVisible = parsedMesh.isVisible;
  33156. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33157. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33158. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33159. if (parsedMesh.applyFog !== undefined) {
  33160. mesh.applyFog = parsedMesh.applyFog;
  33161. }
  33162. if (parsedMesh.pickable !== undefined) {
  33163. mesh.isPickable = parsedMesh.pickable;
  33164. }
  33165. if (parsedMesh.alphaIndex !== undefined) {
  33166. mesh.alphaIndex = parsedMesh.alphaIndex;
  33167. }
  33168. mesh.receiveShadows = parsedMesh.receiveShadows;
  33169. mesh.billboardMode = parsedMesh.billboardMode;
  33170. if (parsedMesh.visibility !== undefined) {
  33171. mesh.visibility = parsedMesh.visibility;
  33172. }
  33173. mesh.checkCollisions = parsedMesh.checkCollisions;
  33174. if (parsedMesh.isBlocker !== undefined) {
  33175. mesh.isBlocker = parsedMesh.isBlocker;
  33176. }
  33177. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33178. // freezeWorldMatrix
  33179. if (parsedMesh.freezeWorldMatrix) {
  33180. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33181. }
  33182. // Parent
  33183. if (parsedMesh.parentId) {
  33184. mesh._waitingParentId = parsedMesh.parentId;
  33185. }
  33186. // Actions
  33187. if (parsedMesh.actions !== undefined) {
  33188. mesh._waitingActions = parsedMesh.actions;
  33189. }
  33190. // Overlay
  33191. if (parsedMesh.overlayAlpha !== undefined) {
  33192. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33193. }
  33194. if (parsedMesh.overlayColor !== undefined) {
  33195. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33196. }
  33197. if (parsedMesh.renderOverlay !== undefined) {
  33198. mesh.renderOverlay = parsedMesh.renderOverlay;
  33199. }
  33200. // Geometry
  33201. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33202. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33203. if (parsedMesh.delayLoadingFile) {
  33204. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33205. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33206. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33207. if (parsedMesh._binaryInfo) {
  33208. mesh._binaryInfo = parsedMesh._binaryInfo;
  33209. }
  33210. mesh._delayInfo = [];
  33211. if (parsedMesh.hasUVs) {
  33212. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33213. }
  33214. if (parsedMesh.hasUVs2) {
  33215. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33216. }
  33217. if (parsedMesh.hasUVs3) {
  33218. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33219. }
  33220. if (parsedMesh.hasUVs4) {
  33221. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33222. }
  33223. if (parsedMesh.hasUVs5) {
  33224. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33225. }
  33226. if (parsedMesh.hasUVs6) {
  33227. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33228. }
  33229. if (parsedMesh.hasColors) {
  33230. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33231. }
  33232. if (parsedMesh.hasMatricesIndices) {
  33233. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33234. }
  33235. if (parsedMesh.hasMatricesWeights) {
  33236. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33237. }
  33238. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33239. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33240. mesh._checkDelayState();
  33241. }
  33242. }
  33243. else {
  33244. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33245. }
  33246. // Material
  33247. if (parsedMesh.materialId) {
  33248. mesh.setMaterialByID(parsedMesh.materialId);
  33249. }
  33250. else {
  33251. mesh.material = null;
  33252. }
  33253. // Morph targets
  33254. if (parsedMesh.morphTargetManagerId > -1) {
  33255. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33256. }
  33257. // Skeleton
  33258. if (parsedMesh.skeletonId > -1) {
  33259. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33260. if (parsedMesh.numBoneInfluencers) {
  33261. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33262. }
  33263. }
  33264. // Animations
  33265. if (parsedMesh.animations) {
  33266. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33267. var parsedAnimation = parsedMesh.animations[animationIndex];
  33268. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33269. }
  33270. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33271. }
  33272. if (parsedMesh.autoAnimate) {
  33273. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33274. }
  33275. // Layer Mask
  33276. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33277. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33278. }
  33279. else {
  33280. mesh.layerMask = 0x0FFFFFFF;
  33281. }
  33282. // Physics
  33283. if (parsedMesh.physicsImpostor) {
  33284. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33285. mass: parsedMesh.physicsMass,
  33286. friction: parsedMesh.physicsFriction,
  33287. restitution: parsedMesh.physicsRestitution
  33288. }, scene);
  33289. }
  33290. // Instances
  33291. if (parsedMesh.instances) {
  33292. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33293. var parsedInstance = parsedMesh.instances[index];
  33294. var instance = mesh.createInstance(parsedInstance.name);
  33295. if (parsedInstance.id) {
  33296. instance.id = parsedInstance.id;
  33297. }
  33298. if (BABYLON.Tags) {
  33299. if (parsedInstance.tags) {
  33300. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33301. }
  33302. else {
  33303. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33304. }
  33305. }
  33306. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33307. if (parsedInstance.parentId) {
  33308. instance._waitingParentId = parsedInstance.parentId;
  33309. }
  33310. if (parsedInstance.rotationQuaternion) {
  33311. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33312. }
  33313. else if (parsedInstance.rotation) {
  33314. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33315. }
  33316. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33317. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33318. instance.checkCollisions = parsedInstance.checkCollisions;
  33319. }
  33320. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33321. instance.isPickable = parsedInstance.pickable;
  33322. }
  33323. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33324. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33325. }
  33326. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33327. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33328. }
  33329. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33330. instance.alphaIndex = parsedInstance.alphaIndex;
  33331. }
  33332. // Physics
  33333. if (parsedInstance.physicsImpostor) {
  33334. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33335. mass: parsedInstance.physicsMass,
  33336. friction: parsedInstance.physicsFriction,
  33337. restitution: parsedInstance.physicsRestitution
  33338. }, scene);
  33339. }
  33340. // Animation
  33341. if (parsedInstance.animations) {
  33342. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33343. parsedAnimation = parsedInstance.animations[animationIndex];
  33344. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33345. }
  33346. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33347. if (parsedInstance.autoAnimate) {
  33348. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33349. }
  33350. }
  33351. }
  33352. }
  33353. return mesh;
  33354. };
  33355. /**
  33356. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33357. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33358. * @param name defines the name of the mesh to create
  33359. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33360. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33361. * @param closePath creates a seam between the first and the last points of each path of the path array
  33362. * @param offset is taken in account only if the `pathArray` is containing a single path
  33363. * @param scene defines the hosting scene
  33364. * @param updatable defines if the mesh must be flagged as updatable
  33365. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33366. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  33367. * @returns a new Mesh
  33368. */
  33369. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33370. if (closeArray === void 0) { closeArray = false; }
  33371. if (updatable === void 0) { updatable = false; }
  33372. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33373. pathArray: pathArray,
  33374. closeArray: closeArray,
  33375. closePath: closePath,
  33376. offset: offset,
  33377. updatable: updatable,
  33378. sideOrientation: sideOrientation,
  33379. instance: instance
  33380. }, scene);
  33381. };
  33382. /**
  33383. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33384. * @param name defines the name of the mesh to create
  33385. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33386. * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
  33387. * @param scene defines the hosting scene
  33388. * @param updatable defines if the mesh must be flagged as updatable
  33389. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33390. * @returns a new Mesh
  33391. */
  33392. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33393. if (scene === void 0) { scene = null; }
  33394. var options = {
  33395. radius: radius,
  33396. tessellation: tessellation,
  33397. sideOrientation: sideOrientation,
  33398. updatable: updatable
  33399. };
  33400. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33401. };
  33402. /**
  33403. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33404. * @param name defines the name of the mesh to create
  33405. * @param size sets the size (float) of each box side (default 1)
  33406. * @param scene defines the hosting scene
  33407. * @param updatable defines if the mesh must be flagged as updatable
  33408. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33409. * @returns a new Mesh
  33410. */
  33411. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33412. if (scene === void 0) { scene = null; }
  33413. var options = {
  33414. size: size,
  33415. sideOrientation: sideOrientation,
  33416. updatable: updatable
  33417. };
  33418. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33419. };
  33420. /**
  33421. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33422. * @param name defines the name of the mesh to create
  33423. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33424. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33425. * @param scene defines the hosting scene
  33426. * @param updatable defines if the mesh must be flagged as updatable
  33427. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33428. * @returns a new Mesh
  33429. */
  33430. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33431. var options = {
  33432. segments: segments,
  33433. diameterX: diameter,
  33434. diameterY: diameter,
  33435. diameterZ: diameter,
  33436. sideOrientation: sideOrientation,
  33437. updatable: updatable
  33438. };
  33439. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33440. };
  33441. /**
  33442. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33443. * @param name defines the name of the mesh to create
  33444. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33445. * @param diameterTop set the top cap diameter (floats, default 1)
  33446. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33447. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33448. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33449. * @param scene defines the hosting scene
  33450. * @param updatable defines if the mesh must be flagged as updatable
  33451. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33452. * @returns a new Mesh
  33453. */
  33454. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33455. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33456. if (scene !== undefined) {
  33457. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33458. updatable = scene;
  33459. }
  33460. scene = subdivisions;
  33461. subdivisions = 1;
  33462. }
  33463. var options = {
  33464. height: height,
  33465. diameterTop: diameterTop,
  33466. diameterBottom: diameterBottom,
  33467. tessellation: tessellation,
  33468. subdivisions: subdivisions,
  33469. sideOrientation: sideOrientation,
  33470. updatable: updatable
  33471. };
  33472. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33473. };
  33474. // Torus (Code from SharpDX.org)
  33475. /**
  33476. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33477. * @param name defines the name of the mesh to create
  33478. * @param diameter sets the diameter size (float) of the torus (default 1)
  33479. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33480. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33481. * @param scene defines the hosting scene
  33482. * @param updatable defines if the mesh must be flagged as updatable
  33483. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33484. * @returns a new Mesh
  33485. */
  33486. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33487. var options = {
  33488. diameter: diameter,
  33489. thickness: thickness,
  33490. tessellation: tessellation,
  33491. sideOrientation: sideOrientation,
  33492. updatable: updatable
  33493. };
  33494. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33495. };
  33496. /**
  33497. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33498. * @param name defines the name of the mesh to create
  33499. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33500. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33501. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33502. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33503. * @param p the number of windings on X axis (positive integers, default 2)
  33504. * @param q the number of windings on Y axis (positive integers, default 3)
  33505. * @param scene defines the hosting scene
  33506. * @param updatable defines if the mesh must be flagged as updatable
  33507. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33508. * @returns a new Mesh
  33509. */
  33510. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33511. var options = {
  33512. radius: radius,
  33513. tube: tube,
  33514. radialSegments: radialSegments,
  33515. tubularSegments: tubularSegments,
  33516. p: p,
  33517. q: q,
  33518. sideOrientation: sideOrientation,
  33519. updatable: updatable
  33520. };
  33521. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33522. };
  33523. /**
  33524. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33525. * @param name defines the name of the mesh to create
  33526. * @param points is an array successive Vector3
  33527. * @param scene defines the hosting scene
  33528. * @param updatable defines if the mesh must be flagged as updatable
  33529. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  33530. * @returns a new Mesh
  33531. */
  33532. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33533. if (scene === void 0) { scene = null; }
  33534. if (updatable === void 0) { updatable = false; }
  33535. if (instance === void 0) { instance = null; }
  33536. var options = {
  33537. points: points,
  33538. updatable: updatable,
  33539. instance: instance
  33540. };
  33541. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33542. };
  33543. /**
  33544. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33545. * @param name defines the name of the mesh to create
  33546. * @param points is an array successive Vector3
  33547. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33548. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33549. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33550. * @param scene defines the hosting scene
  33551. * @param updatable defines if the mesh must be flagged as updatable
  33552. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  33553. * @returns a new Mesh
  33554. */
  33555. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33556. if (scene === void 0) { scene = null; }
  33557. var options = {
  33558. points: points,
  33559. dashSize: dashSize,
  33560. gapSize: gapSize,
  33561. dashNb: dashNb,
  33562. updatable: updatable,
  33563. instance: instance
  33564. };
  33565. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33566. };
  33567. /**
  33568. * Creates a polygon mesh.
  33569. * Please consider using the same method from the MeshBuilder class instead.
  33570. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33571. * 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.
  33572. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33573. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33574. * Remember you can only change the shape positions, not their number when updating a polygon.
  33575. */
  33576. /**
  33577. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33578. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33579. * @param name defines the name of the mesh to create
  33580. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  33581. * @param scene defines the hosting scene
  33582. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33583. * @param updatable defines if the mesh must be flagged as updatable
  33584. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33585. * @returns a new Mesh
  33586. */
  33587. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33588. var options = {
  33589. shape: shape,
  33590. holes: holes,
  33591. updatable: updatable,
  33592. sideOrientation: sideOrientation
  33593. };
  33594. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33595. };
  33596. /**
  33597. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33598. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33599. * @param name defines the name of the mesh to create
  33600. * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
  33601. * @param depth defines the height of extrusion
  33602. * @param scene defines the hosting scene
  33603. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33604. * @param updatable defines if the mesh must be flagged as updatable
  33605. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33606. * @returns a new Mesh
  33607. */
  33608. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33609. var options = {
  33610. shape: shape,
  33611. holes: holes,
  33612. depth: depth,
  33613. updatable: updatable,
  33614. sideOrientation: sideOrientation
  33615. };
  33616. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33617. };
  33618. /**
  33619. * Creates an extruded shape mesh.
  33620. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  33621. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33622. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33623. * @param name defines the name of the mesh to create
  33624. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  33625. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33626. * @param scale is the value to scale the shape
  33627. * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
  33628. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33629. * @param scene defines the hosting scene
  33630. * @param updatable defines if the mesh must be flagged as updatable
  33631. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33632. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  33633. * @returns a new Mesh
  33634. */
  33635. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33636. if (scene === void 0) { scene = null; }
  33637. var options = {
  33638. shape: shape,
  33639. path: path,
  33640. scale: scale,
  33641. rotation: rotation,
  33642. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33643. sideOrientation: sideOrientation,
  33644. instance: instance,
  33645. updatable: updatable
  33646. };
  33647. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33648. };
  33649. /**
  33650. * Creates an custom extruded shape mesh.
  33651. * The custom extrusion is a parametric shape.
  33652. * It has no predefined shape. Its final shape will depend on the input parameters.
  33653. * Please consider using the same method from the MeshBuilder class instead
  33654. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33655. * @param name defines the name of the mesh to create
  33656. * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
  33657. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33658. * @param scaleFunction is a custom Javascript function called on each path point
  33659. * @param rotationFunction is a custom Javascript function called on each path point
  33660. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33661. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33662. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33663. * @param scene defines the hosting scene
  33664. * @param updatable defines if the mesh must be flagged as updatable
  33665. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33666. * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  33667. * @returns a new Mesh
  33668. */
  33669. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33670. var options = {
  33671. shape: shape,
  33672. path: path,
  33673. scaleFunction: scaleFunction,
  33674. rotationFunction: rotationFunction,
  33675. ribbonCloseArray: ribbonCloseArray,
  33676. ribbonClosePath: ribbonClosePath,
  33677. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33678. sideOrientation: sideOrientation,
  33679. instance: instance,
  33680. updatable: updatable
  33681. };
  33682. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33683. };
  33684. /**
  33685. * Creates lathe mesh.
  33686. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33687. * Please consider using the same method from the MeshBuilder class instead
  33688. * @param name defines the name of the mesh to create
  33689. * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  33690. * @param radius is the radius value of the lathe
  33691. * @param tessellation is the side number of the lathe.
  33692. * @param scene defines the hosting scene
  33693. * @param updatable defines if the mesh must be flagged as updatable
  33694. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33695. * @returns a new Mesh
  33696. */
  33697. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33698. var options = {
  33699. shape: shape,
  33700. radius: radius,
  33701. tessellation: tessellation,
  33702. sideOrientation: sideOrientation,
  33703. updatable: updatable
  33704. };
  33705. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33706. };
  33707. /**
  33708. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33709. * @param name defines the name of the mesh to create
  33710. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33711. * @param scene defines the hosting scene
  33712. * @param updatable defines if the mesh must be flagged as updatable
  33713. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33714. * @returns a new Mesh
  33715. */
  33716. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33717. var options = {
  33718. size: size,
  33719. width: size,
  33720. height: size,
  33721. sideOrientation: sideOrientation,
  33722. updatable: updatable
  33723. };
  33724. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33725. };
  33726. /**
  33727. * Creates a ground mesh.
  33728. * Please consider using the same method from the MeshBuilder class instead
  33729. * @param name defines the name of the mesh to create
  33730. * @param width set the width of the ground
  33731. * @param height set the height of the ground
  33732. * @param subdivisions sets the number of subdivisions per side
  33733. * @param scene defines the hosting scene
  33734. * @param updatable defines if the mesh must be flagged as updatable
  33735. * @returns a new Mesh
  33736. */
  33737. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33738. var options = {
  33739. width: width,
  33740. height: height,
  33741. subdivisions: subdivisions,
  33742. updatable: updatable
  33743. };
  33744. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33745. };
  33746. /**
  33747. * Creates a tiled ground mesh.
  33748. * Please consider using the same method from the MeshBuilder class instead
  33749. * @param name defines the name of the mesh to create
  33750. * @param xmin set the ground minimum X coordinate
  33751. * @param zmin set the ground minimum Y coordinate
  33752. * @param xmax set the ground maximum X coordinate
  33753. * @param zmax set the ground maximum Z coordinate
  33754. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  33755. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  33756. * @param scene defines the hosting scene
  33757. * @param updatable defines if the mesh must be flagged as updatable
  33758. * @returns a new Mesh
  33759. */
  33760. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33761. var options = {
  33762. xmin: xmin,
  33763. zmin: zmin,
  33764. xmax: xmax,
  33765. zmax: zmax,
  33766. subdivisions: subdivisions,
  33767. precision: precision,
  33768. updatable: updatable
  33769. };
  33770. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33771. };
  33772. /**
  33773. * Creates a ground mesh from a height map.
  33774. * Please consider using the same method from the MeshBuilder class instead
  33775. * @see http://doc.babylonjs.com/babylon101/height_map
  33776. * @param name defines the name of the mesh to create
  33777. * @param url sets the URL of the height map image resource
  33778. * @param width set the ground width size
  33779. * @param height set the ground height size
  33780. * @param subdivisions sets the number of subdivision per side
  33781. * @param minHeight is the minimum altitude on the ground
  33782. * @param maxHeight is the maximum altitude on the ground
  33783. * @param scene defines the hosting scene
  33784. * @param updatable defines if the mesh must be flagged as updatable
  33785. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33786. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33787. * @returns a new Mesh
  33788. */
  33789. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33790. var options = {
  33791. width: width,
  33792. height: height,
  33793. subdivisions: subdivisions,
  33794. minHeight: minHeight,
  33795. maxHeight: maxHeight,
  33796. updatable: updatable,
  33797. onReady: onReady,
  33798. alphaFilter: alphaFilter
  33799. };
  33800. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33801. };
  33802. /**
  33803. * Creates a tube mesh.
  33804. * The tube is a parametric shape.
  33805. * It has no predefined shape. Its final shape will depend on the input parameters.
  33806. * Please consider using the same method from the MeshBuilder class instead
  33807. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33808. * @param name defines the name of the mesh to create
  33809. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33810. * @param radius sets the tube radius size
  33811. * @param tessellation is the number of sides on the tubular surface
  33812. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
  33813. * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  33814. * @param scene defines the hosting scene
  33815. * @param updatable defines if the mesh must be flagged as updatable
  33816. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33817. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  33818. * @returns a new Mesh
  33819. */
  33820. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33821. var options = {
  33822. path: path,
  33823. radius: radius,
  33824. tessellation: tessellation,
  33825. radiusFunction: radiusFunction,
  33826. arc: 1,
  33827. cap: cap,
  33828. updatable: updatable,
  33829. sideOrientation: sideOrientation,
  33830. instance: instance
  33831. };
  33832. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33833. };
  33834. /**
  33835. * Creates a polyhedron mesh.
  33836. * Please consider using the same method from the MeshBuilder class instead.
  33837. * * 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
  33838. * * The parameter `size` (positive float, default 1) sets the polygon size
  33839. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33840. * * 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`
  33841. * * 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
  33842. * * 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)`)
  33843. * * 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
  33844. * * 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
  33845. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33846. * * 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
  33847. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33848. * @param name defines the name of the mesh to create
  33849. * @param options defines the options used to create the mesh
  33850. * @param scene defines the hosting scene
  33851. * @returns a new Mesh
  33852. */
  33853. Mesh.CreatePolyhedron = function (name, options, scene) {
  33854. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33855. };
  33856. /**
  33857. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33858. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33859. * * 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`)
  33860. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33861. * * 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
  33862. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33863. * * 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
  33864. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33865. * @param name defines the name of the mesh
  33866. * @param options defines the options used to create the mesh
  33867. * @param scene defines the hosting scene
  33868. * @returns a new Mesh
  33869. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33870. */
  33871. Mesh.CreateIcoSphere = function (name, options, scene) {
  33872. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33873. };
  33874. /**
  33875. * Creates a decal mesh.
  33876. * Please consider using the same method from the MeshBuilder class instead.
  33877. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33878. * @param name defines the name of the mesh
  33879. * @param sourceMesh defines the mesh receiving the decal
  33880. * @param position sets the position of the decal in world coordinates
  33881. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33882. * @param size sets the decal scaling
  33883. * @param angle sets the angle to rotate the decal
  33884. * @returns a new Mesh
  33885. */
  33886. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33887. var options = {
  33888. position: position,
  33889. normal: normal,
  33890. size: size,
  33891. angle: angle
  33892. };
  33893. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33894. };
  33895. // Skeletons
  33896. /**
  33897. * Prepare internal position array for software CPU skinning
  33898. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33899. */
  33900. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33901. if (!this._sourcePositions) {
  33902. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33903. if (!source) {
  33904. return this._sourcePositions;
  33905. }
  33906. this._sourcePositions = new Float32Array(source);
  33907. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33908. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33909. }
  33910. }
  33911. return this._sourcePositions;
  33912. };
  33913. /**
  33914. * Prepare internal normal array for software CPU skinning
  33915. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33916. */
  33917. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33918. if (!this._sourceNormals) {
  33919. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33920. if (!source) {
  33921. return this._sourceNormals;
  33922. }
  33923. this._sourceNormals = new Float32Array(source);
  33924. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33925. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33926. }
  33927. }
  33928. return this._sourceNormals;
  33929. };
  33930. /**
  33931. * Updates the vertex buffer by applying transformation from the bones
  33932. * @param skeleton defines the skeleton to apply to current mesh
  33933. * @returns the current mesh
  33934. */
  33935. Mesh.prototype.applySkeleton = function (skeleton) {
  33936. if (!this.geometry) {
  33937. return this;
  33938. }
  33939. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33940. return this;
  33941. }
  33942. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33943. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33944. return this;
  33945. }
  33946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33947. return this;
  33948. }
  33949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33950. return this;
  33951. }
  33952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33953. return this;
  33954. }
  33955. if (!this._sourcePositions) {
  33956. var submeshes = this.subMeshes.slice();
  33957. this.setPositionsForCPUSkinning();
  33958. this.subMeshes = submeshes;
  33959. }
  33960. if (!this._sourceNormals) {
  33961. this.setNormalsForCPUSkinning();
  33962. }
  33963. // positionsData checks for not being Float32Array will only pass at most once
  33964. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33965. if (!positionsData) {
  33966. return this;
  33967. }
  33968. if (!(positionsData instanceof Float32Array)) {
  33969. positionsData = new Float32Array(positionsData);
  33970. }
  33971. // normalsData checks for not being Float32Array will only pass at most once
  33972. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33973. if (!normalsData) {
  33974. return this;
  33975. }
  33976. if (!(normalsData instanceof Float32Array)) {
  33977. normalsData = new Float32Array(normalsData);
  33978. }
  33979. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33980. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33981. if (!matricesWeightsData || !matricesIndicesData) {
  33982. return this;
  33983. }
  33984. var needExtras = this.numBoneInfluencers > 4;
  33985. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33986. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33987. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33988. var tempVector3 = BABYLON.Vector3.Zero();
  33989. var finalMatrix = new BABYLON.Matrix();
  33990. var tempMatrix = new BABYLON.Matrix();
  33991. var matWeightIdx = 0;
  33992. var inf;
  33993. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33994. var weight;
  33995. for (inf = 0; inf < 4; inf++) {
  33996. weight = matricesWeightsData[matWeightIdx + inf];
  33997. if (weight > 0) {
  33998. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33999. finalMatrix.addToSelf(tempMatrix);
  34000. }
  34001. }
  34002. if (needExtras) {
  34003. for (inf = 0; inf < 4; inf++) {
  34004. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34005. if (weight > 0) {
  34006. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34007. finalMatrix.addToSelf(tempMatrix);
  34008. }
  34009. }
  34010. }
  34011. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34012. tempVector3.toArray(positionsData, index);
  34013. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34014. tempVector3.toArray(normalsData, index);
  34015. finalMatrix.reset();
  34016. }
  34017. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34018. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34019. return this;
  34020. };
  34021. // Tools
  34022. /**
  34023. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  34024. * @param meshes defines the list of meshes to scan
  34025. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34026. */
  34027. Mesh.MinMax = function (meshes) {
  34028. var minVector = null;
  34029. var maxVector = null;
  34030. meshes.forEach(function (mesh, index, array) {
  34031. var boundingInfo = mesh.getBoundingInfo();
  34032. var boundingBox = boundingInfo.boundingBox;
  34033. if (!minVector || !maxVector) {
  34034. minVector = boundingBox.minimumWorld;
  34035. maxVector = boundingBox.maximumWorld;
  34036. }
  34037. else {
  34038. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34039. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34040. }
  34041. });
  34042. if (!minVector || !maxVector) {
  34043. return {
  34044. min: BABYLON.Vector3.Zero(),
  34045. max: BABYLON.Vector3.Zero()
  34046. };
  34047. }
  34048. return {
  34049. min: minVector,
  34050. max: maxVector
  34051. };
  34052. };
  34053. /**
  34054. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34055. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34056. * @returns a vector3
  34057. */
  34058. Mesh.Center = function (meshesOrMinMaxVector) {
  34059. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34060. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34061. };
  34062. /**
  34063. * Merge the array of meshes into a single mesh for performance reasons.
  34064. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34065. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34066. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34067. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34068. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34069. * @returns a new mesh
  34070. */
  34071. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34072. if (disposeSource === void 0) { disposeSource = true; }
  34073. var index;
  34074. if (!allow32BitsIndices) {
  34075. var totalVertices = 0;
  34076. // Counting vertices
  34077. for (index = 0; index < meshes.length; index++) {
  34078. if (meshes[index]) {
  34079. totalVertices += meshes[index].getTotalVertices();
  34080. if (totalVertices > 65536) {
  34081. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34082. return null;
  34083. }
  34084. }
  34085. }
  34086. }
  34087. // Merge
  34088. var vertexData = null;
  34089. var otherVertexData;
  34090. var indiceArray = new Array();
  34091. var source = null;
  34092. for (index = 0; index < meshes.length; index++) {
  34093. if (meshes[index]) {
  34094. var wm = meshes[index].computeWorldMatrix(true);
  34095. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34096. otherVertexData.transform(wm);
  34097. if (vertexData) {
  34098. vertexData.merge(otherVertexData, allow32BitsIndices);
  34099. }
  34100. else {
  34101. vertexData = otherVertexData;
  34102. source = meshes[index];
  34103. }
  34104. if (subdivideWithSubMeshes) {
  34105. indiceArray.push(meshes[index].getTotalIndices());
  34106. }
  34107. }
  34108. }
  34109. source = source;
  34110. if (!meshSubclass) {
  34111. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34112. }
  34113. vertexData.applyToMesh(meshSubclass);
  34114. // Setting properties
  34115. meshSubclass.material = source.material;
  34116. meshSubclass.checkCollisions = source.checkCollisions;
  34117. // Cleaning
  34118. if (disposeSource) {
  34119. for (index = 0; index < meshes.length; index++) {
  34120. if (meshes[index]) {
  34121. meshes[index].dispose();
  34122. }
  34123. }
  34124. }
  34125. // Subdivide
  34126. if (subdivideWithSubMeshes) {
  34127. //-- removal of global submesh
  34128. meshSubclass.releaseSubMeshes();
  34129. index = 0;
  34130. var offset = 0;
  34131. //-- apply subdivision according to index table
  34132. while (index < indiceArray.length) {
  34133. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34134. offset += indiceArray[index];
  34135. index++;
  34136. }
  34137. }
  34138. return meshSubclass;
  34139. };
  34140. // Consts
  34141. /**
  34142. * Mesh side orientation : usually the external or front surface
  34143. */
  34144. Mesh.FRONTSIDE = 0;
  34145. /**
  34146. * Mesh side orientation : usually the internal or back surface
  34147. */
  34148. Mesh.BACKSIDE = 1;
  34149. /**
  34150. * Mesh side orientation : both internal and external or front and back surfaces
  34151. */
  34152. Mesh.DOUBLESIDE = 2;
  34153. /**
  34154. * Mesh side orientation : by default, `FRONTSIDE`
  34155. */
  34156. Mesh.DEFAULTSIDE = 0;
  34157. /**
  34158. * Mesh cap setting : no cap
  34159. */
  34160. Mesh.NO_CAP = 0;
  34161. /**
  34162. * Mesh cap setting : one cap at the beginning of the mesh
  34163. */
  34164. Mesh.CAP_START = 1;
  34165. /**
  34166. * Mesh cap setting : one cap at the end of the mesh
  34167. */
  34168. Mesh.CAP_END = 2;
  34169. /**
  34170. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34171. */
  34172. Mesh.CAP_ALL = 3;
  34173. return Mesh;
  34174. }(BABYLON.AbstractMesh));
  34175. BABYLON.Mesh = Mesh;
  34176. })(BABYLON || (BABYLON = {}));
  34177. //# sourceMappingURL=babylon.mesh.js.map
  34178. var BABYLON;
  34179. (function (BABYLON) {
  34180. var BaseSubMesh = /** @class */ (function () {
  34181. function BaseSubMesh() {
  34182. }
  34183. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34184. get: function () {
  34185. return this._materialEffect;
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34191. if (defines === void 0) { defines = null; }
  34192. if (this._materialEffect === effect) {
  34193. if (!effect) {
  34194. this._materialDefines = null;
  34195. }
  34196. return;
  34197. }
  34198. this._materialDefines = defines;
  34199. this._materialEffect = effect;
  34200. };
  34201. return BaseSubMesh;
  34202. }());
  34203. BABYLON.BaseSubMesh = BaseSubMesh;
  34204. var SubMesh = /** @class */ (function (_super) {
  34205. __extends(SubMesh, _super);
  34206. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34207. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34208. var _this = _super.call(this) || this;
  34209. _this.materialIndex = materialIndex;
  34210. _this.verticesStart = verticesStart;
  34211. _this.verticesCount = verticesCount;
  34212. _this.indexStart = indexStart;
  34213. _this.indexCount = indexCount;
  34214. /** @hidden */
  34215. _this._renderId = 0;
  34216. _this._mesh = mesh;
  34217. _this._renderingMesh = renderingMesh || mesh;
  34218. mesh.subMeshes.push(_this);
  34219. _this._trianglePlanes = [];
  34220. _this._id = mesh.subMeshes.length - 1;
  34221. if (createBoundingBox) {
  34222. _this.refreshBoundingInfo();
  34223. mesh.computeWorldMatrix(true);
  34224. }
  34225. return _this;
  34226. }
  34227. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34228. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34229. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34230. };
  34231. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34232. get: function () {
  34233. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34234. },
  34235. enumerable: true,
  34236. configurable: true
  34237. });
  34238. /**
  34239. * Returns the submesh BoudingInfo object.
  34240. */
  34241. SubMesh.prototype.getBoundingInfo = function () {
  34242. if (this.IsGlobal) {
  34243. return this._mesh.getBoundingInfo();
  34244. }
  34245. return this._boundingInfo;
  34246. };
  34247. /**
  34248. * Sets the submesh BoundingInfo.
  34249. * Return the SubMesh.
  34250. */
  34251. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34252. this._boundingInfo = boundingInfo;
  34253. return this;
  34254. };
  34255. /**
  34256. * Returns the mesh of the current submesh.
  34257. */
  34258. SubMesh.prototype.getMesh = function () {
  34259. return this._mesh;
  34260. };
  34261. /**
  34262. * Returns the rendering mesh of the submesh.
  34263. */
  34264. SubMesh.prototype.getRenderingMesh = function () {
  34265. return this._renderingMesh;
  34266. };
  34267. /**
  34268. * Returns the submesh material.
  34269. */
  34270. SubMesh.prototype.getMaterial = function () {
  34271. var rootMaterial = this._renderingMesh.material;
  34272. if (rootMaterial === null || rootMaterial === undefined) {
  34273. return this._mesh.getScene().defaultMaterial;
  34274. }
  34275. else if (rootMaterial.getSubMaterial) {
  34276. var multiMaterial = rootMaterial;
  34277. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34278. if (this._currentMaterial !== effectiveMaterial) {
  34279. this._currentMaterial = effectiveMaterial;
  34280. this._materialDefines = null;
  34281. }
  34282. return effectiveMaterial;
  34283. }
  34284. return rootMaterial;
  34285. };
  34286. // Methods
  34287. /**
  34288. * Sets a new updated BoundingInfo object to the submesh.
  34289. * Returns the SubMesh.
  34290. */
  34291. SubMesh.prototype.refreshBoundingInfo = function () {
  34292. this._lastColliderWorldVertices = null;
  34293. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34294. return this;
  34295. }
  34296. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34297. if (!data) {
  34298. this._boundingInfo = this._mesh.getBoundingInfo();
  34299. return this;
  34300. }
  34301. var indices = this._renderingMesh.getIndices();
  34302. var extend;
  34303. //is this the only submesh?
  34304. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34305. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34306. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34307. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34308. }
  34309. else {
  34310. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34311. }
  34312. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34313. return this;
  34314. };
  34315. /** @hidden */
  34316. SubMesh.prototype._checkCollision = function (collider) {
  34317. var boundingInfo = this.getBoundingInfo();
  34318. return boundingInfo._checkCollision(collider);
  34319. };
  34320. /**
  34321. * Updates the submesh BoundingInfo.
  34322. * Returns the Submesh.
  34323. */
  34324. SubMesh.prototype.updateBoundingInfo = function (world) {
  34325. var boundingInfo = this.getBoundingInfo();
  34326. if (!boundingInfo) {
  34327. this.refreshBoundingInfo();
  34328. boundingInfo = this.getBoundingInfo();
  34329. }
  34330. boundingInfo.update(world);
  34331. return this;
  34332. };
  34333. /**
  34334. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34335. * Boolean returned.
  34336. */
  34337. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34338. var boundingInfo = this.getBoundingInfo();
  34339. if (!boundingInfo) {
  34340. return false;
  34341. }
  34342. return boundingInfo.isInFrustum(frustumPlanes);
  34343. };
  34344. /**
  34345. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34346. * Boolean returned.
  34347. */
  34348. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34349. var boundingInfo = this.getBoundingInfo();
  34350. if (!boundingInfo) {
  34351. return false;
  34352. }
  34353. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34354. };
  34355. /**
  34356. * Renders the submesh.
  34357. * Returns it.
  34358. */
  34359. SubMesh.prototype.render = function (enableAlphaMode) {
  34360. this._renderingMesh.render(this, enableAlphaMode);
  34361. return this;
  34362. };
  34363. /**
  34364. * Returns a new Index Buffer.
  34365. * Type returned : WebGLBuffer.
  34366. */
  34367. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34368. if (!this._linesIndexBuffer) {
  34369. var linesIndices = [];
  34370. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34371. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34372. }
  34373. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34374. this.linesIndexCount = linesIndices.length;
  34375. }
  34376. return this._linesIndexBuffer;
  34377. };
  34378. /**
  34379. * True is the passed Ray intersects the submesh bounding box.
  34380. * Boolean returned.
  34381. */
  34382. SubMesh.prototype.canIntersects = function (ray) {
  34383. var boundingInfo = this.getBoundingInfo();
  34384. if (!boundingInfo) {
  34385. return false;
  34386. }
  34387. return ray.intersectsBox(boundingInfo.boundingBox);
  34388. };
  34389. /**
  34390. * Returns an object IntersectionInfo.
  34391. */
  34392. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34393. var intersectInfo = null;
  34394. var material = this.getMaterial();
  34395. if (!material) {
  34396. return null;
  34397. }
  34398. switch (material.fillMode) {
  34399. case BABYLON.Material.PointListDrawMode:
  34400. case BABYLON.Material.LineListDrawMode:
  34401. case BABYLON.Material.LineLoopDrawMode:
  34402. case BABYLON.Material.LineStripDrawMode:
  34403. case BABYLON.Material.TriangleFanDrawMode:
  34404. case BABYLON.Material.TriangleStripDrawMode:
  34405. return null;
  34406. }
  34407. // LineMesh first as it's also a Mesh...
  34408. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34409. var lineMesh = this._mesh;
  34410. // Line test
  34411. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34412. var p0 = positions[indices[index]];
  34413. var p1 = positions[indices[index + 1]];
  34414. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34415. if (length < 0) {
  34416. continue;
  34417. }
  34418. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34419. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34420. if (fastCheck) {
  34421. break;
  34422. }
  34423. }
  34424. }
  34425. }
  34426. else {
  34427. // Triangles test
  34428. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34429. var p0 = positions[indices[index]];
  34430. var p1 = positions[indices[index + 1]];
  34431. var p2 = positions[indices[index + 2]];
  34432. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34433. if (currentIntersectInfo) {
  34434. if (currentIntersectInfo.distance < 0) {
  34435. continue;
  34436. }
  34437. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34438. intersectInfo = currentIntersectInfo;
  34439. intersectInfo.faceId = index / 3;
  34440. if (fastCheck) {
  34441. break;
  34442. }
  34443. }
  34444. }
  34445. }
  34446. }
  34447. return intersectInfo;
  34448. };
  34449. /** @hidden */
  34450. SubMesh.prototype._rebuild = function () {
  34451. if (this._linesIndexBuffer) {
  34452. this._linesIndexBuffer = null;
  34453. }
  34454. };
  34455. // Clone
  34456. /**
  34457. * Creates a new Submesh from the passed Mesh.
  34458. */
  34459. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34460. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34461. if (!this.IsGlobal) {
  34462. var boundingInfo = this.getBoundingInfo();
  34463. if (!boundingInfo) {
  34464. return result;
  34465. }
  34466. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34467. }
  34468. return result;
  34469. };
  34470. // Dispose
  34471. /**
  34472. * Disposes the Submesh.
  34473. * Returns nothing.
  34474. */
  34475. SubMesh.prototype.dispose = function () {
  34476. if (this._linesIndexBuffer) {
  34477. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34478. this._linesIndexBuffer = null;
  34479. }
  34480. // Remove from mesh
  34481. var index = this._mesh.subMeshes.indexOf(this);
  34482. this._mesh.subMeshes.splice(index, 1);
  34483. };
  34484. // Statics
  34485. /**
  34486. * Creates a new Submesh from the passed parameters :
  34487. * - materialIndex (integer) : the index of the main mesh material.
  34488. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34489. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34490. * - mesh (Mesh) : the main mesh to create the submesh from.
  34491. * - renderingMesh (optional Mesh) : rendering mesh.
  34492. */
  34493. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34494. var minVertexIndex = Number.MAX_VALUE;
  34495. var maxVertexIndex = -Number.MAX_VALUE;
  34496. renderingMesh = (renderingMesh || mesh);
  34497. var indices = renderingMesh.getIndices();
  34498. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34499. var vertexIndex = indices[index];
  34500. if (vertexIndex < minVertexIndex)
  34501. minVertexIndex = vertexIndex;
  34502. if (vertexIndex > maxVertexIndex)
  34503. maxVertexIndex = vertexIndex;
  34504. }
  34505. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34506. };
  34507. return SubMesh;
  34508. }(BaseSubMesh));
  34509. BABYLON.SubMesh = SubMesh;
  34510. })(BABYLON || (BABYLON = {}));
  34511. //# sourceMappingURL=babylon.subMesh.js.map
  34512. var __assign = (this && this.__assign) || function () {
  34513. __assign = Object.assign || function(t) {
  34514. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34515. s = arguments[i];
  34516. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34517. t[p] = s[p];
  34518. }
  34519. return t;
  34520. };
  34521. return __assign.apply(this, arguments);
  34522. };
  34523. var BABYLON;
  34524. (function (BABYLON) {
  34525. /**
  34526. * Manages the defines for the Material
  34527. */
  34528. var MaterialDefines = /** @class */ (function () {
  34529. function MaterialDefines() {
  34530. this._isDirty = true;
  34531. /** @hidden */
  34532. this._areLightsDirty = true;
  34533. /** @hidden */
  34534. this._areAttributesDirty = true;
  34535. /** @hidden */
  34536. this._areTexturesDirty = true;
  34537. /** @hidden */
  34538. this._areFresnelDirty = true;
  34539. /** @hidden */
  34540. this._areMiscDirty = true;
  34541. /** @hidden */
  34542. this._areImageProcessingDirty = true;
  34543. /** @hidden */
  34544. this._normals = false;
  34545. /** @hidden */
  34546. this._uvs = false;
  34547. /** @hidden */
  34548. this._needNormals = false;
  34549. /** @hidden */
  34550. this._needUVs = false;
  34551. }
  34552. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34553. /**
  34554. * Specifies if the material needs to be re-calculated
  34555. */
  34556. get: function () {
  34557. return this._isDirty;
  34558. },
  34559. enumerable: true,
  34560. configurable: true
  34561. });
  34562. /**
  34563. * Marks the material to indicate that it has been re-calculated
  34564. */
  34565. MaterialDefines.prototype.markAsProcessed = function () {
  34566. this._isDirty = false;
  34567. this._areAttributesDirty = false;
  34568. this._areTexturesDirty = false;
  34569. this._areFresnelDirty = false;
  34570. this._areLightsDirty = false;
  34571. this._areMiscDirty = false;
  34572. this._areImageProcessingDirty = false;
  34573. };
  34574. /**
  34575. * Marks the material to indicate that it needs to be re-calculated
  34576. */
  34577. MaterialDefines.prototype.markAsUnprocessed = function () {
  34578. this._isDirty = true;
  34579. };
  34580. /**
  34581. * Marks the material to indicate all of its defines need to be re-calculated
  34582. */
  34583. MaterialDefines.prototype.markAllAsDirty = function () {
  34584. this._areTexturesDirty = true;
  34585. this._areAttributesDirty = true;
  34586. this._areLightsDirty = true;
  34587. this._areFresnelDirty = true;
  34588. this._areMiscDirty = true;
  34589. this._areImageProcessingDirty = true;
  34590. this._isDirty = true;
  34591. };
  34592. /**
  34593. * Marks the material to indicate that image processing needs to be re-calculated
  34594. */
  34595. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34596. this._areImageProcessingDirty = true;
  34597. this._isDirty = true;
  34598. };
  34599. /**
  34600. * Marks the material to indicate the lights need to be re-calculated
  34601. */
  34602. MaterialDefines.prototype.markAsLightDirty = function () {
  34603. this._areLightsDirty = true;
  34604. this._isDirty = true;
  34605. };
  34606. /**
  34607. * Marks the attribute state as changed
  34608. */
  34609. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34610. this._areAttributesDirty = true;
  34611. this._isDirty = true;
  34612. };
  34613. /**
  34614. * Marks the texture state as changed
  34615. */
  34616. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34617. this._areTexturesDirty = true;
  34618. this._isDirty = true;
  34619. };
  34620. /**
  34621. * Marks the fresnel state as changed
  34622. */
  34623. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34624. this._areFresnelDirty = true;
  34625. this._isDirty = true;
  34626. };
  34627. /**
  34628. * Marks the misc state as changed
  34629. */
  34630. MaterialDefines.prototype.markAsMiscDirty = function () {
  34631. this._areMiscDirty = true;
  34632. this._isDirty = true;
  34633. };
  34634. /**
  34635. * Rebuilds the material defines
  34636. */
  34637. MaterialDefines.prototype.rebuild = function () {
  34638. if (this._keys) {
  34639. delete this._keys;
  34640. }
  34641. this._keys = [];
  34642. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34643. var key = _a[_i];
  34644. if (key[0] === "_") {
  34645. continue;
  34646. }
  34647. this._keys.push(key);
  34648. }
  34649. };
  34650. /**
  34651. * Specifies if two material defines are equal
  34652. * @param other - A material define instance to compare to
  34653. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34654. */
  34655. MaterialDefines.prototype.isEqual = function (other) {
  34656. if (this._keys.length !== other._keys.length) {
  34657. return false;
  34658. }
  34659. for (var index = 0; index < this._keys.length; index++) {
  34660. var prop = this._keys[index];
  34661. if (this[prop] !== other[prop]) {
  34662. return false;
  34663. }
  34664. }
  34665. return true;
  34666. };
  34667. /**
  34668. * Clones this instance's defines to another instance
  34669. * @param other - material defines to clone values to
  34670. */
  34671. MaterialDefines.prototype.cloneTo = function (other) {
  34672. if (this._keys.length !== other._keys.length) {
  34673. other._keys = this._keys.slice(0);
  34674. }
  34675. for (var index = 0; index < this._keys.length; index++) {
  34676. var prop = this._keys[index];
  34677. other[prop] = this[prop];
  34678. }
  34679. };
  34680. /**
  34681. * Resets the material define values
  34682. */
  34683. MaterialDefines.prototype.reset = function () {
  34684. for (var index = 0; index < this._keys.length; index++) {
  34685. var prop = this._keys[index];
  34686. var type = typeof this[prop];
  34687. switch (type) {
  34688. case "number":
  34689. this[prop] = 0;
  34690. break;
  34691. case "string":
  34692. this[prop] = "";
  34693. break;
  34694. default:
  34695. this[prop] = false;
  34696. break;
  34697. }
  34698. }
  34699. };
  34700. /**
  34701. * Converts the material define values to a string
  34702. * @returns - String of material define information
  34703. */
  34704. MaterialDefines.prototype.toString = function () {
  34705. var result = "";
  34706. for (var index = 0; index < this._keys.length; index++) {
  34707. var prop = this._keys[index];
  34708. var value = this[prop];
  34709. var type = typeof value;
  34710. switch (type) {
  34711. case "number":
  34712. case "string":
  34713. result += "#define " + prop + " " + value + "\n";
  34714. break;
  34715. default:
  34716. if (value) {
  34717. result += "#define " + prop + "\n";
  34718. }
  34719. break;
  34720. }
  34721. }
  34722. return result;
  34723. };
  34724. return MaterialDefines;
  34725. }());
  34726. BABYLON.MaterialDefines = MaterialDefines;
  34727. /**
  34728. * Base class for the main features of a material in Babylon.js
  34729. */
  34730. var Material = /** @class */ (function () {
  34731. /**
  34732. * Creates a material instance
  34733. * @param name defines the name of the material
  34734. * @param scene defines the scene to reference
  34735. * @param doNotAdd specifies if the material should be added to the scene
  34736. */
  34737. function Material(name, scene, doNotAdd) {
  34738. /**
  34739. * Specifies if the ready state should be checked on each call
  34740. */
  34741. this.checkReadyOnEveryCall = false;
  34742. /**
  34743. * Specifies if the ready state should be checked once
  34744. */
  34745. this.checkReadyOnlyOnce = false;
  34746. /**
  34747. * The state of the material
  34748. */
  34749. this.state = "";
  34750. /**
  34751. * The alpha value of the material
  34752. */
  34753. this._alpha = 1.0;
  34754. /**
  34755. * Specifies if back face culling is enabled
  34756. */
  34757. this._backFaceCulling = true;
  34758. /**
  34759. * Specifies if the material should be serialized
  34760. */
  34761. this.doNotSerialize = false;
  34762. /**
  34763. * Specifies if the effect should be stored on sub meshes
  34764. */
  34765. this.storeEffectOnSubMeshes = false;
  34766. /**
  34767. * An event triggered when the material is disposed
  34768. */
  34769. this.onDisposeObservable = new BABYLON.Observable();
  34770. /**
  34771. * Stores the value of the alpha mode
  34772. */
  34773. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34774. /**
  34775. * Stores the state of the need depth pre-pass value
  34776. */
  34777. this._needDepthPrePass = false;
  34778. /**
  34779. * Specifies if depth writing should be disabled
  34780. */
  34781. this.disableDepthWrite = false;
  34782. /**
  34783. * Specifies if depth writing should be forced
  34784. */
  34785. this.forceDepthWrite = false;
  34786. /**
  34787. * Specifies if there should be a separate pass for culling
  34788. */
  34789. this.separateCullingPass = false;
  34790. /**
  34791. * Stores the state specifing if fog should be enabled
  34792. */
  34793. this._fogEnabled = true;
  34794. /**
  34795. * Stores the size of points
  34796. */
  34797. this.pointSize = 1.0;
  34798. /**
  34799. * Stores the z offset value
  34800. */
  34801. this.zOffset = 0;
  34802. /**
  34803. * @hidden
  34804. * Specifies if the material was previously ready
  34805. */
  34806. this._wasPreviouslyReady = false;
  34807. /**
  34808. * Stores the fill mode state
  34809. */
  34810. this._fillMode = Material.TriangleFillMode;
  34811. this.name = name;
  34812. this.id = name || BABYLON.Tools.RandomId();
  34813. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34814. this.uniqueId = this._scene.getUniqueId();
  34815. if (this._scene.useRightHandedSystem) {
  34816. this.sideOrientation = Material.ClockWiseSideOrientation;
  34817. }
  34818. else {
  34819. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34820. }
  34821. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34822. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34823. if (!doNotAdd) {
  34824. this._scene.materials.push(this);
  34825. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  34826. }
  34827. }
  34828. Object.defineProperty(Material, "TriangleFillMode", {
  34829. /**
  34830. * Returns the triangle fill mode
  34831. */
  34832. get: function () {
  34833. return Material._TriangleFillMode;
  34834. },
  34835. enumerable: true,
  34836. configurable: true
  34837. });
  34838. Object.defineProperty(Material, "WireFrameFillMode", {
  34839. /**
  34840. * Returns the wireframe mode
  34841. */
  34842. get: function () {
  34843. return Material._WireFrameFillMode;
  34844. },
  34845. enumerable: true,
  34846. configurable: true
  34847. });
  34848. Object.defineProperty(Material, "PointFillMode", {
  34849. /**
  34850. * Returns the point fill mode
  34851. */
  34852. get: function () {
  34853. return Material._PointFillMode;
  34854. },
  34855. enumerable: true,
  34856. configurable: true
  34857. });
  34858. Object.defineProperty(Material, "PointListDrawMode", {
  34859. /**
  34860. * Returns the point list draw mode
  34861. */
  34862. get: function () {
  34863. return Material._PointListDrawMode;
  34864. },
  34865. enumerable: true,
  34866. configurable: true
  34867. });
  34868. Object.defineProperty(Material, "LineListDrawMode", {
  34869. /**
  34870. * Returns the line list draw mode
  34871. */
  34872. get: function () {
  34873. return Material._LineListDrawMode;
  34874. },
  34875. enumerable: true,
  34876. configurable: true
  34877. });
  34878. Object.defineProperty(Material, "LineLoopDrawMode", {
  34879. /**
  34880. * Returns the line loop draw mode
  34881. */
  34882. get: function () {
  34883. return Material._LineLoopDrawMode;
  34884. },
  34885. enumerable: true,
  34886. configurable: true
  34887. });
  34888. Object.defineProperty(Material, "LineStripDrawMode", {
  34889. /**
  34890. * Returns the line strip draw mode
  34891. */
  34892. get: function () {
  34893. return Material._LineStripDrawMode;
  34894. },
  34895. enumerable: true,
  34896. configurable: true
  34897. });
  34898. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34899. /**
  34900. * Returns the triangle strip draw mode
  34901. */
  34902. get: function () {
  34903. return Material._TriangleStripDrawMode;
  34904. },
  34905. enumerable: true,
  34906. configurable: true
  34907. });
  34908. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34909. /**
  34910. * Returns the triangle fan draw mode
  34911. */
  34912. get: function () {
  34913. return Material._TriangleFanDrawMode;
  34914. },
  34915. enumerable: true,
  34916. configurable: true
  34917. });
  34918. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34919. /**
  34920. * Returns the clock-wise side orientation
  34921. */
  34922. get: function () {
  34923. return Material._ClockWiseSideOrientation;
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34929. /**
  34930. * Returns the counter clock-wise side orientation
  34931. */
  34932. get: function () {
  34933. return Material._CounterClockWiseSideOrientation;
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(Material.prototype, "alpha", {
  34939. /**
  34940. * Gets the alpha value of the material
  34941. */
  34942. get: function () {
  34943. return this._alpha;
  34944. },
  34945. /**
  34946. * Sets the alpha value of the material
  34947. */
  34948. set: function (value) {
  34949. if (this._alpha === value) {
  34950. return;
  34951. }
  34952. this._alpha = value;
  34953. this.markAsDirty(Material.MiscDirtyFlag);
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34959. /**
  34960. * Gets the back-face culling state
  34961. */
  34962. get: function () {
  34963. return this._backFaceCulling;
  34964. },
  34965. /**
  34966. * Sets the back-face culling state
  34967. */
  34968. set: function (value) {
  34969. if (this._backFaceCulling === value) {
  34970. return;
  34971. }
  34972. this._backFaceCulling = value;
  34973. this.markAsDirty(Material.TextureDirtyFlag);
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  34979. /**
  34980. * Gets a boolean indicating that current material needs to register RTT
  34981. */
  34982. get: function () {
  34983. return false;
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(Material.prototype, "onDispose", {
  34989. /**
  34990. * Called during a dispose event
  34991. */
  34992. set: function (callback) {
  34993. if (this._onDisposeObserver) {
  34994. this.onDisposeObservable.remove(this._onDisposeObserver);
  34995. }
  34996. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34997. },
  34998. enumerable: true,
  34999. configurable: true
  35000. });
  35001. Object.defineProperty(Material.prototype, "onBindObservable", {
  35002. /**
  35003. * An event triggered when the material is bound
  35004. */
  35005. get: function () {
  35006. if (!this._onBindObservable) {
  35007. this._onBindObservable = new BABYLON.Observable();
  35008. }
  35009. return this._onBindObservable;
  35010. },
  35011. enumerable: true,
  35012. configurable: true
  35013. });
  35014. Object.defineProperty(Material.prototype, "onBind", {
  35015. /**
  35016. * Called during a bind event
  35017. */
  35018. set: function (callback) {
  35019. if (this._onBindObserver) {
  35020. this.onBindObservable.remove(this._onBindObserver);
  35021. }
  35022. this._onBindObserver = this.onBindObservable.add(callback);
  35023. },
  35024. enumerable: true,
  35025. configurable: true
  35026. });
  35027. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35028. /**
  35029. * An event triggered when the material is unbound
  35030. */
  35031. get: function () {
  35032. if (!this._onUnBindObservable) {
  35033. this._onUnBindObservable = new BABYLON.Observable();
  35034. }
  35035. return this._onUnBindObservable;
  35036. },
  35037. enumerable: true,
  35038. configurable: true
  35039. });
  35040. Object.defineProperty(Material.prototype, "alphaMode", {
  35041. /**
  35042. * Gets the value of the alpha mode
  35043. */
  35044. get: function () {
  35045. return this._alphaMode;
  35046. },
  35047. /**
  35048. * Sets the value of the alpha mode.
  35049. *
  35050. * | Value | Type | Description |
  35051. * | --- | --- | --- |
  35052. * | 0 | ALPHA_DISABLE | |
  35053. * | 1 | ALPHA_ADD | |
  35054. * | 2 | ALPHA_COMBINE | |
  35055. * | 3 | ALPHA_SUBTRACT | |
  35056. * | 4 | ALPHA_MULTIPLY | |
  35057. * | 5 | ALPHA_MAXIMIZED | |
  35058. * | 6 | ALPHA_ONEONE | |
  35059. * | 7 | ALPHA_PREMULTIPLIED | |
  35060. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35061. * | 9 | ALPHA_INTERPOLATE | |
  35062. * | 10 | ALPHA_SCREENMODE | |
  35063. *
  35064. */
  35065. set: function (value) {
  35066. if (this._alphaMode === value) {
  35067. return;
  35068. }
  35069. this._alphaMode = value;
  35070. this.markAsDirty(Material.TextureDirtyFlag);
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35076. /**
  35077. * Gets the depth pre-pass value
  35078. */
  35079. get: function () {
  35080. return this._needDepthPrePass;
  35081. },
  35082. /**
  35083. * Sets the need depth pre-pass value
  35084. */
  35085. set: function (value) {
  35086. if (this._needDepthPrePass === value) {
  35087. return;
  35088. }
  35089. this._needDepthPrePass = value;
  35090. if (this._needDepthPrePass) {
  35091. this.checkReadyOnEveryCall = true;
  35092. }
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(Material.prototype, "fogEnabled", {
  35098. /**
  35099. * Gets the value of the fog enabled state
  35100. */
  35101. get: function () {
  35102. return this._fogEnabled;
  35103. },
  35104. /**
  35105. * Sets the state for enabling fog
  35106. */
  35107. set: function (value) {
  35108. if (this._fogEnabled === value) {
  35109. return;
  35110. }
  35111. this._fogEnabled = value;
  35112. this.markAsDirty(Material.MiscDirtyFlag);
  35113. },
  35114. enumerable: true,
  35115. configurable: true
  35116. });
  35117. Object.defineProperty(Material.prototype, "wireframe", {
  35118. /**
  35119. * Gets a value specifying if wireframe mode is enabled
  35120. */
  35121. get: function () {
  35122. switch (this._fillMode) {
  35123. case Material.WireFrameFillMode:
  35124. case Material.LineListDrawMode:
  35125. case Material.LineLoopDrawMode:
  35126. case Material.LineStripDrawMode:
  35127. return true;
  35128. }
  35129. return this._scene.forceWireframe;
  35130. },
  35131. /**
  35132. * Sets the state of wireframe mode
  35133. */
  35134. set: function (value) {
  35135. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35136. },
  35137. enumerable: true,
  35138. configurable: true
  35139. });
  35140. Object.defineProperty(Material.prototype, "pointsCloud", {
  35141. /**
  35142. * Gets the value specifying if point clouds are enabled
  35143. */
  35144. get: function () {
  35145. switch (this._fillMode) {
  35146. case Material.PointFillMode:
  35147. case Material.PointListDrawMode:
  35148. return true;
  35149. }
  35150. return this._scene.forcePointsCloud;
  35151. },
  35152. /**
  35153. * Sets the state of point cloud mode
  35154. */
  35155. set: function (value) {
  35156. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(Material.prototype, "fillMode", {
  35162. /**
  35163. * Gets the material fill mode
  35164. */
  35165. get: function () {
  35166. return this._fillMode;
  35167. },
  35168. /**
  35169. * Sets the material fill mode
  35170. */
  35171. set: function (value) {
  35172. if (this._fillMode === value) {
  35173. return;
  35174. }
  35175. this._fillMode = value;
  35176. this.markAsDirty(Material.MiscDirtyFlag);
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. /**
  35182. * Returns a string representation of the current material
  35183. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35184. * @returns a string with material information
  35185. */
  35186. Material.prototype.toString = function (fullDetails) {
  35187. var ret = "Name: " + this.name;
  35188. if (fullDetails) {
  35189. }
  35190. return ret;
  35191. };
  35192. /**
  35193. * Gets the class name of the material
  35194. * @returns a string with the class name of the material
  35195. */
  35196. Material.prototype.getClassName = function () {
  35197. return "Material";
  35198. };
  35199. Object.defineProperty(Material.prototype, "isFrozen", {
  35200. /**
  35201. * Specifies if updates for the material been locked
  35202. */
  35203. get: function () {
  35204. return this.checkReadyOnlyOnce;
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. /**
  35210. * Locks updates for the material
  35211. */
  35212. Material.prototype.freeze = function () {
  35213. this.checkReadyOnlyOnce = true;
  35214. };
  35215. /**
  35216. * Unlocks updates for the material
  35217. */
  35218. Material.prototype.unfreeze = function () {
  35219. this.checkReadyOnlyOnce = false;
  35220. };
  35221. /**
  35222. * Specifies if the material is ready to be used
  35223. * @param mesh defines the mesh to check
  35224. * @param useInstances specifies if instances should be used
  35225. * @returns a boolean indicating if the material is ready to be used
  35226. */
  35227. Material.prototype.isReady = function (mesh, useInstances) {
  35228. return true;
  35229. };
  35230. /**
  35231. * Specifies that the submesh is ready to be used
  35232. * @param mesh defines the mesh to check
  35233. * @param subMesh defines which submesh to check
  35234. * @param useInstances specifies that instances should be used
  35235. * @returns a boolean indicating that the submesh is ready or not
  35236. */
  35237. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35238. return false;
  35239. };
  35240. /**
  35241. * Returns the material effect
  35242. * @returns the effect associated with the material
  35243. */
  35244. Material.prototype.getEffect = function () {
  35245. return this._effect;
  35246. };
  35247. /**
  35248. * Returns the current scene
  35249. * @returns a Scene
  35250. */
  35251. Material.prototype.getScene = function () {
  35252. return this._scene;
  35253. };
  35254. /**
  35255. * Specifies if the material will require alpha blending
  35256. * @returns a boolean specifying if alpha blending is needed
  35257. */
  35258. Material.prototype.needAlphaBlending = function () {
  35259. return (this.alpha < 1.0);
  35260. };
  35261. /**
  35262. * Specifies if the mesh will require alpha blending
  35263. * @param mesh defines the mesh to check
  35264. * @returns a boolean specifying if alpha blending is needed for the mesh
  35265. */
  35266. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35267. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35268. };
  35269. /**
  35270. * Specifies if this material should be rendered in alpha test mode
  35271. * @returns a boolean specifying if an alpha test is needed.
  35272. */
  35273. Material.prototype.needAlphaTesting = function () {
  35274. return false;
  35275. };
  35276. /**
  35277. * Gets the texture used for the alpha test
  35278. * @returns the texture to use for alpha testing
  35279. */
  35280. Material.prototype.getAlphaTestTexture = function () {
  35281. return null;
  35282. };
  35283. /**
  35284. * Marks the material to indicate that it needs to be re-calculated
  35285. */
  35286. Material.prototype.markDirty = function () {
  35287. this._wasPreviouslyReady = false;
  35288. };
  35289. /** @hidden */
  35290. Material.prototype._preBind = function (effect, overrideOrientation) {
  35291. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35292. var engine = this._scene.getEngine();
  35293. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35294. var reverse = orientation === Material.ClockWiseSideOrientation;
  35295. engine.enableEffect(effect ? effect : this._effect);
  35296. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35297. return reverse;
  35298. };
  35299. /**
  35300. * Binds the material to the mesh
  35301. * @param world defines the world transformation matrix
  35302. * @param mesh defines the mesh to bind the material to
  35303. */
  35304. Material.prototype.bind = function (world, mesh) {
  35305. };
  35306. /**
  35307. * Binds the submesh to the material
  35308. * @param world defines the world transformation matrix
  35309. * @param mesh defines the mesh containing the submesh
  35310. * @param subMesh defines the submesh to bind the material to
  35311. */
  35312. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35313. };
  35314. /**
  35315. * Binds the world matrix to the material
  35316. * @param world defines the world transformation matrix
  35317. */
  35318. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35319. };
  35320. /**
  35321. * Binds the scene's uniform buffer to the effect.
  35322. * @param effect defines the effect to bind to the scene uniform buffer
  35323. * @param sceneUbo defines the uniform buffer storing scene data
  35324. */
  35325. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35326. sceneUbo.bindToEffect(effect, "Scene");
  35327. };
  35328. /**
  35329. * Binds the view matrix to the effect
  35330. * @param effect defines the effect to bind the view matrix to
  35331. */
  35332. Material.prototype.bindView = function (effect) {
  35333. if (!this._useUBO) {
  35334. effect.setMatrix("view", this.getScene().getViewMatrix());
  35335. }
  35336. else {
  35337. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35338. }
  35339. };
  35340. /**
  35341. * Binds the view projection matrix to the effect
  35342. * @param effect defines the effect to bind the view projection matrix to
  35343. */
  35344. Material.prototype.bindViewProjection = function (effect) {
  35345. if (!this._useUBO) {
  35346. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35347. }
  35348. else {
  35349. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35350. }
  35351. };
  35352. /**
  35353. * Specifies if material alpha testing should be turned on for the mesh
  35354. * @param mesh defines the mesh to check
  35355. */
  35356. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35357. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35358. };
  35359. /**
  35360. * Processes to execute after binding the material to a mesh
  35361. * @param mesh defines the rendered mesh
  35362. */
  35363. Material.prototype._afterBind = function (mesh) {
  35364. this._scene._cachedMaterial = this;
  35365. if (mesh) {
  35366. this._scene._cachedVisibility = mesh.visibility;
  35367. }
  35368. else {
  35369. this._scene._cachedVisibility = 1;
  35370. }
  35371. if (this._onBindObservable && mesh) {
  35372. this._onBindObservable.notifyObservers(mesh);
  35373. }
  35374. if (this.disableDepthWrite) {
  35375. var engine = this._scene.getEngine();
  35376. this._cachedDepthWriteState = engine.getDepthWrite();
  35377. engine.setDepthWrite(false);
  35378. }
  35379. };
  35380. /**
  35381. * Unbinds the material from the mesh
  35382. */
  35383. Material.prototype.unbind = function () {
  35384. if (this._onUnBindObservable) {
  35385. this._onUnBindObservable.notifyObservers(this);
  35386. }
  35387. if (this.disableDepthWrite) {
  35388. var engine = this._scene.getEngine();
  35389. engine.setDepthWrite(this._cachedDepthWriteState);
  35390. }
  35391. };
  35392. /**
  35393. * Gets the active textures from the material
  35394. * @returns an array of textures
  35395. */
  35396. Material.prototype.getActiveTextures = function () {
  35397. return [];
  35398. };
  35399. /**
  35400. * Specifies if the material uses a texture
  35401. * @param texture defines the texture to check against the material
  35402. * @returns a boolean specifying if the material uses the texture
  35403. */
  35404. Material.prototype.hasTexture = function (texture) {
  35405. return false;
  35406. };
  35407. /**
  35408. * Makes a duplicate of the material, and gives it a new name
  35409. * @param name defines the new name for the duplicated material
  35410. * @returns the cloned material
  35411. */
  35412. Material.prototype.clone = function (name) {
  35413. return null;
  35414. };
  35415. /**
  35416. * Gets the meshes bound to the material
  35417. * @returns an array of meshes bound to the material
  35418. */
  35419. Material.prototype.getBindedMeshes = function () {
  35420. var result = new Array();
  35421. for (var index = 0; index < this._scene.meshes.length; index++) {
  35422. var mesh = this._scene.meshes[index];
  35423. if (mesh.material === this) {
  35424. result.push(mesh);
  35425. }
  35426. }
  35427. return result;
  35428. };
  35429. /**
  35430. * Force shader compilation
  35431. * @param mesh defines the mesh associated with this material
  35432. * @param onCompiled defines a function to execute once the material is compiled
  35433. * @param options defines the options to configure the compilation
  35434. */
  35435. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35436. var _this = this;
  35437. var localOptions = __assign({ clipPlane: false }, options);
  35438. var subMesh = new BABYLON.BaseSubMesh();
  35439. var scene = this.getScene();
  35440. var checkReady = function () {
  35441. if (!_this._scene || !_this._scene.getEngine()) {
  35442. return;
  35443. }
  35444. if (subMesh._materialDefines) {
  35445. subMesh._materialDefines._renderId = -1;
  35446. }
  35447. var clipPlaneState = scene.clipPlane;
  35448. if (localOptions.clipPlane) {
  35449. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35450. }
  35451. if (_this.storeEffectOnSubMeshes) {
  35452. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35453. if (onCompiled) {
  35454. onCompiled(_this);
  35455. }
  35456. }
  35457. else {
  35458. setTimeout(checkReady, 16);
  35459. }
  35460. }
  35461. else {
  35462. if (_this.isReady(mesh)) {
  35463. if (onCompiled) {
  35464. onCompiled(_this);
  35465. }
  35466. }
  35467. else {
  35468. setTimeout(checkReady, 16);
  35469. }
  35470. }
  35471. if (localOptions.clipPlane) {
  35472. scene.clipPlane = clipPlaneState;
  35473. }
  35474. };
  35475. checkReady();
  35476. };
  35477. /**
  35478. * Force shader compilation
  35479. * @param mesh defines the mesh that will use this material
  35480. * @param options defines additional options for compiling the shaders
  35481. * @returns a promise that resolves when the compilation completes
  35482. */
  35483. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35484. var _this = this;
  35485. return new Promise(function (resolve) {
  35486. _this.forceCompilation(mesh, function () {
  35487. resolve();
  35488. }, options);
  35489. });
  35490. };
  35491. /**
  35492. * Marks a define in the material to indicate that it needs to be re-computed
  35493. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35494. */
  35495. Material.prototype.markAsDirty = function (flag) {
  35496. if (flag & Material.TextureDirtyFlag) {
  35497. this._markAllSubMeshesAsTexturesDirty();
  35498. }
  35499. if (flag & Material.LightDirtyFlag) {
  35500. this._markAllSubMeshesAsLightsDirty();
  35501. }
  35502. if (flag & Material.FresnelDirtyFlag) {
  35503. this._markAllSubMeshesAsFresnelDirty();
  35504. }
  35505. if (flag & Material.AttributesDirtyFlag) {
  35506. this._markAllSubMeshesAsAttributesDirty();
  35507. }
  35508. if (flag & Material.MiscDirtyFlag) {
  35509. this._markAllSubMeshesAsMiscDirty();
  35510. }
  35511. this.getScene().resetCachedMaterial();
  35512. };
  35513. /**
  35514. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35515. * @param func defines a function which checks material defines against the submeshes
  35516. */
  35517. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35518. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35519. var mesh = _a[_i];
  35520. if (!mesh.subMeshes) {
  35521. continue;
  35522. }
  35523. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35524. var subMesh = _c[_b];
  35525. if (subMesh.getMaterial() !== this) {
  35526. continue;
  35527. }
  35528. if (!subMesh._materialDefines) {
  35529. continue;
  35530. }
  35531. func(subMesh._materialDefines);
  35532. }
  35533. }
  35534. };
  35535. /**
  35536. * Indicates that image processing needs to be re-calculated for all submeshes
  35537. */
  35538. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35539. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35540. };
  35541. /**
  35542. * Indicates that textures need to be re-calculated for all submeshes
  35543. */
  35544. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35545. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35546. };
  35547. /**
  35548. * Indicates that fresnel needs to be re-calculated for all submeshes
  35549. */
  35550. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35551. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35552. };
  35553. /**
  35554. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35555. */
  35556. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35557. this._markAllSubMeshesAsDirty(function (defines) {
  35558. defines.markAsFresnelDirty();
  35559. defines.markAsMiscDirty();
  35560. });
  35561. };
  35562. /**
  35563. * Indicates that lights need to be re-calculated for all submeshes
  35564. */
  35565. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35566. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35567. };
  35568. /**
  35569. * Indicates that attributes need to be re-calculated for all submeshes
  35570. */
  35571. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35573. };
  35574. /**
  35575. * Indicates that misc needs to be re-calculated for all submeshes
  35576. */
  35577. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35578. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35579. };
  35580. /**
  35581. * Indicates that textures and misc need to be re-calculated for all submeshes
  35582. */
  35583. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35584. this._markAllSubMeshesAsDirty(function (defines) {
  35585. defines.markAsTexturesDirty();
  35586. defines.markAsMiscDirty();
  35587. });
  35588. };
  35589. /**
  35590. * Disposes the material
  35591. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35592. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35593. */
  35594. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35595. // Animations
  35596. this.getScene().stopAnimation(this);
  35597. this.getScene().freeProcessedMaterials();
  35598. // Remove from scene
  35599. var index = this._scene.materials.indexOf(this);
  35600. if (index >= 0) {
  35601. this._scene.materials.splice(index, 1);
  35602. }
  35603. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  35604. // Remove from meshes
  35605. for (index = 0; index < this._scene.meshes.length; index++) {
  35606. var mesh = this._scene.meshes[index];
  35607. if (mesh.material === this) {
  35608. mesh.material = null;
  35609. if (mesh.geometry) {
  35610. var geometry = (mesh.geometry);
  35611. if (this.storeEffectOnSubMeshes) {
  35612. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35613. var subMesh = _a[_i];
  35614. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35615. if (forceDisposeEffect && subMesh._materialEffect) {
  35616. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35617. }
  35618. }
  35619. }
  35620. else {
  35621. geometry._releaseVertexArrayObject(this._effect);
  35622. }
  35623. }
  35624. }
  35625. }
  35626. this._uniformBuffer.dispose();
  35627. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35628. if (forceDisposeEffect && this._effect) {
  35629. if (!this.storeEffectOnSubMeshes) {
  35630. this._scene.getEngine()._releaseEffect(this._effect);
  35631. }
  35632. this._effect = null;
  35633. }
  35634. // Callback
  35635. this.onDisposeObservable.notifyObservers(this);
  35636. this.onDisposeObservable.clear();
  35637. if (this._onBindObservable) {
  35638. this._onBindObservable.clear();
  35639. }
  35640. if (this._onUnBindObservable) {
  35641. this._onUnBindObservable.clear();
  35642. }
  35643. };
  35644. /**
  35645. * Serializes this material
  35646. * @returns the serialized material object
  35647. */
  35648. Material.prototype.serialize = function () {
  35649. return BABYLON.SerializationHelper.Serialize(this);
  35650. };
  35651. /**
  35652. * Creates a MultiMaterial from parsed MultiMaterial data.
  35653. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35654. * @param scene defines the hosting scene
  35655. * @returns a new MultiMaterial
  35656. */
  35657. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35658. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35659. multiMaterial.id = parsedMultiMaterial.id;
  35660. if (BABYLON.Tags) {
  35661. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35662. }
  35663. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35664. var subMatId = parsedMultiMaterial.materials[matIndex];
  35665. if (subMatId) {
  35666. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35667. }
  35668. else {
  35669. multiMaterial.subMaterials.push(null);
  35670. }
  35671. }
  35672. return multiMaterial;
  35673. };
  35674. /**
  35675. * Creates a material from parsed material data
  35676. * @param parsedMaterial defines parsed material data
  35677. * @param scene defines the hosting scene
  35678. * @param rootUrl defines the root URL to use to load textures
  35679. * @returns a new material
  35680. */
  35681. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35682. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35683. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35684. }
  35685. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35686. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35687. if (!BABYLON.LegacyPBRMaterial) {
  35688. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35689. return;
  35690. }
  35691. }
  35692. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35693. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35694. };
  35695. // Triangle views
  35696. Material._TriangleFillMode = 0;
  35697. Material._WireFrameFillMode = 1;
  35698. Material._PointFillMode = 2;
  35699. // Draw modes
  35700. Material._PointListDrawMode = 3;
  35701. Material._LineListDrawMode = 4;
  35702. Material._LineLoopDrawMode = 5;
  35703. Material._LineStripDrawMode = 6;
  35704. Material._TriangleStripDrawMode = 7;
  35705. Material._TriangleFanDrawMode = 8;
  35706. /**
  35707. * Stores the clock-wise side orientation
  35708. */
  35709. Material._ClockWiseSideOrientation = 0;
  35710. /**
  35711. * Stores the counter clock-wise side orientation
  35712. */
  35713. Material._CounterClockWiseSideOrientation = 1;
  35714. /**
  35715. * The dirty texture flag value
  35716. */
  35717. Material.TextureDirtyFlag = 1;
  35718. /**
  35719. * The dirty light flag value
  35720. */
  35721. Material.LightDirtyFlag = 2;
  35722. /**
  35723. * The dirty fresnel flag value
  35724. */
  35725. Material.FresnelDirtyFlag = 4;
  35726. /**
  35727. * The dirty attribute flag value
  35728. */
  35729. Material.AttributesDirtyFlag = 8;
  35730. /**
  35731. * The dirty misc flag value
  35732. */
  35733. Material.MiscDirtyFlag = 16;
  35734. /**
  35735. * The all dirty flag value
  35736. */
  35737. Material.AllDirtyFlag = 31;
  35738. __decorate([
  35739. BABYLON.serialize()
  35740. ], Material.prototype, "id", void 0);
  35741. __decorate([
  35742. BABYLON.serialize()
  35743. ], Material.prototype, "uniqueId", void 0);
  35744. __decorate([
  35745. BABYLON.serialize()
  35746. ], Material.prototype, "name", void 0);
  35747. __decorate([
  35748. BABYLON.serialize()
  35749. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35750. __decorate([
  35751. BABYLON.serialize()
  35752. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35753. __decorate([
  35754. BABYLON.serialize()
  35755. ], Material.prototype, "state", void 0);
  35756. __decorate([
  35757. BABYLON.serialize("alpha")
  35758. ], Material.prototype, "_alpha", void 0);
  35759. __decorate([
  35760. BABYLON.serialize("backFaceCulling")
  35761. ], Material.prototype, "_backFaceCulling", void 0);
  35762. __decorate([
  35763. BABYLON.serialize()
  35764. ], Material.prototype, "sideOrientation", void 0);
  35765. __decorate([
  35766. BABYLON.serialize("alphaMode")
  35767. ], Material.prototype, "_alphaMode", void 0);
  35768. __decorate([
  35769. BABYLON.serialize()
  35770. ], Material.prototype, "_needDepthPrePass", void 0);
  35771. __decorate([
  35772. BABYLON.serialize()
  35773. ], Material.prototype, "disableDepthWrite", void 0);
  35774. __decorate([
  35775. BABYLON.serialize()
  35776. ], Material.prototype, "forceDepthWrite", void 0);
  35777. __decorate([
  35778. BABYLON.serialize()
  35779. ], Material.prototype, "separateCullingPass", void 0);
  35780. __decorate([
  35781. BABYLON.serialize("fogEnabled")
  35782. ], Material.prototype, "_fogEnabled", void 0);
  35783. __decorate([
  35784. BABYLON.serialize()
  35785. ], Material.prototype, "pointSize", void 0);
  35786. __decorate([
  35787. BABYLON.serialize()
  35788. ], Material.prototype, "zOffset", void 0);
  35789. __decorate([
  35790. BABYLON.serialize()
  35791. ], Material.prototype, "wireframe", null);
  35792. __decorate([
  35793. BABYLON.serialize()
  35794. ], Material.prototype, "pointsCloud", null);
  35795. __decorate([
  35796. BABYLON.serialize()
  35797. ], Material.prototype, "fillMode", null);
  35798. return Material;
  35799. }());
  35800. BABYLON.Material = Material;
  35801. })(BABYLON || (BABYLON = {}));
  35802. //# sourceMappingURL=babylon.material.js.map
  35803. var BABYLON;
  35804. (function (BABYLON) {
  35805. var UniformBuffer = /** @class */ (function () {
  35806. /**
  35807. * Uniform buffer objects.
  35808. *
  35809. * Handles blocks of uniform on the GPU.
  35810. *
  35811. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35812. *
  35813. * For more information, please refer to :
  35814. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35815. */
  35816. function UniformBuffer(engine, data, dynamic) {
  35817. this._engine = engine;
  35818. this._noUBO = !engine.supportsUniformBuffers;
  35819. this._dynamic = dynamic;
  35820. this._data = data || [];
  35821. this._uniformLocations = {};
  35822. this._uniformSizes = {};
  35823. this._uniformLocationPointer = 0;
  35824. this._needSync = false;
  35825. if (this._noUBO) {
  35826. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35827. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35828. this.updateFloat = this._updateFloatForEffect;
  35829. this.updateFloat2 = this._updateFloat2ForEffect;
  35830. this.updateFloat3 = this._updateFloat3ForEffect;
  35831. this.updateFloat4 = this._updateFloat4ForEffect;
  35832. this.updateMatrix = this._updateMatrixForEffect;
  35833. this.updateVector3 = this._updateVector3ForEffect;
  35834. this.updateVector4 = this._updateVector4ForEffect;
  35835. this.updateColor3 = this._updateColor3ForEffect;
  35836. this.updateColor4 = this._updateColor4ForEffect;
  35837. }
  35838. else {
  35839. this._engine._uniformBuffers.push(this);
  35840. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35841. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35842. this.updateFloat = this._updateFloatForUniform;
  35843. this.updateFloat2 = this._updateFloat2ForUniform;
  35844. this.updateFloat3 = this._updateFloat3ForUniform;
  35845. this.updateFloat4 = this._updateFloat4ForUniform;
  35846. this.updateMatrix = this._updateMatrixForUniform;
  35847. this.updateVector3 = this._updateVector3ForUniform;
  35848. this.updateVector4 = this._updateVector4ForUniform;
  35849. this.updateColor3 = this._updateColor3ForUniform;
  35850. this.updateColor4 = this._updateColor4ForUniform;
  35851. }
  35852. }
  35853. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35854. // Properties
  35855. /**
  35856. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35857. * or just falling back on setUniformXXX calls.
  35858. */
  35859. get: function () {
  35860. return !this._noUBO;
  35861. },
  35862. enumerable: true,
  35863. configurable: true
  35864. });
  35865. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35866. /**
  35867. * Indicates if the WebGL underlying uniform buffer is in sync
  35868. * with the javascript cache data.
  35869. */
  35870. get: function () {
  35871. return !this._needSync;
  35872. },
  35873. enumerable: true,
  35874. configurable: true
  35875. });
  35876. /**
  35877. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35878. * Also, a dynamic UniformBuffer will disable cache verification and always
  35879. * update the underlying WebGL uniform buffer to the GPU.
  35880. */
  35881. UniformBuffer.prototype.isDynamic = function () {
  35882. return this._dynamic !== undefined;
  35883. };
  35884. /**
  35885. * The data cache on JS side.
  35886. */
  35887. UniformBuffer.prototype.getData = function () {
  35888. return this._bufferData;
  35889. };
  35890. /**
  35891. * The underlying WebGL Uniform buffer.
  35892. */
  35893. UniformBuffer.prototype.getBuffer = function () {
  35894. return this._buffer;
  35895. };
  35896. /**
  35897. * std140 layout specifies how to align data within an UBO structure.
  35898. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35899. * for specs.
  35900. */
  35901. UniformBuffer.prototype._fillAlignment = function (size) {
  35902. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35903. // and 4x4 matrices
  35904. // TODO : change if other types are used
  35905. var alignment;
  35906. if (size <= 2) {
  35907. alignment = size;
  35908. }
  35909. else {
  35910. alignment = 4;
  35911. }
  35912. if ((this._uniformLocationPointer % alignment) !== 0) {
  35913. var oldPointer = this._uniformLocationPointer;
  35914. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35915. var diff = this._uniformLocationPointer - oldPointer;
  35916. for (var i = 0; i < diff; i++) {
  35917. this._data.push(0);
  35918. }
  35919. }
  35920. };
  35921. /**
  35922. * Adds an uniform in the buffer.
  35923. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35924. * for the layout to be correct !
  35925. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35926. * @param {number|number[]} size Data size, or data directly.
  35927. */
  35928. UniformBuffer.prototype.addUniform = function (name, size) {
  35929. if (this._noUBO) {
  35930. return;
  35931. }
  35932. if (this._uniformLocations[name] !== undefined) {
  35933. // Already existing uniform
  35934. return;
  35935. }
  35936. // This function must be called in the order of the shader layout !
  35937. // size can be the size of the uniform, or data directly
  35938. var data;
  35939. if (size instanceof Array) {
  35940. data = size;
  35941. size = data.length;
  35942. }
  35943. else {
  35944. size = size;
  35945. data = [];
  35946. // Fill with zeros
  35947. for (var i = 0; i < size; i++) {
  35948. data.push(0);
  35949. }
  35950. }
  35951. this._fillAlignment(size);
  35952. this._uniformSizes[name] = size;
  35953. this._uniformLocations[name] = this._uniformLocationPointer;
  35954. this._uniformLocationPointer += size;
  35955. for (var i = 0; i < size; i++) {
  35956. this._data.push(data[i]);
  35957. }
  35958. this._needSync = true;
  35959. };
  35960. /**
  35961. * Wrapper for addUniform.
  35962. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35963. * @param {Matrix} mat A 4x4 matrix.
  35964. */
  35965. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35966. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35967. };
  35968. /**
  35969. * Wrapper for addUniform.
  35970. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35971. * @param {number} x
  35972. * @param {number} y
  35973. */
  35974. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35975. var temp = [x, y];
  35976. this.addUniform(name, temp);
  35977. };
  35978. /**
  35979. * Wrapper for addUniform.
  35980. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35981. * @param {number} x
  35982. * @param {number} y
  35983. * @param {number} z
  35984. */
  35985. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35986. var temp = [x, y, z];
  35987. this.addUniform(name, temp);
  35988. };
  35989. /**
  35990. * Wrapper for addUniform.
  35991. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35992. * @param {Color3} color
  35993. */
  35994. UniformBuffer.prototype.addColor3 = function (name, color) {
  35995. var temp = new Array();
  35996. color.toArray(temp);
  35997. this.addUniform(name, temp);
  35998. };
  35999. /**
  36000. * Wrapper for addUniform.
  36001. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36002. * @param {Color3} color
  36003. * @param {number} alpha
  36004. */
  36005. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36006. var temp = new Array();
  36007. color.toArray(temp);
  36008. temp.push(alpha);
  36009. this.addUniform(name, temp);
  36010. };
  36011. /**
  36012. * Wrapper for addUniform.
  36013. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36014. * @param {Vector3} vector
  36015. */
  36016. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36017. var temp = new Array();
  36018. vector.toArray(temp);
  36019. this.addUniform(name, temp);
  36020. };
  36021. /**
  36022. * Wrapper for addUniform.
  36023. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36024. */
  36025. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36026. this.addUniform(name, 12);
  36027. };
  36028. /**
  36029. * Wrapper for addUniform.
  36030. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36031. */
  36032. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36033. this.addUniform(name, 8);
  36034. };
  36035. /**
  36036. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36037. */
  36038. UniformBuffer.prototype.create = function () {
  36039. if (this._noUBO) {
  36040. return;
  36041. }
  36042. if (this._buffer) {
  36043. return; // nothing to do
  36044. }
  36045. // See spec, alignment must be filled as a vec4
  36046. this._fillAlignment(4);
  36047. this._bufferData = new Float32Array(this._data);
  36048. this._rebuild();
  36049. this._needSync = true;
  36050. };
  36051. /** @hidden */
  36052. UniformBuffer.prototype._rebuild = function () {
  36053. if (this._noUBO) {
  36054. return;
  36055. }
  36056. if (this._dynamic) {
  36057. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36058. }
  36059. else {
  36060. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36061. }
  36062. };
  36063. /**
  36064. * Updates the WebGL Uniform Buffer on the GPU.
  36065. * If the `dynamic` flag is set to true, no cache comparison is done.
  36066. * Otherwise, the buffer will be updated only if the cache differs.
  36067. */
  36068. UniformBuffer.prototype.update = function () {
  36069. if (!this._buffer) {
  36070. this.create();
  36071. return;
  36072. }
  36073. if (!this._dynamic && !this._needSync) {
  36074. return;
  36075. }
  36076. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36077. this._needSync = false;
  36078. };
  36079. /**
  36080. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36081. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36082. * @param {number[]|Float32Array} data Flattened data
  36083. * @param {number} size Size of the data.
  36084. */
  36085. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36086. var location = this._uniformLocations[uniformName];
  36087. if (location === undefined) {
  36088. if (this._buffer) {
  36089. // Cannot add an uniform if the buffer is already created
  36090. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36091. return;
  36092. }
  36093. this.addUniform(uniformName, size);
  36094. location = this._uniformLocations[uniformName];
  36095. }
  36096. if (!this._buffer) {
  36097. this.create();
  36098. }
  36099. if (!this._dynamic) {
  36100. // Cache for static uniform buffers
  36101. var changed = false;
  36102. for (var i = 0; i < size; i++) {
  36103. if (this._bufferData[location + i] !== data[i]) {
  36104. changed = true;
  36105. this._bufferData[location + i] = data[i];
  36106. }
  36107. }
  36108. this._needSync = this._needSync || changed;
  36109. }
  36110. else {
  36111. // No cache for dynamic
  36112. for (var i = 0; i < size; i++) {
  36113. this._bufferData[location + i] = data[i];
  36114. }
  36115. }
  36116. };
  36117. // Update methods
  36118. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36119. // To match std140, matrix must be realigned
  36120. for (var i = 0; i < 3; i++) {
  36121. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36122. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36123. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36124. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36125. }
  36126. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36127. };
  36128. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36129. this._currentEffect.setMatrix3x3(name, matrix);
  36130. };
  36131. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36132. this._currentEffect.setMatrix2x2(name, matrix);
  36133. };
  36134. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36135. // To match std140, matrix must be realigned
  36136. for (var i = 0; i < 2; i++) {
  36137. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36138. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36139. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36140. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36141. }
  36142. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36143. };
  36144. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36145. this._currentEffect.setFloat(name, x);
  36146. };
  36147. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36148. UniformBuffer._tempBuffer[0] = x;
  36149. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36150. };
  36151. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36152. if (suffix === void 0) { suffix = ""; }
  36153. this._currentEffect.setFloat2(name + suffix, x, y);
  36154. };
  36155. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36156. if (suffix === void 0) { suffix = ""; }
  36157. UniformBuffer._tempBuffer[0] = x;
  36158. UniformBuffer._tempBuffer[1] = y;
  36159. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36160. };
  36161. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36162. if (suffix === void 0) { suffix = ""; }
  36163. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36164. };
  36165. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36166. if (suffix === void 0) { suffix = ""; }
  36167. UniformBuffer._tempBuffer[0] = x;
  36168. UniformBuffer._tempBuffer[1] = y;
  36169. UniformBuffer._tempBuffer[2] = z;
  36170. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36171. };
  36172. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36173. if (suffix === void 0) { suffix = ""; }
  36174. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36175. };
  36176. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36177. if (suffix === void 0) { suffix = ""; }
  36178. UniformBuffer._tempBuffer[0] = x;
  36179. UniformBuffer._tempBuffer[1] = y;
  36180. UniformBuffer._tempBuffer[2] = z;
  36181. UniformBuffer._tempBuffer[3] = w;
  36182. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36183. };
  36184. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36185. this._currentEffect.setMatrix(name, mat);
  36186. };
  36187. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36188. this.updateUniform(name, mat.toArray(), 16);
  36189. };
  36190. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36191. this._currentEffect.setVector3(name, vector);
  36192. };
  36193. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36194. vector.toArray(UniformBuffer._tempBuffer);
  36195. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36196. };
  36197. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36198. this._currentEffect.setVector4(name, vector);
  36199. };
  36200. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36201. vector.toArray(UniformBuffer._tempBuffer);
  36202. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36203. };
  36204. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36205. if (suffix === void 0) { suffix = ""; }
  36206. this._currentEffect.setColor3(name + suffix, color);
  36207. };
  36208. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36209. if (suffix === void 0) { suffix = ""; }
  36210. color.toArray(UniformBuffer._tempBuffer);
  36211. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36212. };
  36213. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36214. if (suffix === void 0) { suffix = ""; }
  36215. this._currentEffect.setColor4(name + suffix, color, alpha);
  36216. };
  36217. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36218. if (suffix === void 0) { suffix = ""; }
  36219. color.toArray(UniformBuffer._tempBuffer);
  36220. UniformBuffer._tempBuffer[3] = alpha;
  36221. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36222. };
  36223. /**
  36224. * Sets a sampler uniform on the effect.
  36225. * @param {string} name Name of the sampler.
  36226. * @param {Texture} texture
  36227. */
  36228. UniformBuffer.prototype.setTexture = function (name, texture) {
  36229. this._currentEffect.setTexture(name, texture);
  36230. };
  36231. /**
  36232. * Directly updates the value of the uniform in the cache AND on the GPU.
  36233. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36234. * @param {number[]|Float32Array} data Flattened data
  36235. */
  36236. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36237. this.updateUniform(uniformName, data, data.length);
  36238. this.update();
  36239. };
  36240. /**
  36241. * Binds this uniform buffer to an effect.
  36242. * @param {Effect} effect
  36243. * @param {string} name Name of the uniform block in the shader.
  36244. */
  36245. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36246. this._currentEffect = effect;
  36247. if (this._noUBO || !this._buffer) {
  36248. return;
  36249. }
  36250. effect.bindUniformBuffer(this._buffer, name);
  36251. };
  36252. /**
  36253. * Disposes the uniform buffer.
  36254. */
  36255. UniformBuffer.prototype.dispose = function () {
  36256. if (this._noUBO) {
  36257. return;
  36258. }
  36259. var index = this._engine._uniformBuffers.indexOf(this);
  36260. if (index !== -1) {
  36261. this._engine._uniformBuffers.splice(index, 1);
  36262. }
  36263. if (!this._buffer) {
  36264. return;
  36265. }
  36266. if (this._engine._releaseBuffer(this._buffer)) {
  36267. this._buffer = null;
  36268. }
  36269. };
  36270. // Pool for avoiding memory leaks
  36271. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36272. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36273. return UniformBuffer;
  36274. }());
  36275. BABYLON.UniformBuffer = UniformBuffer;
  36276. })(BABYLON || (BABYLON = {}));
  36277. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36278. var BABYLON;
  36279. (function (BABYLON) {
  36280. /**
  36281. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36282. */
  36283. var VertexData = /** @class */ (function () {
  36284. function VertexData() {
  36285. }
  36286. /**
  36287. * Uses the passed data array to set the set the values for the specified kind of data
  36288. * @param data a linear array of floating numbers
  36289. * @param kind the type of data that is being set, eg positions, colors etc
  36290. */
  36291. VertexData.prototype.set = function (data, kind) {
  36292. switch (kind) {
  36293. case BABYLON.VertexBuffer.PositionKind:
  36294. this.positions = data;
  36295. break;
  36296. case BABYLON.VertexBuffer.NormalKind:
  36297. this.normals = data;
  36298. break;
  36299. case BABYLON.VertexBuffer.TangentKind:
  36300. this.tangents = data;
  36301. break;
  36302. case BABYLON.VertexBuffer.UVKind:
  36303. this.uvs = data;
  36304. break;
  36305. case BABYLON.VertexBuffer.UV2Kind:
  36306. this.uvs2 = data;
  36307. break;
  36308. case BABYLON.VertexBuffer.UV3Kind:
  36309. this.uvs3 = data;
  36310. break;
  36311. case BABYLON.VertexBuffer.UV4Kind:
  36312. this.uvs4 = data;
  36313. break;
  36314. case BABYLON.VertexBuffer.UV5Kind:
  36315. this.uvs5 = data;
  36316. break;
  36317. case BABYLON.VertexBuffer.UV6Kind:
  36318. this.uvs6 = data;
  36319. break;
  36320. case BABYLON.VertexBuffer.ColorKind:
  36321. this.colors = data;
  36322. break;
  36323. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36324. this.matricesIndices = data;
  36325. break;
  36326. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36327. this.matricesWeights = data;
  36328. break;
  36329. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36330. this.matricesIndicesExtra = data;
  36331. break;
  36332. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36333. this.matricesWeightsExtra = data;
  36334. break;
  36335. }
  36336. };
  36337. /**
  36338. * Associates the vertexData to the passed Mesh.
  36339. * Sets it as updatable or not (default `false`)
  36340. * @param mesh the mesh the vertexData is applied to
  36341. * @param updatable when used and having the value true allows new data to update the vertexData
  36342. * @returns the VertexData
  36343. */
  36344. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36345. this._applyTo(mesh, updatable);
  36346. return this;
  36347. };
  36348. /**
  36349. * Associates the vertexData to the passed Geometry.
  36350. * Sets it as updatable or not (default `false`)
  36351. * @param geometry the geometry the vertexData is applied to
  36352. * @param updatable when used and having the value true allows new data to update the vertexData
  36353. * @returns VertexData
  36354. */
  36355. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36356. this._applyTo(geometry, updatable);
  36357. return this;
  36358. };
  36359. /**
  36360. * Updates the associated mesh
  36361. * @param mesh the mesh to be updated
  36362. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36363. * @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
  36364. * @returns VertexData
  36365. */
  36366. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36367. this._update(mesh);
  36368. return this;
  36369. };
  36370. /**
  36371. * Updates the associated geometry
  36372. * @param geometry the geometry to be updated
  36373. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36374. * @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
  36375. * @returns VertexData.
  36376. */
  36377. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36378. this._update(geometry);
  36379. return this;
  36380. };
  36381. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36382. if (updatable === void 0) { updatable = false; }
  36383. if (this.positions) {
  36384. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36385. }
  36386. if (this.normals) {
  36387. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36388. }
  36389. if (this.tangents) {
  36390. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36391. }
  36392. if (this.uvs) {
  36393. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36394. }
  36395. if (this.uvs2) {
  36396. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36397. }
  36398. if (this.uvs3) {
  36399. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36400. }
  36401. if (this.uvs4) {
  36402. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36403. }
  36404. if (this.uvs5) {
  36405. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36406. }
  36407. if (this.uvs6) {
  36408. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36409. }
  36410. if (this.colors) {
  36411. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36412. }
  36413. if (this.matricesIndices) {
  36414. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36415. }
  36416. if (this.matricesWeights) {
  36417. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36418. }
  36419. if (this.matricesIndicesExtra) {
  36420. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36421. }
  36422. if (this.matricesWeightsExtra) {
  36423. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36424. }
  36425. if (this.indices) {
  36426. meshOrGeometry.setIndices(this.indices, null, updatable);
  36427. }
  36428. else {
  36429. meshOrGeometry.setIndices([], null);
  36430. }
  36431. return this;
  36432. };
  36433. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36434. if (this.positions) {
  36435. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36436. }
  36437. if (this.normals) {
  36438. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36439. }
  36440. if (this.tangents) {
  36441. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36442. }
  36443. if (this.uvs) {
  36444. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36445. }
  36446. if (this.uvs2) {
  36447. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36448. }
  36449. if (this.uvs3) {
  36450. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36451. }
  36452. if (this.uvs4) {
  36453. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36454. }
  36455. if (this.uvs5) {
  36456. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36457. }
  36458. if (this.uvs6) {
  36459. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36460. }
  36461. if (this.colors) {
  36462. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36463. }
  36464. if (this.matricesIndices) {
  36465. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36466. }
  36467. if (this.matricesWeights) {
  36468. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36469. }
  36470. if (this.matricesIndicesExtra) {
  36471. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36472. }
  36473. if (this.matricesWeightsExtra) {
  36474. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36475. }
  36476. if (this.indices) {
  36477. meshOrGeometry.setIndices(this.indices, null);
  36478. }
  36479. return this;
  36480. };
  36481. /**
  36482. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36483. * @param matrix the transforming matrix
  36484. * @returns the VertexData
  36485. */
  36486. VertexData.prototype.transform = function (matrix) {
  36487. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36488. var transformed = BABYLON.Vector3.Zero();
  36489. var index;
  36490. if (this.positions) {
  36491. var position = BABYLON.Vector3.Zero();
  36492. for (index = 0; index < this.positions.length; index += 3) {
  36493. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36494. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36495. this.positions[index] = transformed.x;
  36496. this.positions[index + 1] = transformed.y;
  36497. this.positions[index + 2] = transformed.z;
  36498. }
  36499. }
  36500. if (this.normals) {
  36501. var normal = BABYLON.Vector3.Zero();
  36502. for (index = 0; index < this.normals.length; index += 3) {
  36503. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36504. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36505. this.normals[index] = transformed.x;
  36506. this.normals[index + 1] = transformed.y;
  36507. this.normals[index + 2] = transformed.z;
  36508. }
  36509. }
  36510. if (this.tangents) {
  36511. var tangent = BABYLON.Vector4.Zero();
  36512. var tangentTransformed = BABYLON.Vector4.Zero();
  36513. for (index = 0; index < this.tangents.length; index += 4) {
  36514. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36515. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36516. this.tangents[index] = tangentTransformed.x;
  36517. this.tangents[index + 1] = tangentTransformed.y;
  36518. this.tangents[index + 2] = tangentTransformed.z;
  36519. this.tangents[index + 3] = tangentTransformed.w;
  36520. }
  36521. }
  36522. if (flip && this.indices) {
  36523. for (index = 0; index < this.indices.length; index += 3) {
  36524. var tmp = this.indices[index + 1];
  36525. this.indices[index + 1] = this.indices[index + 2];
  36526. this.indices[index + 2] = tmp;
  36527. }
  36528. }
  36529. return this;
  36530. };
  36531. /**
  36532. * Merges the passed VertexData into the current one
  36533. * @param other the VertexData to be merged into the current one
  36534. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36535. * @returns the modified VertexData
  36536. */
  36537. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36538. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36539. this._validate();
  36540. other._validate();
  36541. if (!this.normals !== !other.normals ||
  36542. !this.tangents !== !other.tangents ||
  36543. !this.uvs !== !other.uvs ||
  36544. !this.uvs2 !== !other.uvs2 ||
  36545. !this.uvs3 !== !other.uvs3 ||
  36546. !this.uvs4 !== !other.uvs4 ||
  36547. !this.uvs5 !== !other.uvs5 ||
  36548. !this.uvs6 !== !other.uvs6 ||
  36549. !this.colors !== !other.colors ||
  36550. !this.matricesIndices !== !other.matricesIndices ||
  36551. !this.matricesWeights !== !other.matricesWeights ||
  36552. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36553. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36554. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36555. }
  36556. if (other.indices) {
  36557. if (!this.indices) {
  36558. this.indices = [];
  36559. }
  36560. var offset = this.positions ? this.positions.length / 3 : 0;
  36561. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36562. if (isSrcTypedArray) {
  36563. var len = this.indices.length + other.indices.length;
  36564. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36565. temp.set(this.indices);
  36566. var decal = this.indices.length;
  36567. for (var index = 0; index < other.indices.length; index++) {
  36568. temp[decal + index] = other.indices[index] + offset;
  36569. }
  36570. this.indices = temp;
  36571. }
  36572. else {
  36573. for (var index = 0; index < other.indices.length; index++) {
  36574. this.indices.push(other.indices[index] + offset);
  36575. }
  36576. }
  36577. }
  36578. this.positions = this._mergeElement(this.positions, other.positions);
  36579. this.normals = this._mergeElement(this.normals, other.normals);
  36580. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36581. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36582. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36583. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36584. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36585. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36586. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36587. this.colors = this._mergeElement(this.colors, other.colors);
  36588. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36589. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36590. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36591. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36592. return this;
  36593. };
  36594. VertexData.prototype._mergeElement = function (source, other) {
  36595. if (!source) {
  36596. return other;
  36597. }
  36598. if (!other) {
  36599. return source;
  36600. }
  36601. var len = other.length + source.length;
  36602. var isSrcTypedArray = source instanceof Float32Array;
  36603. var isOthTypedArray = other instanceof Float32Array;
  36604. // use non-loop method when the source is Float32Array
  36605. if (isSrcTypedArray) {
  36606. var ret32 = new Float32Array(len);
  36607. ret32.set(source);
  36608. ret32.set(other, source.length);
  36609. return ret32;
  36610. // source is number[], when other is also use concat
  36611. }
  36612. else if (!isOthTypedArray) {
  36613. return source.concat(other);
  36614. // source is a number[], but other is a Float32Array, loop required
  36615. }
  36616. else {
  36617. var ret = source.slice(0); // copy source to a separate array
  36618. for (var i = 0, len = other.length; i < len; i++) {
  36619. ret.push(other[i]);
  36620. }
  36621. return ret;
  36622. }
  36623. };
  36624. VertexData.prototype._validate = function () {
  36625. if (!this.positions) {
  36626. throw new Error("Positions are required");
  36627. }
  36628. var getElementCount = function (kind, values) {
  36629. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36630. if ((values.length % stride) !== 0) {
  36631. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36632. }
  36633. return values.length / stride;
  36634. };
  36635. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36636. var validateElementCount = function (kind, values) {
  36637. var elementCount = getElementCount(kind, values);
  36638. if (elementCount !== positionsElementCount) {
  36639. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36640. }
  36641. };
  36642. if (this.normals)
  36643. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36644. if (this.tangents)
  36645. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36646. if (this.uvs)
  36647. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36648. if (this.uvs2)
  36649. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36650. if (this.uvs3)
  36651. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36652. if (this.uvs4)
  36653. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36654. if (this.uvs5)
  36655. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36656. if (this.uvs6)
  36657. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36658. if (this.colors)
  36659. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36660. if (this.matricesIndices)
  36661. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36662. if (this.matricesWeights)
  36663. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36664. if (this.matricesIndicesExtra)
  36665. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36666. if (this.matricesWeightsExtra)
  36667. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36668. };
  36669. /**
  36670. * Serializes the VertexData
  36671. * @returns a serialized object
  36672. */
  36673. VertexData.prototype.serialize = function () {
  36674. var serializationObject = this.serialize();
  36675. if (this.positions) {
  36676. serializationObject.positions = this.positions;
  36677. }
  36678. if (this.normals) {
  36679. serializationObject.normals = this.normals;
  36680. }
  36681. if (this.tangents) {
  36682. serializationObject.tangents = this.tangents;
  36683. }
  36684. if (this.uvs) {
  36685. serializationObject.uvs = this.uvs;
  36686. }
  36687. if (this.uvs2) {
  36688. serializationObject.uvs2 = this.uvs2;
  36689. }
  36690. if (this.uvs3) {
  36691. serializationObject.uvs3 = this.uvs3;
  36692. }
  36693. if (this.uvs4) {
  36694. serializationObject.uvs4 = this.uvs4;
  36695. }
  36696. if (this.uvs5) {
  36697. serializationObject.uvs5 = this.uvs5;
  36698. }
  36699. if (this.uvs6) {
  36700. serializationObject.uvs6 = this.uvs6;
  36701. }
  36702. if (this.colors) {
  36703. serializationObject.colors = this.colors;
  36704. }
  36705. if (this.matricesIndices) {
  36706. serializationObject.matricesIndices = this.matricesIndices;
  36707. serializationObject.matricesIndices._isExpanded = true;
  36708. }
  36709. if (this.matricesWeights) {
  36710. serializationObject.matricesWeights = this.matricesWeights;
  36711. }
  36712. if (this.matricesIndicesExtra) {
  36713. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36714. serializationObject.matricesIndicesExtra._isExpanded = true;
  36715. }
  36716. if (this.matricesWeightsExtra) {
  36717. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36718. }
  36719. serializationObject.indices = this.indices;
  36720. return serializationObject;
  36721. };
  36722. // Statics
  36723. /**
  36724. * Extracts the vertexData from a mesh
  36725. * @param mesh the mesh from which to extract the VertexData
  36726. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36727. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36728. * @returns the object VertexData associated to the passed mesh
  36729. */
  36730. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36731. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36732. };
  36733. /**
  36734. * Extracts the vertexData from the geometry
  36735. * @param geometry the geometry from which to extract the VertexData
  36736. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36737. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36738. * @returns the object VertexData associated to the passed mesh
  36739. */
  36740. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36741. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36742. };
  36743. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36744. var result = new VertexData();
  36745. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36746. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36747. }
  36748. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36749. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36750. }
  36751. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36752. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36753. }
  36754. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36755. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36756. }
  36757. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36758. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36759. }
  36760. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36761. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36762. }
  36763. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36764. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36765. }
  36766. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36767. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36768. }
  36769. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36770. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36771. }
  36772. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36773. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36774. }
  36775. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36776. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36777. }
  36778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36779. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36780. }
  36781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36782. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36783. }
  36784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36785. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36786. }
  36787. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36788. return result;
  36789. };
  36790. /**
  36791. * Creates the VertexData for a Ribbon
  36792. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36793. * * pathArray array of paths, each of which an array of successive Vector3
  36794. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36795. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36796. * * 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
  36797. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36798. * * 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)
  36799. * * 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)
  36800. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36801. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36802. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36803. * @returns the VertexData of the ribbon
  36804. */
  36805. VertexData.CreateRibbon = function (options) {
  36806. var pathArray = options.pathArray;
  36807. var closeArray = options.closeArray || false;
  36808. var closePath = options.closePath || false;
  36809. var invertUV = options.invertUV || false;
  36810. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36811. var offset = options.offset || defaultOffset;
  36812. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36813. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36814. var customUV = options.uvs;
  36815. var customColors = options.colors;
  36816. var positions = [];
  36817. var indices = [];
  36818. var normals = [];
  36819. var uvs = [];
  36820. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36821. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36822. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36823. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36824. var minlg; // minimal length among all paths from pathArray
  36825. var lg = []; // array of path lengths : nb of vertex per path
  36826. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36827. var p; // path iterator
  36828. var i; // point iterator
  36829. var j; // point iterator
  36830. // if single path in pathArray
  36831. if (pathArray.length < 2) {
  36832. var ar1 = [];
  36833. var ar2 = [];
  36834. for (i = 0; i < pathArray[0].length - offset; i++) {
  36835. ar1.push(pathArray[0][i]);
  36836. ar2.push(pathArray[0][i + offset]);
  36837. }
  36838. pathArray = [ar1, ar2];
  36839. }
  36840. // positions and horizontal distances (u)
  36841. var idc = 0;
  36842. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36843. var path;
  36844. var l;
  36845. minlg = pathArray[0].length;
  36846. var vectlg;
  36847. var dist;
  36848. for (p = 0; p < pathArray.length; p++) {
  36849. uTotalDistance[p] = 0;
  36850. us[p] = [0];
  36851. path = pathArray[p];
  36852. l = path.length;
  36853. minlg = (minlg < l) ? minlg : l;
  36854. j = 0;
  36855. while (j < l) {
  36856. positions.push(path[j].x, path[j].y, path[j].z);
  36857. if (j > 0) {
  36858. vectlg = path[j].subtract(path[j - 1]).length();
  36859. dist = vectlg + uTotalDistance[p];
  36860. us[p].push(dist);
  36861. uTotalDistance[p] = dist;
  36862. }
  36863. j++;
  36864. }
  36865. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36866. j--;
  36867. positions.push(path[0].x, path[0].y, path[0].z);
  36868. vectlg = path[j].subtract(path[0]).length();
  36869. dist = vectlg + uTotalDistance[p];
  36870. us[p].push(dist);
  36871. uTotalDistance[p] = dist;
  36872. }
  36873. lg[p] = l + closePathCorr;
  36874. idx[p] = idc;
  36875. idc += (l + closePathCorr);
  36876. }
  36877. // vertical distances (v)
  36878. var path1;
  36879. var path2;
  36880. var vertex1 = null;
  36881. var vertex2 = null;
  36882. for (i = 0; i < minlg + closePathCorr; i++) {
  36883. vTotalDistance[i] = 0;
  36884. vs[i] = [0];
  36885. for (p = 0; p < pathArray.length - 1; p++) {
  36886. path1 = pathArray[p];
  36887. path2 = pathArray[p + 1];
  36888. if (i === minlg) { // closePath
  36889. vertex1 = path1[0];
  36890. vertex2 = path2[0];
  36891. }
  36892. else {
  36893. vertex1 = path1[i];
  36894. vertex2 = path2[i];
  36895. }
  36896. vectlg = vertex2.subtract(vertex1).length();
  36897. dist = vectlg + vTotalDistance[i];
  36898. vs[i].push(dist);
  36899. vTotalDistance[i] = dist;
  36900. }
  36901. if (closeArray && vertex2 && vertex1) {
  36902. path1 = pathArray[p];
  36903. path2 = pathArray[0];
  36904. if (i === minlg) { // closePath
  36905. vertex2 = path2[0];
  36906. }
  36907. vectlg = vertex2.subtract(vertex1).length();
  36908. dist = vectlg + vTotalDistance[i];
  36909. vTotalDistance[i] = dist;
  36910. }
  36911. }
  36912. // uvs
  36913. var u;
  36914. var v;
  36915. if (customUV) {
  36916. for (p = 0; p < customUV.length; p++) {
  36917. uvs.push(customUV[p].x, customUV[p].y);
  36918. }
  36919. }
  36920. else {
  36921. for (p = 0; p < pathArray.length; p++) {
  36922. for (i = 0; i < minlg + closePathCorr; i++) {
  36923. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36924. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36925. if (invertUV) {
  36926. uvs.push(v, u);
  36927. }
  36928. else {
  36929. uvs.push(u, v);
  36930. }
  36931. }
  36932. }
  36933. }
  36934. // indices
  36935. p = 0; // path index
  36936. var pi = 0; // positions array index
  36937. var l1 = lg[p] - 1; // path1 length
  36938. var l2 = lg[p + 1] - 1; // path2 length
  36939. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36940. var shft = idx[1] - idx[0]; // shift
  36941. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36942. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36943. // 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
  36944. indices.push(pi, pi + shft, pi + 1);
  36945. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36946. pi += 1;
  36947. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36948. p++;
  36949. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36950. shft = idx[0] - idx[p];
  36951. l1 = lg[p] - 1;
  36952. l2 = lg[0] - 1;
  36953. }
  36954. else {
  36955. shft = idx[p + 1] - idx[p];
  36956. l1 = lg[p] - 1;
  36957. l2 = lg[p + 1] - 1;
  36958. }
  36959. pi = idx[p];
  36960. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36961. }
  36962. }
  36963. // normals
  36964. VertexData.ComputeNormals(positions, indices, normals);
  36965. if (closePath) { // update both the first and last vertex normals to their average value
  36966. var indexFirst = 0;
  36967. var indexLast = 0;
  36968. for (p = 0; p < pathArray.length; p++) {
  36969. indexFirst = idx[p] * 3;
  36970. if (p + 1 < pathArray.length) {
  36971. indexLast = (idx[p + 1] - 1) * 3;
  36972. }
  36973. else {
  36974. indexLast = normals.length - 3;
  36975. }
  36976. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36977. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36978. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36979. normals[indexLast] = normals[indexFirst];
  36980. normals[indexLast + 1] = normals[indexFirst + 1];
  36981. normals[indexLast + 2] = normals[indexFirst + 2];
  36982. }
  36983. }
  36984. // sides
  36985. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36986. // Colors
  36987. var colors = null;
  36988. if (customColors) {
  36989. colors = new Float32Array(customColors.length * 4);
  36990. for (var c = 0; c < customColors.length; c++) {
  36991. colors[c * 4] = customColors[c].r;
  36992. colors[c * 4 + 1] = customColors[c].g;
  36993. colors[c * 4 + 2] = customColors[c].b;
  36994. colors[c * 4 + 3] = customColors[c].a;
  36995. }
  36996. }
  36997. // Result
  36998. var vertexData = new VertexData();
  36999. var positions32 = new Float32Array(positions);
  37000. var normals32 = new Float32Array(normals);
  37001. var uvs32 = new Float32Array(uvs);
  37002. vertexData.indices = indices;
  37003. vertexData.positions = positions32;
  37004. vertexData.normals = normals32;
  37005. vertexData.uvs = uvs32;
  37006. if (colors) {
  37007. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37008. }
  37009. if (closePath) {
  37010. vertexData._idx = idx;
  37011. }
  37012. return vertexData;
  37013. };
  37014. /**
  37015. * Creates the VertexData for a box
  37016. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37017. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37018. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37019. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37020. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37021. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37022. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37023. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37024. * * 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)
  37025. * * 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)
  37026. * @returns the VertexData of the box
  37027. */
  37028. VertexData.CreateBox = function (options) {
  37029. var normalsSource = [
  37030. new BABYLON.Vector3(0, 0, 1),
  37031. new BABYLON.Vector3(0, 0, -1),
  37032. new BABYLON.Vector3(1, 0, 0),
  37033. new BABYLON.Vector3(-1, 0, 0),
  37034. new BABYLON.Vector3(0, 1, 0),
  37035. new BABYLON.Vector3(0, -1, 0)
  37036. ];
  37037. var indices = [];
  37038. var positions = [];
  37039. var normals = [];
  37040. var uvs = [];
  37041. var width = options.width || options.size || 1;
  37042. var height = options.height || options.size || 1;
  37043. var depth = options.depth || options.size || 1;
  37044. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37045. var faceUV = options.faceUV || new Array(6);
  37046. var faceColors = options.faceColors;
  37047. var colors = [];
  37048. // default face colors and UV if undefined
  37049. for (var f = 0; f < 6; f++) {
  37050. if (faceUV[f] === undefined) {
  37051. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37052. }
  37053. if (faceColors && faceColors[f] === undefined) {
  37054. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37055. }
  37056. }
  37057. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37058. // Create each face in turn.
  37059. for (var index = 0; index < normalsSource.length; index++) {
  37060. var normal = normalsSource[index];
  37061. // Get two vectors perpendicular to the face normal and to each other.
  37062. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37063. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37064. // Six indices (two triangles) per face.
  37065. var verticesLength = positions.length / 3;
  37066. indices.push(verticesLength);
  37067. indices.push(verticesLength + 1);
  37068. indices.push(verticesLength + 2);
  37069. indices.push(verticesLength);
  37070. indices.push(verticesLength + 2);
  37071. indices.push(verticesLength + 3);
  37072. // Four vertices per face.
  37073. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37074. positions.push(vertex.x, vertex.y, vertex.z);
  37075. normals.push(normal.x, normal.y, normal.z);
  37076. uvs.push(faceUV[index].z, faceUV[index].w);
  37077. if (faceColors) {
  37078. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37079. }
  37080. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37081. positions.push(vertex.x, vertex.y, vertex.z);
  37082. normals.push(normal.x, normal.y, normal.z);
  37083. uvs.push(faceUV[index].x, faceUV[index].w);
  37084. if (faceColors) {
  37085. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37086. }
  37087. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37088. positions.push(vertex.x, vertex.y, vertex.z);
  37089. normals.push(normal.x, normal.y, normal.z);
  37090. uvs.push(faceUV[index].x, faceUV[index].y);
  37091. if (faceColors) {
  37092. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37093. }
  37094. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37095. positions.push(vertex.x, vertex.y, vertex.z);
  37096. normals.push(normal.x, normal.y, normal.z);
  37097. uvs.push(faceUV[index].z, faceUV[index].y);
  37098. if (faceColors) {
  37099. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37100. }
  37101. }
  37102. // sides
  37103. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37104. // Result
  37105. var vertexData = new VertexData();
  37106. vertexData.indices = indices;
  37107. vertexData.positions = positions;
  37108. vertexData.normals = normals;
  37109. vertexData.uvs = uvs;
  37110. if (faceColors) {
  37111. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37112. vertexData.colors = totalColors;
  37113. }
  37114. return vertexData;
  37115. };
  37116. /**
  37117. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37118. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37119. * * segments sets the number of horizontal strips optional, default 32
  37120. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37121. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37122. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37123. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37124. * * 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
  37125. * * 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
  37126. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37127. * * 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)
  37128. * * 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)
  37129. * @returns the VertexData of the ellipsoid
  37130. */
  37131. VertexData.CreateSphere = function (options) {
  37132. var segments = options.segments || 32;
  37133. var diameterX = options.diameterX || options.diameter || 1;
  37134. var diameterY = options.diameterY || options.diameter || 1;
  37135. var diameterZ = options.diameterZ || options.diameter || 1;
  37136. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37137. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37138. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37139. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37140. var totalZRotationSteps = 2 + segments;
  37141. var totalYRotationSteps = 2 * totalZRotationSteps;
  37142. var indices = [];
  37143. var positions = [];
  37144. var normals = [];
  37145. var uvs = [];
  37146. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37147. var normalizedZ = zRotationStep / totalZRotationSteps;
  37148. var angleZ = normalizedZ * Math.PI * slice;
  37149. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37150. var normalizedY = yRotationStep / totalYRotationSteps;
  37151. var angleY = normalizedY * Math.PI * 2 * arc;
  37152. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37153. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37154. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37155. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37156. var vertex = complete.multiply(radius);
  37157. var normal = complete.divide(radius).normalize();
  37158. positions.push(vertex.x, vertex.y, vertex.z);
  37159. normals.push(normal.x, normal.y, normal.z);
  37160. uvs.push(normalizedY, normalizedZ);
  37161. }
  37162. if (zRotationStep > 0) {
  37163. var verticesCount = positions.length / 3;
  37164. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37165. indices.push((firstIndex));
  37166. indices.push((firstIndex + 1));
  37167. indices.push(firstIndex + totalYRotationSteps + 1);
  37168. indices.push((firstIndex + totalYRotationSteps + 1));
  37169. indices.push((firstIndex + 1));
  37170. indices.push((firstIndex + totalYRotationSteps + 2));
  37171. }
  37172. }
  37173. }
  37174. // Sides
  37175. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37176. // Result
  37177. var vertexData = new VertexData();
  37178. vertexData.indices = indices;
  37179. vertexData.positions = positions;
  37180. vertexData.normals = normals;
  37181. vertexData.uvs = uvs;
  37182. return vertexData;
  37183. };
  37184. /**
  37185. * Creates the VertexData for a cylinder, cone or prism
  37186. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37187. * * height sets the height (y direction) of the cylinder, optional, default 2
  37188. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37189. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37190. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37191. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37192. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37193. * * 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
  37194. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37195. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37196. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37197. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37198. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37199. * * 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)
  37200. * * 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)
  37201. * @returns the VertexData of the cylinder, cone or prism
  37202. */
  37203. VertexData.CreateCylinder = function (options) {
  37204. var height = options.height || 2;
  37205. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37206. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37207. var tessellation = options.tessellation || 24;
  37208. var subdivisions = options.subdivisions || 1;
  37209. var hasRings = options.hasRings ? true : false;
  37210. var enclose = options.enclose ? true : false;
  37211. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37212. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37213. var faceUV = options.faceUV || new Array(3);
  37214. var faceColors = options.faceColors;
  37215. // default face colors and UV if undefined
  37216. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37217. var ringNb = (hasRings) ? subdivisions : 1;
  37218. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37219. var f;
  37220. for (f = 0; f < surfaceNb; f++) {
  37221. if (faceColors && faceColors[f] === undefined) {
  37222. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37223. }
  37224. }
  37225. for (f = 0; f < surfaceNb; f++) {
  37226. if (faceUV && faceUV[f] === undefined) {
  37227. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37228. }
  37229. }
  37230. var indices = new Array();
  37231. var positions = new Array();
  37232. var normals = new Array();
  37233. var uvs = new Array();
  37234. var colors = new Array();
  37235. var angle_step = Math.PI * 2 * arc / tessellation;
  37236. var angle;
  37237. var h;
  37238. var radius;
  37239. var tan = (diameterBottom - diameterTop) / 2 / height;
  37240. var ringVertex = BABYLON.Vector3.Zero();
  37241. var ringNormal = BABYLON.Vector3.Zero();
  37242. var ringFirstVertex = BABYLON.Vector3.Zero();
  37243. var ringFirstNormal = BABYLON.Vector3.Zero();
  37244. var quadNormal = BABYLON.Vector3.Zero();
  37245. var Y = BABYLON.Axis.Y;
  37246. // positions, normals, uvs
  37247. var i;
  37248. var j;
  37249. var r;
  37250. var ringIdx = 1;
  37251. var s = 1; // surface index
  37252. var cs = 0;
  37253. var v = 0;
  37254. for (i = 0; i <= subdivisions; i++) {
  37255. h = i / subdivisions;
  37256. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37257. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37258. for (r = 0; r < ringIdx; r++) {
  37259. if (hasRings) {
  37260. s += r;
  37261. }
  37262. if (enclose) {
  37263. s += 2 * r;
  37264. }
  37265. for (j = 0; j <= tessellation; j++) {
  37266. angle = j * angle_step;
  37267. // position
  37268. ringVertex.x = Math.cos(-angle) * radius;
  37269. ringVertex.y = -height / 2 + h * height;
  37270. ringVertex.z = Math.sin(-angle) * radius;
  37271. // normal
  37272. if (diameterTop === 0 && i === subdivisions) {
  37273. // if no top cap, reuse former normals
  37274. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37275. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37276. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37277. }
  37278. else {
  37279. ringNormal.x = ringVertex.x;
  37280. ringNormal.z = ringVertex.z;
  37281. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37282. ringNormal.normalize();
  37283. }
  37284. // keep first ring vertex values for enclose
  37285. if (j === 0) {
  37286. ringFirstVertex.copyFrom(ringVertex);
  37287. ringFirstNormal.copyFrom(ringNormal);
  37288. }
  37289. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37290. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37291. if (hasRings) {
  37292. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37293. }
  37294. else {
  37295. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37296. }
  37297. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37298. if (faceColors) {
  37299. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37300. }
  37301. }
  37302. // if enclose, add four vertices and their dedicated normals
  37303. if (arc !== 1 && enclose) {
  37304. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37305. positions.push(0, ringVertex.y, 0);
  37306. positions.push(0, ringVertex.y, 0);
  37307. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37308. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37309. quadNormal.normalize();
  37310. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37311. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37312. quadNormal.normalize();
  37313. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37314. if (hasRings) {
  37315. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37316. }
  37317. else {
  37318. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37319. }
  37320. uvs.push(faceUV[s + 1].x, v);
  37321. uvs.push(faceUV[s + 1].z, v);
  37322. if (hasRings) {
  37323. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37324. }
  37325. else {
  37326. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37327. }
  37328. uvs.push(faceUV[s + 2].x, v);
  37329. uvs.push(faceUV[s + 2].z, v);
  37330. if (faceColors) {
  37331. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37332. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37333. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37334. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37335. }
  37336. }
  37337. if (cs !== s) {
  37338. cs = s;
  37339. }
  37340. }
  37341. }
  37342. // indices
  37343. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37344. var s;
  37345. i = 0;
  37346. for (s = 0; s < subdivisions; s++) {
  37347. var i0 = 0;
  37348. var i1 = 0;
  37349. var i2 = 0;
  37350. var i3 = 0;
  37351. for (j = 0; j < tessellation; j++) {
  37352. i0 = i * (e + 1) + j;
  37353. i1 = (i + 1) * (e + 1) + j;
  37354. i2 = i * (e + 1) + (j + 1);
  37355. i3 = (i + 1) * (e + 1) + (j + 1);
  37356. indices.push(i0, i1, i2);
  37357. indices.push(i3, i2, i1);
  37358. }
  37359. if (arc !== 1 && enclose) { // if enclose, add two quads
  37360. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37361. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37362. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37363. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37364. }
  37365. i = (hasRings) ? (i + 2) : (i + 1);
  37366. }
  37367. // Caps
  37368. var createCylinderCap = function (isTop) {
  37369. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37370. if (radius === 0) {
  37371. return;
  37372. }
  37373. // Cap positions, normals & uvs
  37374. var angle;
  37375. var circleVector;
  37376. var i;
  37377. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37378. var c = null;
  37379. if (faceColors) {
  37380. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37381. }
  37382. // cap center
  37383. var vbase = positions.length / 3;
  37384. var offset = isTop ? height / 2 : -height / 2;
  37385. var center = new BABYLON.Vector3(0, offset, 0);
  37386. positions.push(center.x, center.y, center.z);
  37387. normals.push(0, isTop ? 1 : -1, 0);
  37388. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37389. if (c) {
  37390. colors.push(c.r, c.g, c.b, c.a);
  37391. }
  37392. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37393. for (i = 0; i <= tessellation; i++) {
  37394. angle = Math.PI * 2 * i * arc / tessellation;
  37395. var cos = Math.cos(-angle);
  37396. var sin = Math.sin(-angle);
  37397. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37398. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37399. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37400. normals.push(0, isTop ? 1 : -1, 0);
  37401. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37402. if (c) {
  37403. colors.push(c.r, c.g, c.b, c.a);
  37404. }
  37405. }
  37406. // Cap indices
  37407. for (i = 0; i < tessellation; i++) {
  37408. if (!isTop) {
  37409. indices.push(vbase);
  37410. indices.push(vbase + (i + 1));
  37411. indices.push(vbase + (i + 2));
  37412. }
  37413. else {
  37414. indices.push(vbase);
  37415. indices.push(vbase + (i + 2));
  37416. indices.push(vbase + (i + 1));
  37417. }
  37418. }
  37419. };
  37420. // add caps to geometry
  37421. createCylinderCap(false);
  37422. createCylinderCap(true);
  37423. // Sides
  37424. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37425. var vertexData = new VertexData();
  37426. vertexData.indices = indices;
  37427. vertexData.positions = positions;
  37428. vertexData.normals = normals;
  37429. vertexData.uvs = uvs;
  37430. if (faceColors) {
  37431. vertexData.colors = colors;
  37432. }
  37433. return vertexData;
  37434. };
  37435. /**
  37436. * Creates the VertexData for a torus
  37437. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37438. * * diameter the diameter of the torus, optional default 1
  37439. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37440. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37441. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37442. * * 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)
  37443. * * 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)
  37444. * @returns the VertexData of the torus
  37445. */
  37446. VertexData.CreateTorus = function (options) {
  37447. var indices = [];
  37448. var positions = [];
  37449. var normals = [];
  37450. var uvs = [];
  37451. var diameter = options.diameter || 1;
  37452. var thickness = options.thickness || 0.5;
  37453. var tessellation = options.tessellation || 16;
  37454. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37455. var stride = tessellation + 1;
  37456. for (var i = 0; i <= tessellation; i++) {
  37457. var u = i / tessellation;
  37458. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37459. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37460. for (var j = 0; j <= tessellation; j++) {
  37461. var v = 1 - j / tessellation;
  37462. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37463. var dx = Math.cos(innerAngle);
  37464. var dy = Math.sin(innerAngle);
  37465. // Create a vertex.
  37466. var normal = new BABYLON.Vector3(dx, dy, 0);
  37467. var position = normal.scale(thickness / 2);
  37468. var textureCoordinate = new BABYLON.Vector2(u, v);
  37469. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37470. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37471. positions.push(position.x, position.y, position.z);
  37472. normals.push(normal.x, normal.y, normal.z);
  37473. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37474. // And create indices for two triangles.
  37475. var nextI = (i + 1) % stride;
  37476. var nextJ = (j + 1) % stride;
  37477. indices.push(i * stride + j);
  37478. indices.push(i * stride + nextJ);
  37479. indices.push(nextI * stride + j);
  37480. indices.push(i * stride + nextJ);
  37481. indices.push(nextI * stride + nextJ);
  37482. indices.push(nextI * stride + j);
  37483. }
  37484. }
  37485. // Sides
  37486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37487. // Result
  37488. var vertexData = new VertexData();
  37489. vertexData.indices = indices;
  37490. vertexData.positions = positions;
  37491. vertexData.normals = normals;
  37492. vertexData.uvs = uvs;
  37493. return vertexData;
  37494. };
  37495. /**
  37496. * Creates the VertexData of the LineSystem
  37497. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37498. * - lines an array of lines, each line being an array of successive Vector3
  37499. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37500. * @returns the VertexData of the LineSystem
  37501. */
  37502. VertexData.CreateLineSystem = function (options) {
  37503. var indices = [];
  37504. var positions = [];
  37505. var lines = options.lines;
  37506. var colors = options.colors;
  37507. var vertexColors = [];
  37508. var idx = 0;
  37509. for (var l = 0; l < lines.length; l++) {
  37510. var points = lines[l];
  37511. for (var index = 0; index < points.length; index++) {
  37512. positions.push(points[index].x, points[index].y, points[index].z);
  37513. if (colors) {
  37514. var color = colors[l];
  37515. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37516. }
  37517. if (index > 0) {
  37518. indices.push(idx - 1);
  37519. indices.push(idx);
  37520. }
  37521. idx++;
  37522. }
  37523. }
  37524. var vertexData = new VertexData();
  37525. vertexData.indices = indices;
  37526. vertexData.positions = positions;
  37527. if (colors) {
  37528. vertexData.colors = vertexColors;
  37529. }
  37530. return vertexData;
  37531. };
  37532. /**
  37533. * Create the VertexData for a DashedLines
  37534. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37535. * - points an array successive Vector3
  37536. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37537. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37538. * - dashNb the intended total number of dashes, optional, default 200
  37539. * @returns the VertexData for the DashedLines
  37540. */
  37541. VertexData.CreateDashedLines = function (options) {
  37542. var dashSize = options.dashSize || 3;
  37543. var gapSize = options.gapSize || 1;
  37544. var dashNb = options.dashNb || 200;
  37545. var points = options.points;
  37546. var positions = new Array();
  37547. var indices = new Array();
  37548. var curvect = BABYLON.Vector3.Zero();
  37549. var lg = 0;
  37550. var nb = 0;
  37551. var shft = 0;
  37552. var dashshft = 0;
  37553. var curshft = 0;
  37554. var idx = 0;
  37555. var i = 0;
  37556. for (i = 0; i < points.length - 1; i++) {
  37557. points[i + 1].subtractToRef(points[i], curvect);
  37558. lg += curvect.length();
  37559. }
  37560. shft = lg / dashNb;
  37561. dashshft = dashSize * shft / (dashSize + gapSize);
  37562. for (i = 0; i < points.length - 1; i++) {
  37563. points[i + 1].subtractToRef(points[i], curvect);
  37564. nb = Math.floor(curvect.length() / shft);
  37565. curvect.normalize();
  37566. for (var j = 0; j < nb; j++) {
  37567. curshft = shft * j;
  37568. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37569. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37570. indices.push(idx, idx + 1);
  37571. idx += 2;
  37572. }
  37573. }
  37574. // Result
  37575. var vertexData = new VertexData();
  37576. vertexData.positions = positions;
  37577. vertexData.indices = indices;
  37578. return vertexData;
  37579. };
  37580. /**
  37581. * Creates the VertexData for a Ground
  37582. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37583. * - width the width (x direction) of the ground, optional, default 1
  37584. * - height the height (z direction) of the ground, optional, default 1
  37585. * - subdivisions the number of subdivisions per side, optional, default 1
  37586. * @returns the VertexData of the Ground
  37587. */
  37588. VertexData.CreateGround = function (options) {
  37589. var indices = [];
  37590. var positions = [];
  37591. var normals = [];
  37592. var uvs = [];
  37593. var row, col;
  37594. var width = options.width || 1;
  37595. var height = options.height || 1;
  37596. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37597. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37598. for (row = 0; row <= subdivisionsY; row++) {
  37599. for (col = 0; col <= subdivisionsX; col++) {
  37600. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37601. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37602. positions.push(position.x, position.y, position.z);
  37603. normals.push(normal.x, normal.y, normal.z);
  37604. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37605. }
  37606. }
  37607. for (row = 0; row < subdivisionsY; row++) {
  37608. for (col = 0; col < subdivisionsX; col++) {
  37609. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37610. indices.push(col + 1 + row * (subdivisionsX + 1));
  37611. indices.push(col + row * (subdivisionsX + 1));
  37612. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37613. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37614. indices.push(col + row * (subdivisionsX + 1));
  37615. }
  37616. }
  37617. // Result
  37618. var vertexData = new VertexData();
  37619. vertexData.indices = indices;
  37620. vertexData.positions = positions;
  37621. vertexData.normals = normals;
  37622. vertexData.uvs = uvs;
  37623. return vertexData;
  37624. };
  37625. /**
  37626. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37627. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37628. * * xmin the ground minimum X coordinate, optional, default -1
  37629. * * zmin the ground minimum Z coordinate, optional, default -1
  37630. * * xmax the ground maximum X coordinate, optional, default 1
  37631. * * zmax the ground maximum Z coordinate, optional, default 1
  37632. * * 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}
  37633. * * 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}
  37634. * @returns the VertexData of the TiledGround
  37635. */
  37636. VertexData.CreateTiledGround = function (options) {
  37637. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37638. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37639. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37640. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37641. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37642. var precision = options.precision || { w: 1, h: 1 };
  37643. var indices = new Array();
  37644. var positions = new Array();
  37645. var normals = new Array();
  37646. var uvs = new Array();
  37647. var row, col, tileRow, tileCol;
  37648. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37649. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37650. precision.w = (precision.w < 1) ? 1 : precision.w;
  37651. precision.h = (precision.h < 1) ? 1 : precision.h;
  37652. var tileSize = {
  37653. 'w': (xmax - xmin) / subdivisions.w,
  37654. 'h': (zmax - zmin) / subdivisions.h
  37655. };
  37656. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37657. // Indices
  37658. var base = positions.length / 3;
  37659. var rowLength = precision.w + 1;
  37660. for (row = 0; row < precision.h; row++) {
  37661. for (col = 0; col < precision.w; col++) {
  37662. var square = [
  37663. base + col + row * rowLength,
  37664. base + (col + 1) + row * rowLength,
  37665. base + (col + 1) + (row + 1) * rowLength,
  37666. base + col + (row + 1) * rowLength
  37667. ];
  37668. indices.push(square[1]);
  37669. indices.push(square[2]);
  37670. indices.push(square[3]);
  37671. indices.push(square[0]);
  37672. indices.push(square[1]);
  37673. indices.push(square[3]);
  37674. }
  37675. }
  37676. // Position, normals and uvs
  37677. var position = BABYLON.Vector3.Zero();
  37678. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37679. for (row = 0; row <= precision.h; row++) {
  37680. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37681. for (col = 0; col <= precision.w; col++) {
  37682. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37683. position.y = 0;
  37684. positions.push(position.x, position.y, position.z);
  37685. normals.push(normal.x, normal.y, normal.z);
  37686. uvs.push(col / precision.w, row / precision.h);
  37687. }
  37688. }
  37689. }
  37690. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37691. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37692. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37693. }
  37694. }
  37695. // Result
  37696. var vertexData = new VertexData();
  37697. vertexData.indices = indices;
  37698. vertexData.positions = positions;
  37699. vertexData.normals = normals;
  37700. vertexData.uvs = uvs;
  37701. return vertexData;
  37702. };
  37703. /**
  37704. * Creates the VertexData of the Ground designed from a heightmap
  37705. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37706. * * width the width (x direction) of the ground
  37707. * * height the height (z direction) of the ground
  37708. * * subdivisions the number of subdivisions per side
  37709. * * minHeight the minimum altitude on the ground, optional, default 0
  37710. * * maxHeight the maximum altitude on the ground, optional default 1
  37711. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37712. * * buffer the array holding the image color data
  37713. * * bufferWidth the width of image
  37714. * * bufferHeight the height of image
  37715. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37716. * @returns the VertexData of the Ground designed from a heightmap
  37717. */
  37718. VertexData.CreateGroundFromHeightMap = function (options) {
  37719. var indices = [];
  37720. var positions = [];
  37721. var normals = [];
  37722. var uvs = [];
  37723. var row, col;
  37724. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37725. var alphaFilter = options.alphaFilter || 0.0;
  37726. // Vertices
  37727. for (row = 0; row <= options.subdivisions; row++) {
  37728. for (col = 0; col <= options.subdivisions; col++) {
  37729. 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));
  37730. // Compute height
  37731. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37732. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37733. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37734. var r = options.buffer[pos] / 255.0;
  37735. var g = options.buffer[pos + 1] / 255.0;
  37736. var b = options.buffer[pos + 2] / 255.0;
  37737. var a = options.buffer[pos + 3] / 255.0;
  37738. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37739. // If our alpha channel is not within our filter then we will assign a 'special' height
  37740. // Then when building the indices, we will ignore any vertex that is using the special height
  37741. if (a >= alphaFilter)
  37742. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37743. else {
  37744. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37745. }
  37746. // Add vertex
  37747. positions.push(position.x, position.y, position.z);
  37748. normals.push(0, 0, 0);
  37749. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37750. }
  37751. }
  37752. // Indices
  37753. for (row = 0; row < options.subdivisions; row++) {
  37754. for (col = 0; col < options.subdivisions; col++) {
  37755. // Calculate Indices
  37756. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37757. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37758. var idx3 = (col + row * (options.subdivisions + 1));
  37759. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37760. // Check that all indices are visible (based on our special height)
  37761. // Only display the vertex if all Indices are visible
  37762. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37763. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37764. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37765. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37766. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37767. indices.push(idx1);
  37768. indices.push(idx2);
  37769. indices.push(idx3);
  37770. }
  37771. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37772. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37773. indices.push(idx4);
  37774. indices.push(idx1);
  37775. indices.push(idx3);
  37776. }
  37777. }
  37778. }
  37779. // Normals
  37780. VertexData.ComputeNormals(positions, indices, normals);
  37781. // Result
  37782. var vertexData = new VertexData();
  37783. vertexData.indices = indices;
  37784. vertexData.positions = positions;
  37785. vertexData.normals = normals;
  37786. vertexData.uvs = uvs;
  37787. return vertexData;
  37788. };
  37789. /**
  37790. * Creates the VertexData for a Plane
  37791. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37792. * * size sets the width and height of the plane to the value of size, optional default 1
  37793. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37794. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37795. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37796. * * 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)
  37797. * * 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)
  37798. * @returns the VertexData of the box
  37799. */
  37800. VertexData.CreatePlane = function (options) {
  37801. var indices = [];
  37802. var positions = [];
  37803. var normals = [];
  37804. var uvs = [];
  37805. var width = options.width || options.size || 1;
  37806. var height = options.height || options.size || 1;
  37807. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37808. // Vertices
  37809. var halfWidth = width / 2.0;
  37810. var halfHeight = height / 2.0;
  37811. positions.push(-halfWidth, -halfHeight, 0);
  37812. normals.push(0, 0, -1.0);
  37813. uvs.push(0.0, 0.0);
  37814. positions.push(halfWidth, -halfHeight, 0);
  37815. normals.push(0, 0, -1.0);
  37816. uvs.push(1.0, 0.0);
  37817. positions.push(halfWidth, halfHeight, 0);
  37818. normals.push(0, 0, -1.0);
  37819. uvs.push(1.0, 1.0);
  37820. positions.push(-halfWidth, halfHeight, 0);
  37821. normals.push(0, 0, -1.0);
  37822. uvs.push(0.0, 1.0);
  37823. // Indices
  37824. indices.push(0);
  37825. indices.push(1);
  37826. indices.push(2);
  37827. indices.push(0);
  37828. indices.push(2);
  37829. indices.push(3);
  37830. // Sides
  37831. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37832. // Result
  37833. var vertexData = new VertexData();
  37834. vertexData.indices = indices;
  37835. vertexData.positions = positions;
  37836. vertexData.normals = normals;
  37837. vertexData.uvs = uvs;
  37838. return vertexData;
  37839. };
  37840. /**
  37841. * Creates the VertexData of the Disc or regular Polygon
  37842. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37843. * * radius the radius of the disc, optional default 0.5
  37844. * * tessellation the number of polygon sides, optional, default 64
  37845. * * 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
  37846. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37847. * * 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)
  37848. * * 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)
  37849. * @returns the VertexData of the box
  37850. */
  37851. VertexData.CreateDisc = function (options) {
  37852. var positions = new Array();
  37853. var indices = new Array();
  37854. var normals = new Array();
  37855. var uvs = new Array();
  37856. var radius = options.radius || 0.5;
  37857. var tessellation = options.tessellation || 64;
  37858. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37859. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37860. // positions and uvs
  37861. positions.push(0, 0, 0); // disc center first
  37862. uvs.push(0.5, 0.5);
  37863. var theta = Math.PI * 2 * arc;
  37864. var step = theta / tessellation;
  37865. for (var a = 0; a < theta; a += step) {
  37866. var x = Math.cos(a);
  37867. var y = Math.sin(a);
  37868. var u = (x + 1) / 2;
  37869. var v = (1 - y) / 2;
  37870. positions.push(radius * x, radius * y, 0);
  37871. uvs.push(u, v);
  37872. }
  37873. if (arc === 1) {
  37874. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37875. uvs.push(uvs[2], uvs[3]);
  37876. }
  37877. //indices
  37878. var vertexNb = positions.length / 3;
  37879. for (var i = 1; i < vertexNb - 1; i++) {
  37880. indices.push(i + 1, 0, i);
  37881. }
  37882. // result
  37883. VertexData.ComputeNormals(positions, indices, normals);
  37884. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37885. var vertexData = new VertexData();
  37886. vertexData.indices = indices;
  37887. vertexData.positions = positions;
  37888. vertexData.normals = normals;
  37889. vertexData.uvs = uvs;
  37890. return vertexData;
  37891. };
  37892. /**
  37893. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37894. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37895. * @param polygon a mesh built from polygonTriangulation.build()
  37896. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37897. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37898. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37899. * @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)
  37900. * @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)
  37901. * @returns the VertexData of the Polygon
  37902. */
  37903. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37904. var faceUV = fUV || new Array(3);
  37905. var faceColors = fColors;
  37906. var colors = [];
  37907. // default face colors and UV if undefined
  37908. for (var f = 0; f < 3; f++) {
  37909. if (faceUV[f] === undefined) {
  37910. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37911. }
  37912. if (faceColors && faceColors[f] === undefined) {
  37913. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37914. }
  37915. }
  37916. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37917. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37918. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37919. var indices = polygon.getIndices();
  37920. // set face colours and textures
  37921. var idx = 0;
  37922. var face = 0;
  37923. for (var index = 0; index < normals.length; index += 3) {
  37924. //Edge Face no. 1
  37925. if (Math.abs(normals[index + 1]) < 0.001) {
  37926. face = 1;
  37927. }
  37928. //Top Face no. 0
  37929. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37930. face = 0;
  37931. }
  37932. //Bottom Face no. 2
  37933. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37934. face = 2;
  37935. }
  37936. idx = index / 3;
  37937. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37938. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37939. if (faceColors) {
  37940. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37941. }
  37942. }
  37943. // sides
  37944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37945. // Result
  37946. var vertexData = new VertexData();
  37947. vertexData.indices = indices;
  37948. vertexData.positions = positions;
  37949. vertexData.normals = normals;
  37950. vertexData.uvs = uvs;
  37951. if (faceColors) {
  37952. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37953. vertexData.colors = totalColors;
  37954. }
  37955. return vertexData;
  37956. };
  37957. /**
  37958. * Creates the VertexData of the IcoSphere
  37959. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37960. * * radius the radius of the IcoSphere, optional default 1
  37961. * * radiusX allows stretching in the x direction, optional, default radius
  37962. * * radiusY allows stretching in the y direction, optional, default radius
  37963. * * radiusZ allows stretching in the z direction, optional, default radius
  37964. * * flat when true creates a flat shaded mesh, optional, default true
  37965. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37966. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37967. * * 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)
  37968. * * 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)
  37969. * @returns the VertexData of the IcoSphere
  37970. */
  37971. VertexData.CreateIcoSphere = function (options) {
  37972. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37973. var radius = options.radius || 1;
  37974. var flat = (options.flat === undefined) ? true : options.flat;
  37975. var subdivisions = options.subdivisions || 4;
  37976. var radiusX = options.radiusX || radius;
  37977. var radiusY = options.radiusY || radius;
  37978. var radiusZ = options.radiusZ || radius;
  37979. var t = (1 + Math.sqrt(5)) / 2;
  37980. // 12 vertex x,y,z
  37981. var ico_vertices = [
  37982. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37983. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37984. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37985. ];
  37986. // index of 3 vertex makes a face of icopshere
  37987. var ico_indices = [
  37988. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37989. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37990. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37991. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37992. ];
  37993. // vertex for uv have aliased position, not for UV
  37994. var vertices_unalias_id = [
  37995. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37996. // vertex alias
  37997. 0,
  37998. 2,
  37999. 3,
  38000. 3,
  38001. 3,
  38002. 4,
  38003. 7,
  38004. 8,
  38005. 9,
  38006. 9,
  38007. 10,
  38008. 11 // 23: B + 12
  38009. ];
  38010. // uv as integer step (not pixels !)
  38011. var ico_vertexuv = [
  38012. 5, 1, 3, 1, 6, 4, 0, 0,
  38013. 5, 3, 4, 2, 2, 2, 4, 0,
  38014. 2, 0, 1, 1, 6, 0, 6, 2,
  38015. // vertex alias (for same vertex on different faces)
  38016. 0, 4,
  38017. 3, 3,
  38018. 4, 4,
  38019. 3, 1,
  38020. 4, 2,
  38021. 4, 4,
  38022. 0, 2,
  38023. 1, 1,
  38024. 2, 2,
  38025. 3, 3,
  38026. 1, 3,
  38027. 2, 4 // 23: B + 12
  38028. ];
  38029. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38030. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38031. // First island of uv mapping
  38032. // v = 4h 3+ 2
  38033. // v = 3h 9+ 4
  38034. // v = 2h 9+ 5 B
  38035. // v = 1h 9 1 0
  38036. // v = 0h 3 8 7 A
  38037. // u = 0 1 2 3 4 5 6 *a
  38038. // Second island of uv mapping
  38039. // v = 4h 0+ B+ 4+
  38040. // v = 3h A+ 2+
  38041. // v = 2h 7+ 6 3+
  38042. // v = 1h 8+ 3+
  38043. // v = 0h
  38044. // u = 0 1 2 3 4 5 6 *a
  38045. // Face layout on texture UV mapping
  38046. // ============
  38047. // \ 4 /\ 16 / ======
  38048. // \ / \ / /\ 11 /
  38049. // \/ 7 \/ / \ /
  38050. // ======= / 10 \/
  38051. // /\ 17 /\ =======
  38052. // / \ / \ \ 15 /\
  38053. // / 8 \/ 12 \ \ / \
  38054. // ============ \/ 6 \
  38055. // \ 18 /\ ============
  38056. // \ / \ \ 5 /\ 0 /
  38057. // \/ 13 \ \ / \ /
  38058. // ======= \/ 1 \/
  38059. // =============
  38060. // /\ 19 /\ 2 /\
  38061. // / \ / \ / \
  38062. // / 14 \/ 9 \/ 3 \
  38063. // ===================
  38064. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38065. var ustep = 138 / 1024;
  38066. var vstep = 239 / 1024;
  38067. var uoffset = 60 / 1024;
  38068. var voffset = 26 / 1024;
  38069. // Second island should have margin, not to touch the first island
  38070. // avoid any borderline artefact in pixel rounding
  38071. var island_u_offset = -40 / 1024;
  38072. var island_v_offset = +20 / 1024;
  38073. // face is either island 0 or 1 :
  38074. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38075. var island = [
  38076. 0, 0, 0, 0, 1,
  38077. 0, 0, 1, 1, 0,
  38078. 0, 0, 1, 1, 0,
  38079. 0, 1, 1, 1, 0 // 15 - 19
  38080. ];
  38081. var indices = new Array();
  38082. var positions = new Array();
  38083. var normals = new Array();
  38084. var uvs = new Array();
  38085. var current_indice = 0;
  38086. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38087. var face_vertex_pos = new Array(3);
  38088. var face_vertex_uv = new Array(3);
  38089. var v012;
  38090. for (v012 = 0; v012 < 3; v012++) {
  38091. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38092. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38093. }
  38094. // create all with normals
  38095. for (var face = 0; face < 20; face++) {
  38096. // 3 vertex per face
  38097. for (v012 = 0; v012 < 3; v012++) {
  38098. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38099. var v_id = ico_indices[3 * face + v012];
  38100. // vertex have 3D position (x,y,z)
  38101. 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]);
  38102. // Normalize to get normal, then scale to radius
  38103. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38104. // uv Coordinates from vertex ID
  38105. 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);
  38106. }
  38107. // Subdivide the face (interpolate pos, norm, uv)
  38108. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38109. // - norm is linear interpolation of vertex corner normal
  38110. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38111. // - uv is linear interpolation
  38112. //
  38113. // Topology is as below for sub-divide by 2
  38114. // vertex shown as v0,v1,v2
  38115. // interp index is i1 to progress in range [v0,v1[
  38116. // interp index is i2 to progress in range [v0,v2[
  38117. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38118. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38119. //
  38120. //
  38121. // i2 v2
  38122. // ^ ^
  38123. // / / \
  38124. // / / \
  38125. // / / \
  38126. // / / (0,1) \
  38127. // / #---------\
  38128. // / / \ (0,0)'/ \
  38129. // / / \ / \
  38130. // / / \ / \
  38131. // / / (0,0) \ / (1,0) \
  38132. // / #---------#---------\
  38133. // v0 v1
  38134. //
  38135. // --------------------> i1
  38136. //
  38137. // interp of (i1,i2):
  38138. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38139. // along i1 : lerp(x0,x1, i1/(S-i2))
  38140. //
  38141. // centroid of triangle is needed to get help normal computation
  38142. // (c1,c2) are used for centroid location
  38143. var interp_vertex = function (i1, i2, c1, c2) {
  38144. // vertex is interpolated from
  38145. // - face_vertex_pos[0..2]
  38146. // - face_vertex_uv[0..2]
  38147. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38148. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38149. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38150. pos_interp.normalize();
  38151. var vertex_normal;
  38152. if (flat) {
  38153. // in flat mode, recalculate normal as face centroid normal
  38154. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38155. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38156. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38157. }
  38158. else {
  38159. // in smooth mode, recalculate normal from each single vertex position
  38160. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38161. }
  38162. // Vertex normal need correction due to X,Y,Z radius scaling
  38163. vertex_normal.x /= radiusX;
  38164. vertex_normal.y /= radiusY;
  38165. vertex_normal.z /= radiusZ;
  38166. vertex_normal.normalize();
  38167. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38168. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38169. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38170. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38171. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38172. uvs.push(uv_interp.x, uv_interp.y);
  38173. // push each vertex has member of a face
  38174. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38175. indices.push(current_indice);
  38176. current_indice++;
  38177. };
  38178. for (var i2 = 0; i2 < subdivisions; i2++) {
  38179. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38180. // face : (i1,i2) for /\ :
  38181. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38182. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38183. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38184. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38185. if (i1 + i2 + 1 < subdivisions) {
  38186. // face : (i1,i2)' for \/ :
  38187. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38188. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38189. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38190. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38191. }
  38192. }
  38193. }
  38194. }
  38195. // Sides
  38196. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38197. // Result
  38198. var vertexData = new VertexData();
  38199. vertexData.indices = indices;
  38200. vertexData.positions = positions;
  38201. vertexData.normals = normals;
  38202. vertexData.uvs = uvs;
  38203. return vertexData;
  38204. };
  38205. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38206. /**
  38207. * Creates the VertexData for a Polyhedron
  38208. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38209. * * type provided types are:
  38210. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38211. * * 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)
  38212. * * size the size of the IcoSphere, optional default 1
  38213. * * sizeX allows stretching in the x direction, optional, default size
  38214. * * sizeY allows stretching in the y direction, optional, default size
  38215. * * sizeZ allows stretching in the z direction, optional, default size
  38216. * * 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
  38217. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38218. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38219. * * flat when true creates a flat shaded mesh, optional, default true
  38220. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38221. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38222. * * 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)
  38223. * * 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)
  38224. * @returns the VertexData of the Polyhedron
  38225. */
  38226. VertexData.CreatePolyhedron = function (options) {
  38227. // provided polyhedron types :
  38228. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38229. // 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)
  38230. var polyhedra = [];
  38231. 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]] };
  38232. 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]] };
  38233. polyhedra[2] = {
  38234. 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]],
  38235. 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]]
  38236. };
  38237. polyhedra[3] = {
  38238. 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]],
  38239. 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]]
  38240. };
  38241. polyhedra[4] = {
  38242. 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]],
  38243. 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]]
  38244. };
  38245. 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]] };
  38246. 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]] };
  38247. 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]] };
  38248. 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]] };
  38249. 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]] };
  38250. 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]] };
  38251. 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]] };
  38252. 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]] };
  38253. 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]] };
  38254. polyhedra[14] = {
  38255. 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]],
  38256. 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]]
  38257. };
  38258. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38259. var size = options.size;
  38260. var sizeX = options.sizeX || size || 1;
  38261. var sizeY = options.sizeY || size || 1;
  38262. var sizeZ = options.sizeZ || size || 1;
  38263. var data = options.custom || polyhedra[type];
  38264. var nbfaces = data.face.length;
  38265. var faceUV = options.faceUV || new Array(nbfaces);
  38266. var faceColors = options.faceColors;
  38267. var flat = (options.flat === undefined) ? true : options.flat;
  38268. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38269. var positions = new Array();
  38270. var indices = new Array();
  38271. var normals = new Array();
  38272. var uvs = new Array();
  38273. var colors = new Array();
  38274. var index = 0;
  38275. var faceIdx = 0; // face cursor in the array "indexes"
  38276. var indexes = new Array();
  38277. var i = 0;
  38278. var f = 0;
  38279. var u, v, ang, x, y, tmp;
  38280. // default face colors and UV if undefined
  38281. if (flat) {
  38282. for (f = 0; f < nbfaces; f++) {
  38283. if (faceColors && faceColors[f] === undefined) {
  38284. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38285. }
  38286. if (faceUV && faceUV[f] === undefined) {
  38287. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38288. }
  38289. }
  38290. }
  38291. if (!flat) {
  38292. for (i = 0; i < data.vertex.length; i++) {
  38293. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38294. uvs.push(0, 0);
  38295. }
  38296. for (f = 0; f < nbfaces; f++) {
  38297. for (i = 0; i < data.face[f].length - 2; i++) {
  38298. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38299. }
  38300. }
  38301. }
  38302. else {
  38303. for (f = 0; f < nbfaces; f++) {
  38304. var fl = data.face[f].length; // number of vertices of the current face
  38305. ang = 2 * Math.PI / fl;
  38306. x = 0.5 * Math.tan(ang / 2);
  38307. y = 0.5;
  38308. // positions, uvs, colors
  38309. for (i = 0; i < fl; i++) {
  38310. // positions
  38311. 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);
  38312. indexes.push(index);
  38313. index++;
  38314. // uvs
  38315. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38316. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38317. uvs.push(u, v);
  38318. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38319. y = x * Math.sin(ang) + y * Math.cos(ang);
  38320. x = tmp;
  38321. // colors
  38322. if (faceColors) {
  38323. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38324. }
  38325. }
  38326. // indices from indexes
  38327. for (i = 0; i < fl - 2; i++) {
  38328. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38329. }
  38330. faceIdx += fl;
  38331. }
  38332. }
  38333. VertexData.ComputeNormals(positions, indices, normals);
  38334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38335. var vertexData = new VertexData();
  38336. vertexData.positions = positions;
  38337. vertexData.indices = indices;
  38338. vertexData.normals = normals;
  38339. vertexData.uvs = uvs;
  38340. if (faceColors && flat) {
  38341. vertexData.colors = colors;
  38342. }
  38343. return vertexData;
  38344. };
  38345. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38346. /**
  38347. * Creates the VertexData for a TorusKnot
  38348. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38349. * * radius the radius of the torus knot, optional, default 2
  38350. * * tube the thickness of the tube, optional, default 0.5
  38351. * * radialSegments the number of sides on each tube segments, optional, default 32
  38352. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38353. * * p the number of windings around the z axis, optional, default 2
  38354. * * q the number of windings around the x axis, optional, default 3
  38355. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38356. * * 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)
  38357. * * 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)
  38358. * @returns the VertexData of the Torus Knot
  38359. */
  38360. VertexData.CreateTorusKnot = function (options) {
  38361. var indices = new Array();
  38362. var positions = new Array();
  38363. var normals = new Array();
  38364. var uvs = new Array();
  38365. var radius = options.radius || 2;
  38366. var tube = options.tube || 0.5;
  38367. var radialSegments = options.radialSegments || 32;
  38368. var tubularSegments = options.tubularSegments || 32;
  38369. var p = options.p || 2;
  38370. var q = options.q || 3;
  38371. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38372. // Helper
  38373. var getPos = function (angle) {
  38374. var cu = Math.cos(angle);
  38375. var su = Math.sin(angle);
  38376. var quOverP = q / p * angle;
  38377. var cs = Math.cos(quOverP);
  38378. var tx = radius * (2 + cs) * 0.5 * cu;
  38379. var ty = radius * (2 + cs) * su * 0.5;
  38380. var tz = radius * Math.sin(quOverP) * 0.5;
  38381. return new BABYLON.Vector3(tx, ty, tz);
  38382. };
  38383. // Vertices
  38384. var i;
  38385. var j;
  38386. for (i = 0; i <= radialSegments; i++) {
  38387. var modI = i % radialSegments;
  38388. var u = modI / radialSegments * 2 * p * Math.PI;
  38389. var p1 = getPos(u);
  38390. var p2 = getPos(u + 0.01);
  38391. var tang = p2.subtract(p1);
  38392. var n = p2.add(p1);
  38393. var bitan = BABYLON.Vector3.Cross(tang, n);
  38394. n = BABYLON.Vector3.Cross(bitan, tang);
  38395. bitan.normalize();
  38396. n.normalize();
  38397. for (j = 0; j < tubularSegments; j++) {
  38398. var modJ = j % tubularSegments;
  38399. var v = modJ / tubularSegments * 2 * Math.PI;
  38400. var cx = -tube * Math.cos(v);
  38401. var cy = tube * Math.sin(v);
  38402. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38403. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38404. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38405. uvs.push(i / radialSegments);
  38406. uvs.push(j / tubularSegments);
  38407. }
  38408. }
  38409. for (i = 0; i < radialSegments; i++) {
  38410. for (j = 0; j < tubularSegments; j++) {
  38411. var jNext = (j + 1) % tubularSegments;
  38412. var a = i * tubularSegments + j;
  38413. var b = (i + 1) * tubularSegments + j;
  38414. var c = (i + 1) * tubularSegments + jNext;
  38415. var d = i * tubularSegments + jNext;
  38416. indices.push(d);
  38417. indices.push(b);
  38418. indices.push(a);
  38419. indices.push(d);
  38420. indices.push(c);
  38421. indices.push(b);
  38422. }
  38423. }
  38424. // Normals
  38425. VertexData.ComputeNormals(positions, indices, normals);
  38426. // Sides
  38427. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38428. // Result
  38429. var vertexData = new VertexData();
  38430. vertexData.indices = indices;
  38431. vertexData.positions = positions;
  38432. vertexData.normals = normals;
  38433. vertexData.uvs = uvs;
  38434. return vertexData;
  38435. };
  38436. // Tools
  38437. /**
  38438. * Compute normals for given positions and indices
  38439. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38440. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38441. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38442. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38443. * * facetNormals : optional array of facet normals (vector3)
  38444. * * facetPositions : optional array of facet positions (vector3)
  38445. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38446. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38447. * * bInfo : optional bounding info, required for facetPartitioning computation
  38448. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38449. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38450. * * useRightHandedSystem: optional boolean to for right handed system computation
  38451. * * depthSort : optional boolean to enable the facet depth sort computation
  38452. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38453. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38454. */
  38455. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38456. // temporary scalar variables
  38457. var index = 0; // facet index
  38458. var p1p2x = 0.0; // p1p2 vector x coordinate
  38459. var p1p2y = 0.0; // p1p2 vector y coordinate
  38460. var p1p2z = 0.0; // p1p2 vector z coordinate
  38461. var p3p2x = 0.0; // p3p2 vector x coordinate
  38462. var p3p2y = 0.0; // p3p2 vector y coordinate
  38463. var p3p2z = 0.0; // p3p2 vector z coordinate
  38464. var faceNormalx = 0.0; // facet normal x coordinate
  38465. var faceNormaly = 0.0; // facet normal y coordinate
  38466. var faceNormalz = 0.0; // facet normal z coordinate
  38467. var length = 0.0; // facet normal length before normalization
  38468. var v1x = 0; // vector1 x index in the positions array
  38469. var v1y = 0; // vector1 y index in the positions array
  38470. var v1z = 0; // vector1 z index in the positions array
  38471. var v2x = 0; // vector2 x index in the positions array
  38472. var v2y = 0; // vector2 y index in the positions array
  38473. var v2z = 0; // vector2 z index in the positions array
  38474. var v3x = 0; // vector3 x index in the positions array
  38475. var v3y = 0; // vector3 y index in the positions array
  38476. var v3z = 0; // vector3 z index in the positions array
  38477. var computeFacetNormals = false;
  38478. var computeFacetPositions = false;
  38479. var computeFacetPartitioning = false;
  38480. var computeDepthSort = false;
  38481. var faceNormalSign = 1;
  38482. var ratio = 0;
  38483. var distanceTo = null;
  38484. if (options) {
  38485. computeFacetNormals = (options.facetNormals) ? true : false;
  38486. computeFacetPositions = (options.facetPositions) ? true : false;
  38487. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38488. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38489. ratio = options.ratio || 0;
  38490. computeDepthSort = (options.depthSort) ? true : false;
  38491. distanceTo = (options.distanceTo);
  38492. if (computeDepthSort) {
  38493. if (distanceTo === undefined) {
  38494. distanceTo = BABYLON.Vector3.Zero();
  38495. }
  38496. var depthSortedFacets = options.depthSortedFacets;
  38497. }
  38498. }
  38499. // facetPartitioning reinit if needed
  38500. var xSubRatio = 0;
  38501. var ySubRatio = 0;
  38502. var zSubRatio = 0;
  38503. var subSq = 0;
  38504. if (computeFacetPartitioning && options && options.bbSize) {
  38505. var ox = 0; // X partitioning index for facet position
  38506. var oy = 0; // Y partinioning index for facet position
  38507. var oz = 0; // Z partinioning index for facet position
  38508. var b1x = 0; // X partitioning index for facet v1 vertex
  38509. var b1y = 0; // Y partitioning index for facet v1 vertex
  38510. var b1z = 0; // z partitioning index for facet v1 vertex
  38511. var b2x = 0; // X partitioning index for facet v2 vertex
  38512. var b2y = 0; // Y partitioning index for facet v2 vertex
  38513. var b2z = 0; // Z partitioning index for facet v2 vertex
  38514. var b3x = 0; // X partitioning index for facet v3 vertex
  38515. var b3y = 0; // Y partitioning index for facet v3 vertex
  38516. var b3z = 0; // Z partitioning index for facet v3 vertex
  38517. var block_idx_o = 0; // facet barycenter block index
  38518. var block_idx_v1 = 0; // v1 vertex block index
  38519. var block_idx_v2 = 0; // v2 vertex block index
  38520. var block_idx_v3 = 0; // v3 vertex block index
  38521. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38522. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38523. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38524. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38525. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38526. subSq = options.subDiv.max * options.subDiv.max;
  38527. options.facetPartitioning.length = 0;
  38528. }
  38529. // reset the normals
  38530. for (index = 0; index < positions.length; index++) {
  38531. normals[index] = 0.0;
  38532. }
  38533. // Loop : 1 indice triplet = 1 facet
  38534. var nbFaces = (indices.length / 3) | 0;
  38535. for (index = 0; index < nbFaces; index++) {
  38536. // get the indexes of the coordinates of each vertex of the facet
  38537. v1x = indices[index * 3] * 3;
  38538. v1y = v1x + 1;
  38539. v1z = v1x + 2;
  38540. v2x = indices[index * 3 + 1] * 3;
  38541. v2y = v2x + 1;
  38542. v2z = v2x + 2;
  38543. v3x = indices[index * 3 + 2] * 3;
  38544. v3y = v3x + 1;
  38545. v3z = v3x + 2;
  38546. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38547. p1p2y = positions[v1y] - positions[v2y];
  38548. p1p2z = positions[v1z] - positions[v2z];
  38549. p3p2x = positions[v3x] - positions[v2x];
  38550. p3p2y = positions[v3y] - positions[v2y];
  38551. p3p2z = positions[v3z] - positions[v2z];
  38552. // compute the face normal with the cross product
  38553. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38554. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38555. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38556. // normalize this normal and store it in the array facetData
  38557. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38558. length = (length === 0) ? 1.0 : length;
  38559. faceNormalx /= length;
  38560. faceNormaly /= length;
  38561. faceNormalz /= length;
  38562. if (computeFacetNormals && options) {
  38563. options.facetNormals[index].x = faceNormalx;
  38564. options.facetNormals[index].y = faceNormaly;
  38565. options.facetNormals[index].z = faceNormalz;
  38566. }
  38567. if (computeFacetPositions && options) {
  38568. // compute and the facet barycenter coordinates in the array facetPositions
  38569. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38570. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38571. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38572. }
  38573. if (computeFacetPartitioning && options) {
  38574. // store the facet indexes in arrays in the main facetPartitioning array :
  38575. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38576. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38577. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38578. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38579. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38580. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38581. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38582. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38583. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38584. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38585. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38586. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38587. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38588. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38589. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38590. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38591. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38592. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38593. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38594. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38595. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38596. // push each facet index in each block containing the vertex
  38597. options.facetPartitioning[block_idx_v1].push(index);
  38598. if (block_idx_v2 != block_idx_v1) {
  38599. options.facetPartitioning[block_idx_v2].push(index);
  38600. }
  38601. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38602. options.facetPartitioning[block_idx_v3].push(index);
  38603. }
  38604. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38605. options.facetPartitioning[block_idx_o].push(index);
  38606. }
  38607. }
  38608. if (computeDepthSort && options && options.facetPositions) {
  38609. var dsf = depthSortedFacets[index];
  38610. dsf.ind = index * 3;
  38611. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38612. }
  38613. // compute the normals anyway
  38614. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38615. normals[v1y] += faceNormaly;
  38616. normals[v1z] += faceNormalz;
  38617. normals[v2x] += faceNormalx;
  38618. normals[v2y] += faceNormaly;
  38619. normals[v2z] += faceNormalz;
  38620. normals[v3x] += faceNormalx;
  38621. normals[v3y] += faceNormaly;
  38622. normals[v3z] += faceNormalz;
  38623. }
  38624. // last normalization of each normal
  38625. for (index = 0; index < normals.length / 3; index++) {
  38626. faceNormalx = normals[index * 3];
  38627. faceNormaly = normals[index * 3 + 1];
  38628. faceNormalz = normals[index * 3 + 2];
  38629. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38630. length = (length === 0) ? 1.0 : length;
  38631. faceNormalx /= length;
  38632. faceNormaly /= length;
  38633. faceNormalz /= length;
  38634. normals[index * 3] = faceNormalx;
  38635. normals[index * 3 + 1] = faceNormaly;
  38636. normals[index * 3 + 2] = faceNormalz;
  38637. }
  38638. };
  38639. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38640. var li = indices.length;
  38641. var ln = normals.length;
  38642. var i;
  38643. var n;
  38644. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38645. switch (sideOrientation) {
  38646. case BABYLON.Mesh.FRONTSIDE:
  38647. // nothing changed
  38648. break;
  38649. case BABYLON.Mesh.BACKSIDE:
  38650. var tmp;
  38651. // indices
  38652. for (i = 0; i < li; i += 3) {
  38653. tmp = indices[i];
  38654. indices[i] = indices[i + 2];
  38655. indices[i + 2] = tmp;
  38656. }
  38657. // normals
  38658. for (n = 0; n < ln; n++) {
  38659. normals[n] = -normals[n];
  38660. }
  38661. break;
  38662. case BABYLON.Mesh.DOUBLESIDE:
  38663. // positions
  38664. var lp = positions.length;
  38665. var l = lp / 3;
  38666. for (var p = 0; p < lp; p++) {
  38667. positions[lp + p] = positions[p];
  38668. }
  38669. // indices
  38670. for (i = 0; i < li; i += 3) {
  38671. indices[i + li] = indices[i + 2] + l;
  38672. indices[i + 1 + li] = indices[i + 1] + l;
  38673. indices[i + 2 + li] = indices[i] + l;
  38674. }
  38675. // normals
  38676. for (n = 0; n < ln; n++) {
  38677. normals[ln + n] = -normals[n];
  38678. }
  38679. // uvs
  38680. var lu = uvs.length;
  38681. var u = 0;
  38682. for (u = 0; u < lu; u++) {
  38683. uvs[u + lu] = uvs[u];
  38684. }
  38685. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38686. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38687. u = 0;
  38688. for (i = 0; i < lu / 2; i++) {
  38689. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38690. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38691. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38692. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38693. u += 2;
  38694. }
  38695. break;
  38696. }
  38697. };
  38698. /**
  38699. * Applies VertexData created from the imported parameters to the geometry
  38700. * @param parsedVertexData the parsed data from an imported file
  38701. * @param geometry the geometry to apply the VertexData to
  38702. */
  38703. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38704. var vertexData = new VertexData();
  38705. // positions
  38706. var positions = parsedVertexData.positions;
  38707. if (positions) {
  38708. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38709. }
  38710. // normals
  38711. var normals = parsedVertexData.normals;
  38712. if (normals) {
  38713. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38714. }
  38715. // tangents
  38716. var tangents = parsedVertexData.tangents;
  38717. if (tangents) {
  38718. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38719. }
  38720. // uvs
  38721. var uvs = parsedVertexData.uvs;
  38722. if (uvs) {
  38723. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38724. }
  38725. // uv2s
  38726. var uv2s = parsedVertexData.uv2s;
  38727. if (uv2s) {
  38728. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38729. }
  38730. // uv3s
  38731. var uv3s = parsedVertexData.uv3s;
  38732. if (uv3s) {
  38733. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38734. }
  38735. // uv4s
  38736. var uv4s = parsedVertexData.uv4s;
  38737. if (uv4s) {
  38738. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38739. }
  38740. // uv5s
  38741. var uv5s = parsedVertexData.uv5s;
  38742. if (uv5s) {
  38743. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38744. }
  38745. // uv6s
  38746. var uv6s = parsedVertexData.uv6s;
  38747. if (uv6s) {
  38748. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38749. }
  38750. // colors
  38751. var colors = parsedVertexData.colors;
  38752. if (colors) {
  38753. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38754. }
  38755. // matricesIndices
  38756. var matricesIndices = parsedVertexData.matricesIndices;
  38757. if (matricesIndices) {
  38758. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38759. }
  38760. // matricesWeights
  38761. var matricesWeights = parsedVertexData.matricesWeights;
  38762. if (matricesWeights) {
  38763. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38764. }
  38765. // indices
  38766. var indices = parsedVertexData.indices;
  38767. if (indices) {
  38768. vertexData.indices = indices;
  38769. }
  38770. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38771. };
  38772. return VertexData;
  38773. }());
  38774. BABYLON.VertexData = VertexData;
  38775. })(BABYLON || (BABYLON = {}));
  38776. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38777. var BABYLON;
  38778. (function (BABYLON) {
  38779. /**
  38780. * Class used to store geometry data (vertex buffers + index buffer)
  38781. */
  38782. var Geometry = /** @class */ (function () {
  38783. /**
  38784. * Creates a new geometry
  38785. * @param id defines the unique ID
  38786. * @param scene defines the hosting scene
  38787. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38788. * @param updatable defines if geometry must be updatable (false by default)
  38789. * @param mesh defines the mesh that will be associated with the geometry
  38790. */
  38791. function Geometry(id, scene, vertexData, updatable, mesh) {
  38792. if (updatable === void 0) { updatable = false; }
  38793. if (mesh === void 0) { mesh = null; }
  38794. /**
  38795. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38796. */
  38797. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38798. this._totalVertices = 0;
  38799. this._isDisposed = false;
  38800. this._indexBufferIsUpdatable = false;
  38801. this.id = id;
  38802. this._engine = scene.getEngine();
  38803. this._meshes = [];
  38804. this._scene = scene;
  38805. //Init vertex buffer cache
  38806. this._vertexBuffers = {};
  38807. this._indices = [];
  38808. this._updatable = updatable;
  38809. // vertexData
  38810. if (vertexData) {
  38811. this.setAllVerticesData(vertexData, updatable);
  38812. }
  38813. else {
  38814. this._totalVertices = 0;
  38815. this._indices = [];
  38816. }
  38817. if (this._engine.getCaps().vertexArrayObject) {
  38818. this._vertexArrayObjects = {};
  38819. }
  38820. // applyToMesh
  38821. if (mesh) {
  38822. if (mesh.getClassName() === "LinesMesh") {
  38823. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38824. this._updateExtend();
  38825. }
  38826. this.applyToMesh(mesh);
  38827. mesh.computeWorldMatrix(true);
  38828. }
  38829. }
  38830. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38831. /**
  38832. * 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
  38833. */
  38834. get: function () {
  38835. return this._boundingBias;
  38836. },
  38837. /**
  38838. * 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
  38839. */
  38840. set: function (value) {
  38841. if (this._boundingBias && this._boundingBias.equals(value)) {
  38842. return;
  38843. }
  38844. this._boundingBias = value.clone();
  38845. this._updateBoundingInfo(true, null);
  38846. },
  38847. enumerable: true,
  38848. configurable: true
  38849. });
  38850. /**
  38851. * Static function used to attach a new empty geometry to a mesh
  38852. * @param mesh defines the mesh to attach the geometry to
  38853. * @returns the new {BABYLON.Geometry}
  38854. */
  38855. Geometry.CreateGeometryForMesh = function (mesh) {
  38856. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38857. geometry.applyToMesh(mesh);
  38858. return geometry;
  38859. };
  38860. Object.defineProperty(Geometry.prototype, "extend", {
  38861. /**
  38862. * Gets the current extend of the geometry
  38863. */
  38864. get: function () {
  38865. return this._extend;
  38866. },
  38867. enumerable: true,
  38868. configurable: true
  38869. });
  38870. /**
  38871. * Gets the hosting scene
  38872. * @returns the hosting {BABYLON.Scene}
  38873. */
  38874. Geometry.prototype.getScene = function () {
  38875. return this._scene;
  38876. };
  38877. /**
  38878. * Gets the hosting engine
  38879. * @returns the hosting {BABYLON.Engine}
  38880. */
  38881. Geometry.prototype.getEngine = function () {
  38882. return this._engine;
  38883. };
  38884. /**
  38885. * Defines if the geometry is ready to use
  38886. * @returns true if the geometry is ready to be used
  38887. */
  38888. Geometry.prototype.isReady = function () {
  38889. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38890. };
  38891. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38892. /**
  38893. * Gets a value indicating that the geometry should not be serialized
  38894. */
  38895. get: function () {
  38896. for (var index = 0; index < this._meshes.length; index++) {
  38897. if (!this._meshes[index].doNotSerialize) {
  38898. return false;
  38899. }
  38900. }
  38901. return true;
  38902. },
  38903. enumerable: true,
  38904. configurable: true
  38905. });
  38906. /** @hidden */
  38907. Geometry.prototype._rebuild = function () {
  38908. if (this._vertexArrayObjects) {
  38909. this._vertexArrayObjects = {};
  38910. }
  38911. // Index buffer
  38912. if (this._meshes.length !== 0 && this._indices) {
  38913. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38914. }
  38915. // Vertex buffers
  38916. for (var key in this._vertexBuffers) {
  38917. var vertexBuffer = this._vertexBuffers[key];
  38918. vertexBuffer._rebuild();
  38919. }
  38920. };
  38921. /**
  38922. * Affects all geometry data in one call
  38923. * @param vertexData defines the geometry data
  38924. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38925. */
  38926. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38927. vertexData.applyToGeometry(this, updatable);
  38928. this.notifyUpdate();
  38929. };
  38930. /**
  38931. * Set specific vertex data
  38932. * @param kind defines the data kind (Position, normal, etc...)
  38933. * @param data defines the vertex data to use
  38934. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38935. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38936. */
  38937. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38938. if (updatable === void 0) { updatable = false; }
  38939. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38940. this.setVerticesBuffer(buffer);
  38941. };
  38942. /**
  38943. * Removes a specific vertex data
  38944. * @param kind defines the data kind (Position, normal, etc...)
  38945. */
  38946. Geometry.prototype.removeVerticesData = function (kind) {
  38947. if (this._vertexBuffers[kind]) {
  38948. this._vertexBuffers[kind].dispose();
  38949. delete this._vertexBuffers[kind];
  38950. }
  38951. };
  38952. /**
  38953. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38954. * @param buffer defines the vertex buffer to use
  38955. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38956. */
  38957. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38958. if (totalVertices === void 0) { totalVertices = null; }
  38959. var kind = buffer.getKind();
  38960. if (this._vertexBuffers[kind]) {
  38961. this._vertexBuffers[kind].dispose();
  38962. }
  38963. this._vertexBuffers[kind] = buffer;
  38964. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38965. var data = buffer.getData();
  38966. if (totalVertices != null) {
  38967. this._totalVertices = totalVertices;
  38968. }
  38969. else {
  38970. if (data != null) {
  38971. this._totalVertices = data.length / (buffer.byteStride / 4);
  38972. }
  38973. }
  38974. this._updateExtend(data);
  38975. this._resetPointsArrayCache();
  38976. var meshes = this._meshes;
  38977. var numOfMeshes = meshes.length;
  38978. for (var index = 0; index < numOfMeshes; index++) {
  38979. var mesh = meshes[index];
  38980. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38981. mesh._createGlobalSubMesh(false);
  38982. mesh.computeWorldMatrix(true);
  38983. }
  38984. }
  38985. this.notifyUpdate(kind);
  38986. if (this._vertexArrayObjects) {
  38987. this._disposeVertexArrayObjects();
  38988. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38989. }
  38990. };
  38991. /**
  38992. * Update a specific vertex buffer
  38993. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38994. * It will do nothing if the buffer is not updatable
  38995. * @param kind defines the data kind (Position, normal, etc...)
  38996. * @param data defines the data to use
  38997. * @param offset defines the offset in the target buffer where to store the data
  38998. * @param useBytes set to true if the offset is in bytes
  38999. */
  39000. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39001. if (useBytes === void 0) { useBytes = false; }
  39002. var vertexBuffer = this.getVertexBuffer(kind);
  39003. if (!vertexBuffer) {
  39004. return;
  39005. }
  39006. vertexBuffer.updateDirectly(data, offset, useBytes);
  39007. this.notifyUpdate(kind);
  39008. };
  39009. /**
  39010. * Update a specific vertex buffer
  39011. * This function will create a new buffer if the current one is not updatable
  39012. * @param kind defines the data kind (Position, normal, etc...)
  39013. * @param data defines the data to use
  39014. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39015. */
  39016. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39017. if (updateExtends === void 0) { updateExtends = false; }
  39018. var vertexBuffer = this.getVertexBuffer(kind);
  39019. if (!vertexBuffer) {
  39020. return;
  39021. }
  39022. vertexBuffer.update(data);
  39023. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39024. this._updateBoundingInfo(updateExtends, data);
  39025. }
  39026. this.notifyUpdate(kind);
  39027. };
  39028. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39029. if (updateExtends) {
  39030. this._updateExtend(data);
  39031. }
  39032. var meshes = this._meshes;
  39033. var numOfMeshes = meshes.length;
  39034. this._resetPointsArrayCache();
  39035. for (var index = 0; index < numOfMeshes; index++) {
  39036. var mesh = meshes[index];
  39037. if (updateExtends) {
  39038. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39039. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39040. var subMesh = mesh.subMeshes[subIndex];
  39041. subMesh.refreshBoundingInfo();
  39042. }
  39043. }
  39044. }
  39045. };
  39046. /** @hidden */
  39047. Geometry.prototype._bind = function (effect, indexToBind) {
  39048. if (!effect) {
  39049. return;
  39050. }
  39051. if (indexToBind === undefined) {
  39052. indexToBind = this._indexBuffer;
  39053. }
  39054. var vbs = this.getVertexBuffers();
  39055. if (!vbs) {
  39056. return;
  39057. }
  39058. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39059. this._engine.bindBuffers(vbs, indexToBind, effect);
  39060. return;
  39061. }
  39062. // Using VAO
  39063. if (!this._vertexArrayObjects[effect.key]) {
  39064. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39065. }
  39066. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39067. };
  39068. /**
  39069. * Gets total number of vertices
  39070. * @returns the total number of vertices
  39071. */
  39072. Geometry.prototype.getTotalVertices = function () {
  39073. if (!this.isReady()) {
  39074. return 0;
  39075. }
  39076. return this._totalVertices;
  39077. };
  39078. /**
  39079. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39080. * @param kind defines the data kind (Position, normal, etc...)
  39081. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39082. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39083. * @returns a float array containing vertex data
  39084. */
  39085. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39086. var vertexBuffer = this.getVertexBuffer(kind);
  39087. if (!vertexBuffer) {
  39088. return null;
  39089. }
  39090. var data = vertexBuffer.getData();
  39091. if (!data) {
  39092. return null;
  39093. }
  39094. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39095. var count = this._totalVertices * vertexBuffer.getSize();
  39096. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39097. var copy_1 = new Array(count);
  39098. vertexBuffer.forEach(count, function (value, index) {
  39099. copy_1[index] = value;
  39100. });
  39101. return copy_1;
  39102. }
  39103. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39104. if (data instanceof Array) {
  39105. var offset = vertexBuffer.byteOffset / 4;
  39106. return BABYLON.Tools.Slice(data, offset, offset + count);
  39107. }
  39108. else if (data instanceof ArrayBuffer) {
  39109. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39110. }
  39111. else {
  39112. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39113. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39114. var result = new Float32Array(count);
  39115. var source = new Float32Array(data.buffer, offset, count);
  39116. result.set(source);
  39117. return result;
  39118. }
  39119. return new Float32Array(data.buffer, offset, count);
  39120. }
  39121. }
  39122. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39123. return BABYLON.Tools.Slice(data);
  39124. }
  39125. return data;
  39126. };
  39127. /**
  39128. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39129. * @param kind defines the data kind (Position, normal, etc...)
  39130. * @returns true if the vertex buffer with the specified kind is updatable
  39131. */
  39132. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39133. var vb = this._vertexBuffers[kind];
  39134. if (!vb) {
  39135. return false;
  39136. }
  39137. return vb.isUpdatable();
  39138. };
  39139. /**
  39140. * Gets a specific vertex buffer
  39141. * @param kind defines the data kind (Position, normal, etc...)
  39142. * @returns a {BABYLON.VertexBuffer}
  39143. */
  39144. Geometry.prototype.getVertexBuffer = function (kind) {
  39145. if (!this.isReady()) {
  39146. return null;
  39147. }
  39148. return this._vertexBuffers[kind];
  39149. };
  39150. /**
  39151. * Returns all vertex buffers
  39152. * @return an object holding all vertex buffers indexed by kind
  39153. */
  39154. Geometry.prototype.getVertexBuffers = function () {
  39155. if (!this.isReady()) {
  39156. return null;
  39157. }
  39158. return this._vertexBuffers;
  39159. };
  39160. /**
  39161. * Gets a boolean indicating if specific vertex buffer is present
  39162. * @param kind defines the data kind (Position, normal, etc...)
  39163. * @returns true if data is present
  39164. */
  39165. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39166. if (!this._vertexBuffers) {
  39167. if (this._delayInfo) {
  39168. return this._delayInfo.indexOf(kind) !== -1;
  39169. }
  39170. return false;
  39171. }
  39172. return this._vertexBuffers[kind] !== undefined;
  39173. };
  39174. /**
  39175. * Gets a list of all attached data kinds (Position, normal, etc...)
  39176. * @returns a list of string containing all kinds
  39177. */
  39178. Geometry.prototype.getVerticesDataKinds = function () {
  39179. var result = [];
  39180. var kind;
  39181. if (!this._vertexBuffers && this._delayInfo) {
  39182. for (kind in this._delayInfo) {
  39183. result.push(kind);
  39184. }
  39185. }
  39186. else {
  39187. for (kind in this._vertexBuffers) {
  39188. result.push(kind);
  39189. }
  39190. }
  39191. return result;
  39192. };
  39193. /**
  39194. * Update index buffer
  39195. * @param indices defines the indices to store in the index buffer
  39196. * @param offset defines the offset in the target buffer where to store the data
  39197. */
  39198. Geometry.prototype.updateIndices = function (indices, offset) {
  39199. if (!this._indexBuffer) {
  39200. return;
  39201. }
  39202. if (!this._indexBufferIsUpdatable) {
  39203. this.setIndices(indices, null, true);
  39204. }
  39205. else {
  39206. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39207. }
  39208. };
  39209. /**
  39210. * Creates a new index buffer
  39211. * @param indices defines the indices to store in the index buffer
  39212. * @param totalVertices defines the total number of vertices (could be null)
  39213. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39214. */
  39215. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39216. if (totalVertices === void 0) { totalVertices = null; }
  39217. if (updatable === void 0) { updatable = false; }
  39218. if (this._indexBuffer) {
  39219. this._engine._releaseBuffer(this._indexBuffer);
  39220. }
  39221. this._disposeVertexArrayObjects();
  39222. this._indices = indices;
  39223. this._indexBufferIsUpdatable = updatable;
  39224. if (this._meshes.length !== 0 && this._indices) {
  39225. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39226. }
  39227. if (totalVertices != undefined) { // including null and undefined
  39228. this._totalVertices = totalVertices;
  39229. }
  39230. var meshes = this._meshes;
  39231. var numOfMeshes = meshes.length;
  39232. for (var index = 0; index < numOfMeshes; index++) {
  39233. meshes[index]._createGlobalSubMesh(true);
  39234. }
  39235. this.notifyUpdate();
  39236. };
  39237. /**
  39238. * Return the total number of indices
  39239. * @returns the total number of indices
  39240. */
  39241. Geometry.prototype.getTotalIndices = function () {
  39242. if (!this.isReady()) {
  39243. return 0;
  39244. }
  39245. return this._indices.length;
  39246. };
  39247. /**
  39248. * Gets the index buffer array
  39249. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39250. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39251. * @returns the index buffer array
  39252. */
  39253. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39254. if (!this.isReady()) {
  39255. return null;
  39256. }
  39257. var orig = this._indices;
  39258. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39259. return orig;
  39260. }
  39261. else {
  39262. var len = orig.length;
  39263. var copy = [];
  39264. for (var i = 0; i < len; i++) {
  39265. copy.push(orig[i]);
  39266. }
  39267. return copy;
  39268. }
  39269. };
  39270. /**
  39271. * Gets the index buffer
  39272. * @return the index buffer
  39273. */
  39274. Geometry.prototype.getIndexBuffer = function () {
  39275. if (!this.isReady()) {
  39276. return null;
  39277. }
  39278. return this._indexBuffer;
  39279. };
  39280. /** @hidden */
  39281. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39282. if (effect === void 0) { effect = null; }
  39283. if (!effect || !this._vertexArrayObjects) {
  39284. return;
  39285. }
  39286. if (this._vertexArrayObjects[effect.key]) {
  39287. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39288. delete this._vertexArrayObjects[effect.key];
  39289. }
  39290. };
  39291. /**
  39292. * Release the associated resources for a specific mesh
  39293. * @param mesh defines the source mesh
  39294. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39295. */
  39296. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39297. var meshes = this._meshes;
  39298. var index = meshes.indexOf(mesh);
  39299. if (index === -1) {
  39300. return;
  39301. }
  39302. meshes.splice(index, 1);
  39303. mesh._geometry = null;
  39304. if (meshes.length === 0 && shouldDispose) {
  39305. this.dispose();
  39306. }
  39307. };
  39308. /**
  39309. * Apply current geometry to a given mesh
  39310. * @param mesh defines the mesh to apply geometry to
  39311. */
  39312. Geometry.prototype.applyToMesh = function (mesh) {
  39313. if (mesh._geometry === this) {
  39314. return;
  39315. }
  39316. var previousGeometry = mesh._geometry;
  39317. if (previousGeometry) {
  39318. previousGeometry.releaseForMesh(mesh);
  39319. }
  39320. var meshes = this._meshes;
  39321. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39322. mesh._geometry = this;
  39323. this._scene.pushGeometry(this);
  39324. meshes.push(mesh);
  39325. if (this.isReady()) {
  39326. this._applyToMesh(mesh);
  39327. }
  39328. else {
  39329. mesh._boundingInfo = this._boundingInfo;
  39330. }
  39331. };
  39332. Geometry.prototype._updateExtend = function (data) {
  39333. if (data === void 0) { data = null; }
  39334. if (!data) {
  39335. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39336. }
  39337. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39338. };
  39339. Geometry.prototype._applyToMesh = function (mesh) {
  39340. var numOfMeshes = this._meshes.length;
  39341. // vertexBuffers
  39342. for (var kind in this._vertexBuffers) {
  39343. if (numOfMeshes === 1) {
  39344. this._vertexBuffers[kind].create();
  39345. }
  39346. var buffer = this._vertexBuffers[kind].getBuffer();
  39347. if (buffer)
  39348. buffer.references = numOfMeshes;
  39349. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39350. if (!this._extend) {
  39351. this._updateExtend();
  39352. }
  39353. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39354. mesh._createGlobalSubMesh(false);
  39355. //bounding info was just created again, world matrix should be applied again.
  39356. mesh._updateBoundingInfo();
  39357. }
  39358. }
  39359. // indexBuffer
  39360. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39361. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39362. }
  39363. if (this._indexBuffer) {
  39364. this._indexBuffer.references = numOfMeshes;
  39365. }
  39366. };
  39367. Geometry.prototype.notifyUpdate = function (kind) {
  39368. if (this.onGeometryUpdated) {
  39369. this.onGeometryUpdated(this, kind);
  39370. }
  39371. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39372. var mesh = _a[_i];
  39373. mesh._markSubMeshesAsAttributesDirty();
  39374. }
  39375. };
  39376. /**
  39377. * Load the geometry if it was flagged as delay loaded
  39378. * @param scene defines the hosting scene
  39379. * @param onLoaded defines a callback called when the geometry is loaded
  39380. */
  39381. Geometry.prototype.load = function (scene, onLoaded) {
  39382. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39383. return;
  39384. }
  39385. if (this.isReady()) {
  39386. if (onLoaded) {
  39387. onLoaded();
  39388. }
  39389. return;
  39390. }
  39391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39392. this._queueLoad(scene, onLoaded);
  39393. };
  39394. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39395. var _this = this;
  39396. if (!this.delayLoadingFile) {
  39397. return;
  39398. }
  39399. scene._addPendingData(this);
  39400. scene._loadFile(this.delayLoadingFile, function (data) {
  39401. if (!_this._delayLoadingFunction) {
  39402. return;
  39403. }
  39404. _this._delayLoadingFunction(JSON.parse(data), _this);
  39405. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39406. _this._delayInfo = [];
  39407. scene._removePendingData(_this);
  39408. var meshes = _this._meshes;
  39409. var numOfMeshes = meshes.length;
  39410. for (var index = 0; index < numOfMeshes; index++) {
  39411. _this._applyToMesh(meshes[index]);
  39412. }
  39413. if (onLoaded) {
  39414. onLoaded();
  39415. }
  39416. }, undefined, true);
  39417. };
  39418. /**
  39419. * Invert the geometry to move from a right handed system to a left handed one.
  39420. */
  39421. Geometry.prototype.toLeftHanded = function () {
  39422. // Flip faces
  39423. var tIndices = this.getIndices(false);
  39424. if (tIndices != null && tIndices.length > 0) {
  39425. for (var i = 0; i < tIndices.length; i += 3) {
  39426. var tTemp = tIndices[i + 0];
  39427. tIndices[i + 0] = tIndices[i + 2];
  39428. tIndices[i + 2] = tTemp;
  39429. }
  39430. this.setIndices(tIndices);
  39431. }
  39432. // Negate position.z
  39433. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39434. if (tPositions != null && tPositions.length > 0) {
  39435. for (var i = 0; i < tPositions.length; i += 3) {
  39436. tPositions[i + 2] = -tPositions[i + 2];
  39437. }
  39438. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39439. }
  39440. // Negate normal.z
  39441. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39442. if (tNormals != null && tNormals.length > 0) {
  39443. for (var i = 0; i < tNormals.length; i += 3) {
  39444. tNormals[i + 2] = -tNormals[i + 2];
  39445. }
  39446. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39447. }
  39448. };
  39449. // Cache
  39450. /** @hidden */
  39451. Geometry.prototype._resetPointsArrayCache = function () {
  39452. this._positions = null;
  39453. };
  39454. /** @hidden */
  39455. Geometry.prototype._generatePointsArray = function () {
  39456. if (this._positions)
  39457. return true;
  39458. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39459. if (!data || data.length === 0) {
  39460. return false;
  39461. }
  39462. this._positions = [];
  39463. for (var index = 0; index < data.length; index += 3) {
  39464. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39465. }
  39466. return true;
  39467. };
  39468. /**
  39469. * Gets a value indicating if the geometry is disposed
  39470. * @returns true if the geometry was disposed
  39471. */
  39472. Geometry.prototype.isDisposed = function () {
  39473. return this._isDisposed;
  39474. };
  39475. Geometry.prototype._disposeVertexArrayObjects = function () {
  39476. if (this._vertexArrayObjects) {
  39477. for (var kind in this._vertexArrayObjects) {
  39478. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39479. }
  39480. this._vertexArrayObjects = {};
  39481. }
  39482. };
  39483. /**
  39484. * Free all associated resources
  39485. */
  39486. Geometry.prototype.dispose = function () {
  39487. var meshes = this._meshes;
  39488. var numOfMeshes = meshes.length;
  39489. var index;
  39490. for (index = 0; index < numOfMeshes; index++) {
  39491. this.releaseForMesh(meshes[index]);
  39492. }
  39493. this._meshes = [];
  39494. this._disposeVertexArrayObjects();
  39495. for (var kind in this._vertexBuffers) {
  39496. this._vertexBuffers[kind].dispose();
  39497. }
  39498. this._vertexBuffers = {};
  39499. this._totalVertices = 0;
  39500. if (this._indexBuffer) {
  39501. this._engine._releaseBuffer(this._indexBuffer);
  39502. }
  39503. this._indexBuffer = null;
  39504. this._indices = [];
  39505. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39506. this.delayLoadingFile = null;
  39507. this._delayLoadingFunction = null;
  39508. this._delayInfo = [];
  39509. this._boundingInfo = null;
  39510. this._scene.removeGeometry(this);
  39511. this._isDisposed = true;
  39512. };
  39513. /**
  39514. * Clone the current geometry into a new geometry
  39515. * @param id defines the unique ID of the new geometry
  39516. * @returns a new geometry object
  39517. */
  39518. Geometry.prototype.copy = function (id) {
  39519. var vertexData = new BABYLON.VertexData();
  39520. vertexData.indices = [];
  39521. var indices = this.getIndices();
  39522. if (indices) {
  39523. for (var index = 0; index < indices.length; index++) {
  39524. vertexData.indices.push(indices[index]);
  39525. }
  39526. }
  39527. var updatable = false;
  39528. var stopChecking = false;
  39529. var kind;
  39530. for (kind in this._vertexBuffers) {
  39531. // using slice() to make a copy of the array and not just reference it
  39532. var data = this.getVerticesData(kind);
  39533. if (data instanceof Float32Array) {
  39534. vertexData.set(new Float32Array(data), kind);
  39535. }
  39536. else {
  39537. vertexData.set(data.slice(0), kind);
  39538. }
  39539. if (!stopChecking) {
  39540. var vb = this.getVertexBuffer(kind);
  39541. if (vb) {
  39542. updatable = vb.isUpdatable();
  39543. stopChecking = !updatable;
  39544. }
  39545. }
  39546. }
  39547. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39548. geometry.delayLoadState = this.delayLoadState;
  39549. geometry.delayLoadingFile = this.delayLoadingFile;
  39550. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39551. for (kind in this._delayInfo) {
  39552. geometry._delayInfo = geometry._delayInfo || [];
  39553. geometry._delayInfo.push(kind);
  39554. }
  39555. // Bounding info
  39556. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39557. return geometry;
  39558. };
  39559. /**
  39560. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39561. * @return a JSON representation of the current geometry data (without the vertices data)
  39562. */
  39563. Geometry.prototype.serialize = function () {
  39564. var serializationObject = {};
  39565. serializationObject.id = this.id;
  39566. serializationObject.updatable = this._updatable;
  39567. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39568. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39569. }
  39570. return serializationObject;
  39571. };
  39572. Geometry.prototype.toNumberArray = function (origin) {
  39573. if (Array.isArray(origin)) {
  39574. return origin;
  39575. }
  39576. else {
  39577. return Array.prototype.slice.call(origin);
  39578. }
  39579. };
  39580. /**
  39581. * Serialize all vertices data into a JSON oject
  39582. * @returns a JSON representation of the current geometry data
  39583. */
  39584. Geometry.prototype.serializeVerticeData = function () {
  39585. var serializationObject = this.serialize();
  39586. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39587. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39588. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39589. serializationObject.positions._updatable = true;
  39590. }
  39591. }
  39592. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39593. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39594. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39595. serializationObject.normals._updatable = true;
  39596. }
  39597. }
  39598. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39599. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39600. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39601. serializationObject.tangets._updatable = true;
  39602. }
  39603. }
  39604. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39605. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39606. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39607. serializationObject.uvs._updatable = true;
  39608. }
  39609. }
  39610. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39611. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39612. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39613. serializationObject.uv2s._updatable = true;
  39614. }
  39615. }
  39616. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39617. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39618. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39619. serializationObject.uv3s._updatable = true;
  39620. }
  39621. }
  39622. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39623. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39624. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39625. serializationObject.uv4s._updatable = true;
  39626. }
  39627. }
  39628. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39629. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39630. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39631. serializationObject.uv5s._updatable = true;
  39632. }
  39633. }
  39634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39635. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39636. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39637. serializationObject.uv6s._updatable = true;
  39638. }
  39639. }
  39640. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39641. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39642. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39643. serializationObject.colors._updatable = true;
  39644. }
  39645. }
  39646. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39647. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39648. serializationObject.matricesIndices._isExpanded = true;
  39649. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39650. serializationObject.matricesIndices._updatable = true;
  39651. }
  39652. }
  39653. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39654. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39655. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39656. serializationObject.matricesWeights._updatable = true;
  39657. }
  39658. }
  39659. serializationObject.indices = this.toNumberArray(this.getIndices());
  39660. return serializationObject;
  39661. };
  39662. // Statics
  39663. /**
  39664. * Extracts a clone of a mesh geometry
  39665. * @param mesh defines the source mesh
  39666. * @param id defines the unique ID of the new geometry object
  39667. * @returns the new geometry object
  39668. */
  39669. Geometry.ExtractFromMesh = function (mesh, id) {
  39670. var geometry = mesh._geometry;
  39671. if (!geometry) {
  39672. return null;
  39673. }
  39674. return geometry.copy(id);
  39675. };
  39676. /**
  39677. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39678. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39679. * Be aware Math.random() could cause collisions, but:
  39680. * "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"
  39681. * @returns a string containing a new GUID
  39682. */
  39683. Geometry.RandomId = function () {
  39684. return BABYLON.Tools.RandomId();
  39685. };
  39686. /** @hidden */
  39687. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39688. var scene = mesh.getScene();
  39689. // Geometry
  39690. var geometryId = parsedGeometry.geometryId;
  39691. if (geometryId) {
  39692. var geometry = scene.getGeometryByID(geometryId);
  39693. if (geometry) {
  39694. geometry.applyToMesh(mesh);
  39695. }
  39696. }
  39697. else if (parsedGeometry instanceof ArrayBuffer) {
  39698. var binaryInfo = mesh._binaryInfo;
  39699. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39700. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39701. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39702. }
  39703. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39704. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39705. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39706. }
  39707. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39708. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39709. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39710. }
  39711. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39712. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39713. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39714. }
  39715. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39716. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39717. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39718. }
  39719. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39720. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39721. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39722. }
  39723. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39724. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39725. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39726. }
  39727. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39728. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39729. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39730. }
  39731. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39732. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39733. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39734. }
  39735. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39736. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39737. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39738. }
  39739. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39740. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39741. var floatIndices = [];
  39742. for (var i = 0; i < matricesIndicesData.length; i++) {
  39743. var index = matricesIndicesData[i];
  39744. floatIndices.push(index & 0x000000FF);
  39745. floatIndices.push((index & 0x0000FF00) >> 8);
  39746. floatIndices.push((index & 0x00FF0000) >> 16);
  39747. floatIndices.push(index >> 24);
  39748. }
  39749. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39750. }
  39751. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39752. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39753. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39754. }
  39755. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39756. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39757. mesh.setIndices(indicesData, null);
  39758. }
  39759. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39760. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39761. mesh.subMeshes = [];
  39762. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39763. var materialIndex = subMeshesData[(i * 5) + 0];
  39764. var verticesStart = subMeshesData[(i * 5) + 1];
  39765. var verticesCount = subMeshesData[(i * 5) + 2];
  39766. var indexStart = subMeshesData[(i * 5) + 3];
  39767. var indexCount = subMeshesData[(i * 5) + 4];
  39768. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39769. }
  39770. }
  39771. }
  39772. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39773. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39774. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39775. if (parsedGeometry.tangents) {
  39776. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39777. }
  39778. if (parsedGeometry.uvs) {
  39779. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39780. }
  39781. if (parsedGeometry.uvs2) {
  39782. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39783. }
  39784. if (parsedGeometry.uvs3) {
  39785. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39786. }
  39787. if (parsedGeometry.uvs4) {
  39788. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39789. }
  39790. if (parsedGeometry.uvs5) {
  39791. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39792. }
  39793. if (parsedGeometry.uvs6) {
  39794. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39795. }
  39796. if (parsedGeometry.colors) {
  39797. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39798. }
  39799. if (parsedGeometry.matricesIndices) {
  39800. if (!parsedGeometry.matricesIndices._isExpanded) {
  39801. var floatIndices = [];
  39802. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39803. var matricesIndex = parsedGeometry.matricesIndices[i];
  39804. floatIndices.push(matricesIndex & 0x000000FF);
  39805. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39806. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39807. floatIndices.push(matricesIndex >> 24);
  39808. }
  39809. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39810. }
  39811. else {
  39812. delete parsedGeometry.matricesIndices._isExpanded;
  39813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39814. }
  39815. }
  39816. if (parsedGeometry.matricesIndicesExtra) {
  39817. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39818. var floatIndices = [];
  39819. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39820. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39821. floatIndices.push(matricesIndex & 0x000000FF);
  39822. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39823. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39824. floatIndices.push(matricesIndex >> 24);
  39825. }
  39826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39827. }
  39828. else {
  39829. delete parsedGeometry.matricesIndices._isExpanded;
  39830. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39831. }
  39832. }
  39833. if (parsedGeometry.matricesWeights) {
  39834. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39835. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39836. }
  39837. if (parsedGeometry.matricesWeightsExtra) {
  39838. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39839. }
  39840. mesh.setIndices(parsedGeometry.indices, null);
  39841. }
  39842. // SubMeshes
  39843. if (parsedGeometry.subMeshes) {
  39844. mesh.subMeshes = [];
  39845. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39846. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39847. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39848. }
  39849. }
  39850. // Flat shading
  39851. if (mesh._shouldGenerateFlatShading) {
  39852. mesh.convertToFlatShadedMesh();
  39853. delete mesh._shouldGenerateFlatShading;
  39854. }
  39855. // Update
  39856. mesh.computeWorldMatrix(true);
  39857. scene.onMeshImportedObservable.notifyObservers(mesh);
  39858. };
  39859. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39860. var epsilon = 1e-3;
  39861. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39862. return;
  39863. }
  39864. var noInfluenceBoneIndex = 0.0;
  39865. if (parsedGeometry.skeletonId > -1) {
  39866. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39867. if (!skeleton) {
  39868. return;
  39869. }
  39870. noInfluenceBoneIndex = skeleton.bones.length;
  39871. }
  39872. else {
  39873. return;
  39874. }
  39875. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39876. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39877. var matricesWeights = parsedGeometry.matricesWeights;
  39878. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39879. var influencers = parsedGeometry.numBoneInfluencer;
  39880. var size = matricesWeights.length;
  39881. for (var i = 0; i < size; i += 4) {
  39882. var weight = 0.0;
  39883. var firstZeroWeight = -1;
  39884. for (var j = 0; j < 4; j++) {
  39885. var w = matricesWeights[i + j];
  39886. weight += w;
  39887. if (w < epsilon && firstZeroWeight < 0) {
  39888. firstZeroWeight = j;
  39889. }
  39890. }
  39891. if (matricesWeightsExtra) {
  39892. for (var j = 0; j < 4; j++) {
  39893. var w = matricesWeightsExtra[i + j];
  39894. weight += w;
  39895. if (w < epsilon && firstZeroWeight < 0) {
  39896. firstZeroWeight = j + 4;
  39897. }
  39898. }
  39899. }
  39900. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39901. firstZeroWeight = influencers - 1;
  39902. }
  39903. if (weight > epsilon) {
  39904. var mweight = 1.0 / weight;
  39905. for (var j = 0; j < 4; j++) {
  39906. matricesWeights[i + j] *= mweight;
  39907. }
  39908. if (matricesWeightsExtra) {
  39909. for (var j = 0; j < 4; j++) {
  39910. matricesWeightsExtra[i + j] *= mweight;
  39911. }
  39912. }
  39913. }
  39914. else {
  39915. if (firstZeroWeight >= 4) {
  39916. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39917. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39918. }
  39919. else {
  39920. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39921. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39922. }
  39923. }
  39924. }
  39925. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39926. if (parsedGeometry.matricesWeightsExtra) {
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39928. }
  39929. };
  39930. /**
  39931. * Create a new geometry from persisted data (Using .babylon file format)
  39932. * @param parsedVertexData defines the persisted data
  39933. * @param scene defines the hosting scene
  39934. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39935. * @returns the new geometry object
  39936. */
  39937. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39938. if (scene.getGeometryByID(parsedVertexData.id)) {
  39939. return null; // null since geometry could be something else than a box...
  39940. }
  39941. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39942. if (BABYLON.Tags) {
  39943. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39944. }
  39945. if (parsedVertexData.delayLoadingFile) {
  39946. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39947. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39948. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39949. geometry._delayInfo = [];
  39950. if (parsedVertexData.hasUVs) {
  39951. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39952. }
  39953. if (parsedVertexData.hasUVs2) {
  39954. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39955. }
  39956. if (parsedVertexData.hasUVs3) {
  39957. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39958. }
  39959. if (parsedVertexData.hasUVs4) {
  39960. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39961. }
  39962. if (parsedVertexData.hasUVs5) {
  39963. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39964. }
  39965. if (parsedVertexData.hasUVs6) {
  39966. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39967. }
  39968. if (parsedVertexData.hasColors) {
  39969. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39970. }
  39971. if (parsedVertexData.hasMatricesIndices) {
  39972. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39973. }
  39974. if (parsedVertexData.hasMatricesWeights) {
  39975. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39976. }
  39977. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39978. }
  39979. else {
  39980. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39981. }
  39982. scene.pushGeometry(geometry, true);
  39983. return geometry;
  39984. };
  39985. return Geometry;
  39986. }());
  39987. BABYLON.Geometry = Geometry;
  39988. // Primitives
  39989. /// Abstract class
  39990. /**
  39991. * Abstract class used to provide common services for all typed geometries
  39992. * @hidden
  39993. */
  39994. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39995. __extends(_PrimitiveGeometry, _super);
  39996. /**
  39997. * Creates a new typed geometry
  39998. * @param id defines the unique ID of the geometry
  39999. * @param scene defines the hosting scene
  40000. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40001. * @param mesh defines the hosting mesh (can be null)
  40002. */
  40003. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40004. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40005. if (mesh === void 0) { mesh = null; }
  40006. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40007. _this._canBeRegenerated = _canBeRegenerated;
  40008. _this._beingRegenerated = true;
  40009. _this.regenerate();
  40010. _this._beingRegenerated = false;
  40011. return _this;
  40012. }
  40013. /**
  40014. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40015. * @returns true if the geometry can be regenerated
  40016. */
  40017. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40018. return this._canBeRegenerated;
  40019. };
  40020. /**
  40021. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40022. */
  40023. _PrimitiveGeometry.prototype.regenerate = function () {
  40024. if (!this._canBeRegenerated) {
  40025. return;
  40026. }
  40027. this._beingRegenerated = true;
  40028. this.setAllVerticesData(this._regenerateVertexData(), false);
  40029. this._beingRegenerated = false;
  40030. };
  40031. /**
  40032. * Clone the geometry
  40033. * @param id defines the unique ID of the new geometry
  40034. * @returns the new geometry
  40035. */
  40036. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40037. return _super.prototype.copy.call(this, id);
  40038. };
  40039. // overrides
  40040. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40041. if (!this._beingRegenerated) {
  40042. return;
  40043. }
  40044. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40045. };
  40046. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40047. if (!this._beingRegenerated) {
  40048. return;
  40049. }
  40050. _super.prototype.setVerticesData.call(this, kind, data, false);
  40051. };
  40052. // to override
  40053. /** @hidden */
  40054. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40055. throw new Error("Abstract method");
  40056. };
  40057. _PrimitiveGeometry.prototype.copy = function (id) {
  40058. throw new Error("Must be overriden in sub-classes.");
  40059. };
  40060. _PrimitiveGeometry.prototype.serialize = function () {
  40061. var serializationObject = _super.prototype.serialize.call(this);
  40062. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40063. return serializationObject;
  40064. };
  40065. return _PrimitiveGeometry;
  40066. }(Geometry));
  40067. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40068. /**
  40069. * Creates a ribbon geometry
  40070. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40071. */
  40072. var RibbonGeometry = /** @class */ (function (_super) {
  40073. __extends(RibbonGeometry, _super);
  40074. /**
  40075. * Creates a ribbon geometry
  40076. * @param id defines the unique ID of the geometry
  40077. * @param scene defines the hosting scene
  40078. * @param pathArray defines the array of paths to use
  40079. * @param closeArray defines if the last path and the first path must be joined
  40080. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40081. * @param offset defines the offset between points
  40082. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40083. * @param mesh defines the hosting mesh (can be null)
  40084. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40085. */
  40086. function RibbonGeometry(id, scene,
  40087. /**
  40088. * Defines the array of paths to use
  40089. */
  40090. pathArray,
  40091. /**
  40092. * Defines if the last and first points of each path in your pathArray must be joined
  40093. */
  40094. closeArray,
  40095. /**
  40096. * Defines if the last and first points of each path in your pathArray must be joined
  40097. */
  40098. closePath,
  40099. /**
  40100. * Defines the offset between points
  40101. */
  40102. offset, canBeRegenerated, mesh,
  40103. /**
  40104. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40105. */
  40106. side) {
  40107. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40108. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40109. _this.pathArray = pathArray;
  40110. _this.closeArray = closeArray;
  40111. _this.closePath = closePath;
  40112. _this.offset = offset;
  40113. _this.side = side;
  40114. return _this;
  40115. }
  40116. /** @hidden */
  40117. RibbonGeometry.prototype._regenerateVertexData = function () {
  40118. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40119. };
  40120. RibbonGeometry.prototype.copy = function (id) {
  40121. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40122. };
  40123. return RibbonGeometry;
  40124. }(_PrimitiveGeometry));
  40125. BABYLON.RibbonGeometry = RibbonGeometry;
  40126. /**
  40127. * Creates a box geometry
  40128. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40129. */
  40130. var BoxGeometry = /** @class */ (function (_super) {
  40131. __extends(BoxGeometry, _super);
  40132. /**
  40133. * Creates a box geometry
  40134. * @param id defines the unique ID of the geometry
  40135. * @param scene defines the hosting scene
  40136. * @param size defines the zise of the box (width, height and depth are the same)
  40137. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40138. * @param mesh defines the hosting mesh (can be null)
  40139. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40140. */
  40141. function BoxGeometry(id, scene,
  40142. /**
  40143. * Defines the zise of the box (width, height and depth are the same)
  40144. */
  40145. size, canBeRegenerated, mesh,
  40146. /**
  40147. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40148. */
  40149. side) {
  40150. if (mesh === void 0) { mesh = null; }
  40151. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40152. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40153. _this.size = size;
  40154. _this.side = side;
  40155. return _this;
  40156. }
  40157. /** @hidden */
  40158. BoxGeometry.prototype._regenerateVertexData = function () {
  40159. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40160. };
  40161. BoxGeometry.prototype.copy = function (id) {
  40162. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40163. };
  40164. BoxGeometry.prototype.serialize = function () {
  40165. var serializationObject = _super.prototype.serialize.call(this);
  40166. serializationObject.size = this.size;
  40167. return serializationObject;
  40168. };
  40169. BoxGeometry.Parse = function (parsedBox, scene) {
  40170. if (scene.getGeometryByID(parsedBox.id)) {
  40171. return null; // null since geometry could be something else than a box...
  40172. }
  40173. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40174. if (BABYLON.Tags) {
  40175. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40176. }
  40177. scene.pushGeometry(box, true);
  40178. return box;
  40179. };
  40180. return BoxGeometry;
  40181. }(_PrimitiveGeometry));
  40182. BABYLON.BoxGeometry = BoxGeometry;
  40183. /**
  40184. * Creates a sphere geometry
  40185. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40186. */
  40187. var SphereGeometry = /** @class */ (function (_super) {
  40188. __extends(SphereGeometry, _super);
  40189. /**
  40190. * Create a new sphere geometry
  40191. * @param id defines the unique ID of the geometry
  40192. * @param scene defines the hosting scene
  40193. * @param segments defines the number of segments to use to create the sphere
  40194. * @param diameter defines the diameter of the sphere
  40195. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40196. * @param mesh defines the hosting mesh (can be null)
  40197. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40198. */
  40199. function SphereGeometry(id, scene,
  40200. /**
  40201. * Defines the number of segments to use to create the sphere
  40202. */
  40203. segments,
  40204. /**
  40205. * Defines the diameter of the sphere
  40206. */
  40207. diameter, canBeRegenerated, mesh,
  40208. /**
  40209. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40210. */
  40211. side) {
  40212. if (mesh === void 0) { mesh = null; }
  40213. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40214. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40215. _this.segments = segments;
  40216. _this.diameter = diameter;
  40217. _this.side = side;
  40218. return _this;
  40219. }
  40220. /** @hidden */
  40221. SphereGeometry.prototype._regenerateVertexData = function () {
  40222. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40223. };
  40224. SphereGeometry.prototype.copy = function (id) {
  40225. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40226. };
  40227. SphereGeometry.prototype.serialize = function () {
  40228. var serializationObject = _super.prototype.serialize.call(this);
  40229. serializationObject.segments = this.segments;
  40230. serializationObject.diameter = this.diameter;
  40231. return serializationObject;
  40232. };
  40233. SphereGeometry.Parse = function (parsedSphere, scene) {
  40234. if (scene.getGeometryByID(parsedSphere.id)) {
  40235. return null; // null since geometry could be something else than a sphere...
  40236. }
  40237. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40238. if (BABYLON.Tags) {
  40239. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40240. }
  40241. scene.pushGeometry(sphere, true);
  40242. return sphere;
  40243. };
  40244. return SphereGeometry;
  40245. }(_PrimitiveGeometry));
  40246. BABYLON.SphereGeometry = SphereGeometry;
  40247. /**
  40248. * Creates a disc geometry
  40249. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40250. */
  40251. var DiscGeometry = /** @class */ (function (_super) {
  40252. __extends(DiscGeometry, _super);
  40253. /**
  40254. * Creates a new disc geometry
  40255. * @param id defines the unique ID of the geometry
  40256. * @param scene defines the hosting scene
  40257. * @param radius defines the radius of the disc
  40258. * @param tessellation defines the tesselation factor to apply to the disc
  40259. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40260. * @param mesh defines the hosting mesh (can be null)
  40261. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40262. */
  40263. function DiscGeometry(id, scene,
  40264. /**
  40265. * Defines the radius of the disc
  40266. */
  40267. radius,
  40268. /**
  40269. * Defines the tesselation factor to apply to the disc
  40270. */
  40271. tessellation, canBeRegenerated, mesh,
  40272. /**
  40273. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40274. */
  40275. side) {
  40276. if (mesh === void 0) { mesh = null; }
  40277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40278. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40279. _this.radius = radius;
  40280. _this.tessellation = tessellation;
  40281. _this.side = side;
  40282. return _this;
  40283. }
  40284. /** @hidden */
  40285. DiscGeometry.prototype._regenerateVertexData = function () {
  40286. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40287. };
  40288. DiscGeometry.prototype.copy = function (id) {
  40289. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40290. };
  40291. return DiscGeometry;
  40292. }(_PrimitiveGeometry));
  40293. BABYLON.DiscGeometry = DiscGeometry;
  40294. /**
  40295. * Creates a new cylinder geometry
  40296. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40297. */
  40298. var CylinderGeometry = /** @class */ (function (_super) {
  40299. __extends(CylinderGeometry, _super);
  40300. /**
  40301. * Creates a new cylinder geometry
  40302. * @param id defines the unique ID of the geometry
  40303. * @param scene defines the hosting scene
  40304. * @param height defines the height of the cylinder
  40305. * @param diameterTop defines the diameter of the cylinder's top cap
  40306. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40307. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40308. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40309. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40310. * @param mesh defines the hosting mesh (can be null)
  40311. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40312. */
  40313. function CylinderGeometry(id, scene,
  40314. /**
  40315. * Defines the height of the cylinder
  40316. */
  40317. height,
  40318. /**
  40319. * Defines the diameter of the cylinder's top cap
  40320. */
  40321. diameterTop,
  40322. /**
  40323. * Defines the diameter of the cylinder's bottom cap
  40324. */
  40325. diameterBottom,
  40326. /**
  40327. * Defines the tessellation factor to apply to the cylinder
  40328. */
  40329. tessellation,
  40330. /**
  40331. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40332. */
  40333. subdivisions, canBeRegenerated, mesh,
  40334. /**
  40335. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40336. */
  40337. side) {
  40338. if (subdivisions === void 0) { subdivisions = 1; }
  40339. if (mesh === void 0) { mesh = null; }
  40340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40342. _this.height = height;
  40343. _this.diameterTop = diameterTop;
  40344. _this.diameterBottom = diameterBottom;
  40345. _this.tessellation = tessellation;
  40346. _this.subdivisions = subdivisions;
  40347. _this.side = side;
  40348. return _this;
  40349. }
  40350. /** @hidden */
  40351. CylinderGeometry.prototype._regenerateVertexData = function () {
  40352. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40353. };
  40354. CylinderGeometry.prototype.copy = function (id) {
  40355. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40356. };
  40357. CylinderGeometry.prototype.serialize = function () {
  40358. var serializationObject = _super.prototype.serialize.call(this);
  40359. serializationObject.height = this.height;
  40360. serializationObject.diameterTop = this.diameterTop;
  40361. serializationObject.diameterBottom = this.diameterBottom;
  40362. serializationObject.tessellation = this.tessellation;
  40363. return serializationObject;
  40364. };
  40365. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40366. if (scene.getGeometryByID(parsedCylinder.id)) {
  40367. return null; // null since geometry could be something else than a cylinder...
  40368. }
  40369. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40370. if (BABYLON.Tags) {
  40371. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40372. }
  40373. scene.pushGeometry(cylinder, true);
  40374. return cylinder;
  40375. };
  40376. return CylinderGeometry;
  40377. }(_PrimitiveGeometry));
  40378. BABYLON.CylinderGeometry = CylinderGeometry;
  40379. /**
  40380. * Creates a new torus geometry
  40381. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40382. */
  40383. var TorusGeometry = /** @class */ (function (_super) {
  40384. __extends(TorusGeometry, _super);
  40385. /**
  40386. * Creates a new torus geometry
  40387. * @param id defines the unique ID of the geometry
  40388. * @param scene defines the hosting scene
  40389. * @param diameter defines the diameter of the torus
  40390. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40391. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40392. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40393. * @param mesh defines the hosting mesh (can be null)
  40394. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40395. */
  40396. function TorusGeometry(id, scene,
  40397. /**
  40398. * Defines the diameter of the torus
  40399. */
  40400. diameter,
  40401. /**
  40402. * Defines the thickness of the torus (ie. internal diameter)
  40403. */
  40404. thickness,
  40405. /**
  40406. * Defines the tesselation factor to apply to the torus
  40407. */
  40408. tessellation, canBeRegenerated, mesh,
  40409. /**
  40410. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40411. */
  40412. side) {
  40413. if (mesh === void 0) { mesh = null; }
  40414. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40415. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40416. _this.diameter = diameter;
  40417. _this.thickness = thickness;
  40418. _this.tessellation = tessellation;
  40419. _this.side = side;
  40420. return _this;
  40421. }
  40422. /** @hidden */
  40423. TorusGeometry.prototype._regenerateVertexData = function () {
  40424. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40425. };
  40426. TorusGeometry.prototype.copy = function (id) {
  40427. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40428. };
  40429. TorusGeometry.prototype.serialize = function () {
  40430. var serializationObject = _super.prototype.serialize.call(this);
  40431. serializationObject.diameter = this.diameter;
  40432. serializationObject.thickness = this.thickness;
  40433. serializationObject.tessellation = this.tessellation;
  40434. return serializationObject;
  40435. };
  40436. TorusGeometry.Parse = function (parsedTorus, scene) {
  40437. if (scene.getGeometryByID(parsedTorus.id)) {
  40438. return null; // null since geometry could be something else than a torus...
  40439. }
  40440. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40441. if (BABYLON.Tags) {
  40442. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40443. }
  40444. scene.pushGeometry(torus, true);
  40445. return torus;
  40446. };
  40447. return TorusGeometry;
  40448. }(_PrimitiveGeometry));
  40449. BABYLON.TorusGeometry = TorusGeometry;
  40450. /**
  40451. * Creates a new ground geometry
  40452. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40453. */
  40454. var GroundGeometry = /** @class */ (function (_super) {
  40455. __extends(GroundGeometry, _super);
  40456. /**
  40457. * Creates a new ground geometry
  40458. * @param id defines the unique ID of the geometry
  40459. * @param scene defines the hosting scene
  40460. * @param width defines the width of the ground
  40461. * @param height defines the height of the ground
  40462. * @param subdivisions defines the subdivisions to apply to the ground
  40463. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40464. * @param mesh defines the hosting mesh (can be null)
  40465. */
  40466. function GroundGeometry(id, scene,
  40467. /**
  40468. * Defines the width of the ground
  40469. */
  40470. width,
  40471. /**
  40472. * Defines the height of the ground
  40473. */
  40474. height,
  40475. /**
  40476. * Defines the subdivisions to apply to the ground
  40477. */
  40478. subdivisions, canBeRegenerated, mesh) {
  40479. if (mesh === void 0) { mesh = null; }
  40480. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40481. _this.width = width;
  40482. _this.height = height;
  40483. _this.subdivisions = subdivisions;
  40484. return _this;
  40485. }
  40486. /** @hidden */
  40487. GroundGeometry.prototype._regenerateVertexData = function () {
  40488. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40489. };
  40490. GroundGeometry.prototype.copy = function (id) {
  40491. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40492. };
  40493. GroundGeometry.prototype.serialize = function () {
  40494. var serializationObject = _super.prototype.serialize.call(this);
  40495. serializationObject.width = this.width;
  40496. serializationObject.height = this.height;
  40497. serializationObject.subdivisions = this.subdivisions;
  40498. return serializationObject;
  40499. };
  40500. GroundGeometry.Parse = function (parsedGround, scene) {
  40501. if (scene.getGeometryByID(parsedGround.id)) {
  40502. return null; // null since geometry could be something else than a ground...
  40503. }
  40504. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40505. if (BABYLON.Tags) {
  40506. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40507. }
  40508. scene.pushGeometry(ground, true);
  40509. return ground;
  40510. };
  40511. return GroundGeometry;
  40512. }(_PrimitiveGeometry));
  40513. BABYLON.GroundGeometry = GroundGeometry;
  40514. /**
  40515. * Creates a tiled ground geometry
  40516. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40517. */
  40518. var TiledGroundGeometry = /** @class */ (function (_super) {
  40519. __extends(TiledGroundGeometry, _super);
  40520. /**
  40521. * Creates a tiled ground geometry
  40522. * @param id defines the unique ID of the geometry
  40523. * @param scene defines the hosting scene
  40524. * @param xmin defines the minimum value on X axis
  40525. * @param zmin defines the minimum value on Z axis
  40526. * @param xmax defines the maximum value on X axis
  40527. * @param zmax defines the maximum value on Z axis
  40528. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40529. * @param precision defines the precision to use when computing the tiles
  40530. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40531. * @param mesh defines the hosting mesh (can be null)
  40532. */
  40533. function TiledGroundGeometry(id, scene,
  40534. /**
  40535. * Defines the minimum value on X axis
  40536. */
  40537. xmin,
  40538. /**
  40539. * Defines the minimum value on Z axis
  40540. */
  40541. zmin,
  40542. /**
  40543. * Defines the maximum value on X axis
  40544. */
  40545. xmax,
  40546. /**
  40547. * Defines the maximum value on Z axis
  40548. */
  40549. zmax,
  40550. /**
  40551. * Defines the subdivisions to apply to the ground
  40552. */
  40553. subdivisions,
  40554. /**
  40555. * Defines the precision to use when computing the tiles
  40556. */
  40557. precision, canBeRegenerated, mesh) {
  40558. if (mesh === void 0) { mesh = null; }
  40559. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40560. _this.xmin = xmin;
  40561. _this.zmin = zmin;
  40562. _this.xmax = xmax;
  40563. _this.zmax = zmax;
  40564. _this.subdivisions = subdivisions;
  40565. _this.precision = precision;
  40566. return _this;
  40567. }
  40568. /** @hidden */
  40569. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40570. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40571. };
  40572. TiledGroundGeometry.prototype.copy = function (id) {
  40573. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40574. };
  40575. return TiledGroundGeometry;
  40576. }(_PrimitiveGeometry));
  40577. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40578. /**
  40579. * Creates a plane geometry
  40580. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40581. */
  40582. var PlaneGeometry = /** @class */ (function (_super) {
  40583. __extends(PlaneGeometry, _super);
  40584. /**
  40585. * Creates a plane geometry
  40586. * @param id defines the unique ID of the geometry
  40587. * @param scene defines the hosting scene
  40588. * @param size defines the size of the plane (width === height)
  40589. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40590. * @param mesh defines the hosting mesh (can be null)
  40591. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40592. */
  40593. function PlaneGeometry(id, scene,
  40594. /**
  40595. * Defines the size of the plane (width === height)
  40596. */
  40597. size, canBeRegenerated, mesh,
  40598. /**
  40599. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40600. */
  40601. side) {
  40602. if (mesh === void 0) { mesh = null; }
  40603. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40604. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40605. _this.size = size;
  40606. _this.side = side;
  40607. return _this;
  40608. }
  40609. /** @hidden */
  40610. PlaneGeometry.prototype._regenerateVertexData = function () {
  40611. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40612. };
  40613. PlaneGeometry.prototype.copy = function (id) {
  40614. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40615. };
  40616. PlaneGeometry.prototype.serialize = function () {
  40617. var serializationObject = _super.prototype.serialize.call(this);
  40618. serializationObject.size = this.size;
  40619. return serializationObject;
  40620. };
  40621. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40622. if (scene.getGeometryByID(parsedPlane.id)) {
  40623. return null; // null since geometry could be something else than a ground...
  40624. }
  40625. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40626. if (BABYLON.Tags) {
  40627. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40628. }
  40629. scene.pushGeometry(plane, true);
  40630. return plane;
  40631. };
  40632. return PlaneGeometry;
  40633. }(_PrimitiveGeometry));
  40634. BABYLON.PlaneGeometry = PlaneGeometry;
  40635. /**
  40636. * Creates a torus knot geometry
  40637. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40638. */
  40639. var TorusKnotGeometry = /** @class */ (function (_super) {
  40640. __extends(TorusKnotGeometry, _super);
  40641. /**
  40642. * Creates a torus knot geometry
  40643. * @param id defines the unique ID of the geometry
  40644. * @param scene defines the hosting scene
  40645. * @param radius defines the radius of the torus knot
  40646. * @param tube defines the thickness of the torus knot tube
  40647. * @param radialSegments defines the number of radial segments
  40648. * @param tubularSegments defines the number of tubular segments
  40649. * @param p defines the first number of windings
  40650. * @param q defines the second number of windings
  40651. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40652. * @param mesh defines the hosting mesh (can be null)
  40653. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40654. */
  40655. function TorusKnotGeometry(id, scene,
  40656. /**
  40657. * Defines the radius of the torus knot
  40658. */
  40659. radius,
  40660. /**
  40661. * Defines the thickness of the torus knot tube
  40662. */
  40663. tube,
  40664. /**
  40665. * Defines the number of radial segments
  40666. */
  40667. radialSegments,
  40668. /**
  40669. * Defines the number of tubular segments
  40670. */
  40671. tubularSegments,
  40672. /**
  40673. * Defines the first number of windings
  40674. */
  40675. p,
  40676. /**
  40677. * Defines the second number of windings
  40678. */
  40679. q, canBeRegenerated, mesh,
  40680. /**
  40681. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40682. */
  40683. side) {
  40684. if (mesh === void 0) { mesh = null; }
  40685. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40686. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40687. _this.radius = radius;
  40688. _this.tube = tube;
  40689. _this.radialSegments = radialSegments;
  40690. _this.tubularSegments = tubularSegments;
  40691. _this.p = p;
  40692. _this.q = q;
  40693. _this.side = side;
  40694. return _this;
  40695. }
  40696. /** @hidden */
  40697. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40698. 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 });
  40699. };
  40700. TorusKnotGeometry.prototype.copy = function (id) {
  40701. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40702. };
  40703. TorusKnotGeometry.prototype.serialize = function () {
  40704. var serializationObject = _super.prototype.serialize.call(this);
  40705. serializationObject.radius = this.radius;
  40706. serializationObject.tube = this.tube;
  40707. serializationObject.radialSegments = this.radialSegments;
  40708. serializationObject.tubularSegments = this.tubularSegments;
  40709. serializationObject.p = this.p;
  40710. serializationObject.q = this.q;
  40711. return serializationObject;
  40712. };
  40713. ;
  40714. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40715. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40716. return null; // null since geometry could be something else than a ground...
  40717. }
  40718. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40719. if (BABYLON.Tags) {
  40720. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40721. }
  40722. scene.pushGeometry(torusKnot, true);
  40723. return torusKnot;
  40724. };
  40725. return TorusKnotGeometry;
  40726. }(_PrimitiveGeometry));
  40727. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40728. //}
  40729. })(BABYLON || (BABYLON = {}));
  40730. //# sourceMappingURL=babylon.geometry.js.map
  40731. var BABYLON;
  40732. (function (BABYLON) {
  40733. /**
  40734. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40735. */
  40736. var PerformanceMonitor = /** @class */ (function () {
  40737. /**
  40738. * constructor
  40739. * @param frameSampleSize The number of samples required to saturate the sliding window
  40740. */
  40741. function PerformanceMonitor(frameSampleSize) {
  40742. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40743. this._enabled = true;
  40744. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40745. }
  40746. /**
  40747. * Samples current frame
  40748. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40749. */
  40750. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40751. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40752. if (!this._enabled)
  40753. return;
  40754. if (this._lastFrameTimeMs != null) {
  40755. var dt = timeMs - this._lastFrameTimeMs;
  40756. this._rollingFrameTime.add(dt);
  40757. }
  40758. this._lastFrameTimeMs = timeMs;
  40759. };
  40760. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40761. /**
  40762. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40763. * @return Average frame time in milliseconds
  40764. */
  40765. get: function () {
  40766. return this._rollingFrameTime.average;
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40772. /**
  40773. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40774. * @return Frame time variance in milliseconds squared
  40775. */
  40776. get: function () {
  40777. return this._rollingFrameTime.variance;
  40778. },
  40779. enumerable: true,
  40780. configurable: true
  40781. });
  40782. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40783. /**
  40784. * Returns the frame time of the most recent frame
  40785. * @return Frame time in milliseconds
  40786. */
  40787. get: function () {
  40788. return this._rollingFrameTime.history(0);
  40789. },
  40790. enumerable: true,
  40791. configurable: true
  40792. });
  40793. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40794. /**
  40795. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40796. * @return Framerate in frames per second
  40797. */
  40798. get: function () {
  40799. return 1000.0 / this._rollingFrameTime.average;
  40800. },
  40801. enumerable: true,
  40802. configurable: true
  40803. });
  40804. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40805. /**
  40806. * Returns the average framerate in frames per second using the most recent frame time
  40807. * @return Framerate in frames per second
  40808. */
  40809. get: function () {
  40810. var history = this._rollingFrameTime.history(0);
  40811. if (history === 0) {
  40812. return 0;
  40813. }
  40814. return 1000.0 / history;
  40815. },
  40816. enumerable: true,
  40817. configurable: true
  40818. });
  40819. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40820. /**
  40821. * Returns true if enough samples have been taken to completely fill the sliding window
  40822. * @return true if saturated
  40823. */
  40824. get: function () {
  40825. return this._rollingFrameTime.isSaturated();
  40826. },
  40827. enumerable: true,
  40828. configurable: true
  40829. });
  40830. /**
  40831. * Enables contributions to the sliding window sample set
  40832. */
  40833. PerformanceMonitor.prototype.enable = function () {
  40834. this._enabled = true;
  40835. };
  40836. /**
  40837. * Disables contributions to the sliding window sample set
  40838. * Samples will not be interpolated over the disabled period
  40839. */
  40840. PerformanceMonitor.prototype.disable = function () {
  40841. this._enabled = false;
  40842. //clear last sample to avoid interpolating over the disabled period when next enabled
  40843. this._lastFrameTimeMs = null;
  40844. };
  40845. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40846. /**
  40847. * Returns true if sampling is enabled
  40848. * @return true if enabled
  40849. */
  40850. get: function () {
  40851. return this._enabled;
  40852. },
  40853. enumerable: true,
  40854. configurable: true
  40855. });
  40856. /**
  40857. * Resets performance monitor
  40858. */
  40859. PerformanceMonitor.prototype.reset = function () {
  40860. //clear last sample to avoid interpolating over the disabled period when next enabled
  40861. this._lastFrameTimeMs = null;
  40862. //wipe record
  40863. this._rollingFrameTime.reset();
  40864. };
  40865. return PerformanceMonitor;
  40866. }());
  40867. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40868. /**
  40869. * RollingAverage
  40870. *
  40871. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40872. */
  40873. var RollingAverage = /** @class */ (function () {
  40874. /**
  40875. * constructor
  40876. * @param length The number of samples required to saturate the sliding window
  40877. */
  40878. function RollingAverage(length) {
  40879. this._samples = new Array(length);
  40880. this.reset();
  40881. }
  40882. /**
  40883. * Adds a sample to the sample set
  40884. * @param v The sample value
  40885. */
  40886. RollingAverage.prototype.add = function (v) {
  40887. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40888. var delta;
  40889. //we need to check if we've already wrapped round
  40890. if (this.isSaturated()) {
  40891. //remove bottom of stack from mean
  40892. var bottomValue = this._samples[this._pos];
  40893. delta = bottomValue - this.average;
  40894. this.average -= delta / (this._sampleCount - 1);
  40895. this._m2 -= delta * (bottomValue - this.average);
  40896. }
  40897. else {
  40898. this._sampleCount++;
  40899. }
  40900. //add new value to mean
  40901. delta = v - this.average;
  40902. this.average += delta / (this._sampleCount);
  40903. this._m2 += delta * (v - this.average);
  40904. //set the new variance
  40905. this.variance = this._m2 / (this._sampleCount - 1);
  40906. this._samples[this._pos] = v;
  40907. this._pos++;
  40908. this._pos %= this._samples.length; //positive wrap around
  40909. };
  40910. /**
  40911. * Returns previously added values or null if outside of history or outside the sliding window domain
  40912. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40913. * @return Value previously recorded with add() or null if outside of range
  40914. */
  40915. RollingAverage.prototype.history = function (i) {
  40916. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40917. return 0;
  40918. }
  40919. var i0 = this._wrapPosition(this._pos - 1.0);
  40920. return this._samples[this._wrapPosition(i0 - i)];
  40921. };
  40922. /**
  40923. * Returns true if enough samples have been taken to completely fill the sliding window
  40924. * @return true if sample-set saturated
  40925. */
  40926. RollingAverage.prototype.isSaturated = function () {
  40927. return this._sampleCount >= this._samples.length;
  40928. };
  40929. /**
  40930. * Resets the rolling average (equivalent to 0 samples taken so far)
  40931. */
  40932. RollingAverage.prototype.reset = function () {
  40933. this.average = 0;
  40934. this.variance = 0;
  40935. this._sampleCount = 0;
  40936. this._pos = 0;
  40937. this._m2 = 0;
  40938. };
  40939. /**
  40940. * Wraps a value around the sample range boundaries
  40941. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40942. * @return Wrapped position in sample range
  40943. */
  40944. RollingAverage.prototype._wrapPosition = function (i) {
  40945. var max = this._samples.length;
  40946. return ((i % max) + max) % max;
  40947. };
  40948. return RollingAverage;
  40949. }());
  40950. BABYLON.RollingAverage = RollingAverage;
  40951. })(BABYLON || (BABYLON = {}));
  40952. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40953. var BABYLON;
  40954. (function (BABYLON) {
  40955. /**
  40956. * "Static Class" containing the most commonly used helper while dealing with material for
  40957. * rendering purpose.
  40958. *
  40959. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40960. *
  40961. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40962. */
  40963. var MaterialHelper = /** @class */ (function () {
  40964. function MaterialHelper() {
  40965. }
  40966. /**
  40967. * Bind the current view position to an effect.
  40968. * @param effect The effect to be bound
  40969. * @param scene The scene the eyes position is used from
  40970. */
  40971. MaterialHelper.BindEyePosition = function (effect, scene) {
  40972. if (scene._forcedViewPosition) {
  40973. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40974. return;
  40975. }
  40976. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40977. };
  40978. /**
  40979. * Helps preparing the defines values about the UVs in used in the effect.
  40980. * UVs are shared as much as we can accross chanels in the shaders.
  40981. * @param texture The texture we are preparing the UVs for
  40982. * @param defines The defines to update
  40983. * @param key The chanel key "diffuse", "specular"... used in the shader
  40984. */
  40985. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40986. defines._needUVs = true;
  40987. defines[key] = true;
  40988. if (texture.getTextureMatrix().isIdentity(true)) {
  40989. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40990. if (texture.coordinatesIndex === 0) {
  40991. defines["MAINUV1"] = true;
  40992. }
  40993. else {
  40994. defines["MAINUV2"] = true;
  40995. }
  40996. }
  40997. else {
  40998. defines[key + "DIRECTUV"] = 0;
  40999. }
  41000. };
  41001. /**
  41002. * Binds a texture matrix value to its corrsponding uniform
  41003. * @param texture The texture to bind the matrix for
  41004. * @param uniformBuffer The uniform buffer receivin the data
  41005. * @param key The chanel key "diffuse", "specular"... used in the shader
  41006. */
  41007. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41008. var matrix = texture.getTextureMatrix();
  41009. if (!matrix.isIdentity(true)) {
  41010. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41011. }
  41012. };
  41013. /**
  41014. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41015. * @param mesh defines the current mesh
  41016. * @param scene defines the current scene
  41017. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41018. * @param pointsCloud defines if point cloud rendering has to be turned on
  41019. * @param fogEnabled defines if fog has to be turned on
  41020. * @param alphaTest defines if alpha testing has to be turned on
  41021. * @param defines defines the current list of defines
  41022. */
  41023. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41024. if (defines._areMiscDirty) {
  41025. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41026. defines["POINTSIZE"] = pointsCloud;
  41027. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41028. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41029. defines["ALPHATEST"] = alphaTest;
  41030. }
  41031. };
  41032. /**
  41033. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41034. * @param scene defines the current scene
  41035. * @param engine defines the current engine
  41036. * @param defines specifies the list of active defines
  41037. * @param useInstances defines if instances have to be turned on
  41038. * @param useClipPlane defines if clip plane have to be turned on
  41039. */
  41040. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41041. if (useClipPlane === void 0) { useClipPlane = null; }
  41042. var changed = false;
  41043. var useClipPlane1 = false;
  41044. var useClipPlane2 = false;
  41045. var useClipPlane3 = false;
  41046. var useClipPlane4 = false;
  41047. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41048. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41049. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41050. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41051. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41052. defines["CLIPPLANE"] = useClipPlane1;
  41053. changed = true;
  41054. }
  41055. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41056. defines["CLIPPLANE2"] = useClipPlane2;
  41057. changed = true;
  41058. }
  41059. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41060. defines["CLIPPLANE3"] = useClipPlane3;
  41061. changed = true;
  41062. }
  41063. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41064. defines["CLIPPLANE4"] = useClipPlane4;
  41065. changed = true;
  41066. }
  41067. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41068. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41069. changed = true;
  41070. }
  41071. if (defines["INSTANCES"] !== useInstances) {
  41072. defines["INSTANCES"] = useInstances;
  41073. changed = true;
  41074. }
  41075. if (changed) {
  41076. defines.markAsUnprocessed();
  41077. }
  41078. };
  41079. /**
  41080. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41081. * @param mesh The mesh containing the geometry data we will draw
  41082. * @param defines The defines to update
  41083. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41084. * @param useBones Precise whether bones should be used or not (override mesh info)
  41085. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41086. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41087. * @returns false if defines are considered not dirty and have not been checked
  41088. */
  41089. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41090. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41091. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41092. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41093. return false;
  41094. }
  41095. defines._normals = defines._needNormals;
  41096. defines._uvs = defines._needUVs;
  41097. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41098. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41099. defines["TANGENT"] = true;
  41100. }
  41101. if (defines._needUVs) {
  41102. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41103. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41104. }
  41105. else {
  41106. defines["UV1"] = false;
  41107. defines["UV2"] = false;
  41108. }
  41109. if (useVertexColor) {
  41110. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41111. defines["VERTEXCOLOR"] = hasVertexColors;
  41112. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41113. }
  41114. if (useBones) {
  41115. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41116. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41117. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41118. }
  41119. else {
  41120. defines["NUM_BONE_INFLUENCERS"] = 0;
  41121. defines["BonesPerMesh"] = 0;
  41122. }
  41123. }
  41124. if (useMorphTargets) {
  41125. var manager = mesh.morphTargetManager;
  41126. if (manager) {
  41127. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41128. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41129. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41130. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41131. }
  41132. else {
  41133. defines["MORPHTARGETS_TANGENT"] = false;
  41134. defines["MORPHTARGETS_NORMAL"] = false;
  41135. defines["MORPHTARGETS"] = false;
  41136. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41137. }
  41138. }
  41139. return true;
  41140. };
  41141. /**
  41142. * Prepares the defines related to the light information passed in parameter
  41143. * @param scene The scene we are intending to draw
  41144. * @param mesh The mesh the effect is compiling for
  41145. * @param defines The defines to update
  41146. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41147. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41148. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41149. * @returns true if normals will be required for the rest of the effect
  41150. */
  41151. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41152. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41153. if (disableLighting === void 0) { disableLighting = false; }
  41154. if (!defines._areLightsDirty) {
  41155. return defines._needNormals;
  41156. }
  41157. var lightIndex = 0;
  41158. var needNormals = false;
  41159. var needRebuild = false;
  41160. var lightmapMode = false;
  41161. var shadowEnabled = false;
  41162. var specularEnabled = false;
  41163. if (scene.lightsEnabled && !disableLighting) {
  41164. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41165. var light = _a[_i];
  41166. needNormals = true;
  41167. if (defines["LIGHT" + lightIndex] === undefined) {
  41168. needRebuild = true;
  41169. }
  41170. defines["LIGHT" + lightIndex] = true;
  41171. defines["SPOTLIGHT" + lightIndex] = false;
  41172. defines["HEMILIGHT" + lightIndex] = false;
  41173. defines["POINTLIGHT" + lightIndex] = false;
  41174. defines["DIRLIGHT" + lightIndex] = false;
  41175. light.prepareLightSpecificDefines(defines, lightIndex);
  41176. // FallOff.
  41177. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41178. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41179. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41180. switch (light.falloffType) {
  41181. case BABYLON.Light.FALLOFF_GLTF:
  41182. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41183. break;
  41184. case BABYLON.Light.FALLOFF_PHYSICAL:
  41185. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41186. break;
  41187. case BABYLON.Light.FALLOFF_STANDARD:
  41188. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41189. break;
  41190. }
  41191. // Specular
  41192. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41193. specularEnabled = true;
  41194. }
  41195. // Shadows
  41196. defines["SHADOW" + lightIndex] = false;
  41197. defines["SHADOWPCF" + lightIndex] = false;
  41198. defines["SHADOWPCSS" + lightIndex] = false;
  41199. defines["SHADOWPOISSON" + lightIndex] = false;
  41200. defines["SHADOWESM" + lightIndex] = false;
  41201. defines["SHADOWCUBE" + lightIndex] = false;
  41202. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41203. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41204. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41205. var shadowGenerator = light.getShadowGenerator();
  41206. if (shadowGenerator) {
  41207. var shadowMap = shadowGenerator.getShadowMap();
  41208. if (shadowMap) {
  41209. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41210. shadowEnabled = true;
  41211. shadowGenerator.prepareDefines(defines, lightIndex);
  41212. }
  41213. }
  41214. }
  41215. }
  41216. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41217. lightmapMode = true;
  41218. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41219. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41220. }
  41221. else {
  41222. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41223. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41224. }
  41225. lightIndex++;
  41226. if (lightIndex === maxSimultaneousLights)
  41227. break;
  41228. }
  41229. }
  41230. defines["SPECULARTERM"] = specularEnabled;
  41231. defines["SHADOWS"] = shadowEnabled;
  41232. // Resetting all other lights if any
  41233. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41234. if (defines["LIGHT" + index] !== undefined) {
  41235. defines["LIGHT" + index] = false;
  41236. defines["HEMILIGHT" + lightIndex] = false;
  41237. defines["POINTLIGHT" + lightIndex] = false;
  41238. defines["DIRLIGHT" + lightIndex] = false;
  41239. defines["SPOTLIGHT" + lightIndex] = false;
  41240. defines["SHADOW" + lightIndex] = false;
  41241. }
  41242. }
  41243. var caps = scene.getEngine().getCaps();
  41244. if (defines["SHADOWFLOAT"] === undefined) {
  41245. needRebuild = true;
  41246. }
  41247. defines["SHADOWFLOAT"] = shadowEnabled &&
  41248. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41249. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41250. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41251. if (needRebuild) {
  41252. defines.rebuild();
  41253. }
  41254. return needNormals;
  41255. };
  41256. /**
  41257. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41258. * that won t be acctive due to defines being turned off.
  41259. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41260. * @param samplersList The samplers list
  41261. * @param defines The defines helping in the list generation
  41262. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41263. */
  41264. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41265. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41266. var uniformsList;
  41267. var uniformBuffersList = null;
  41268. if (uniformsListOrOptions.uniformsNames) {
  41269. var options = uniformsListOrOptions;
  41270. uniformsList = options.uniformsNames;
  41271. uniformBuffersList = options.uniformBuffersNames;
  41272. samplersList = options.samplers;
  41273. defines = options.defines;
  41274. maxSimultaneousLights = options.maxSimultaneousLights;
  41275. }
  41276. else {
  41277. uniformsList = uniformsListOrOptions;
  41278. if (!samplersList) {
  41279. samplersList = [];
  41280. }
  41281. }
  41282. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41283. if (!defines["LIGHT" + lightIndex]) {
  41284. break;
  41285. }
  41286. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41287. if (uniformBuffersList) {
  41288. uniformBuffersList.push("Light" + lightIndex);
  41289. }
  41290. samplersList.push("shadowSampler" + lightIndex);
  41291. samplersList.push("depthSampler" + lightIndex);
  41292. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41293. samplersList.push("projectionLightSampler" + lightIndex);
  41294. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41295. }
  41296. }
  41297. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41298. uniformsList.push("morphTargetInfluences");
  41299. }
  41300. };
  41301. /**
  41302. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41303. * @param defines The defines to update while falling back
  41304. * @param fallbacks The authorized effect fallbacks
  41305. * @param maxSimultaneousLights The maximum number of lights allowed
  41306. * @param rank the current rank of the Effect
  41307. * @returns The newly affected rank
  41308. */
  41309. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41310. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41311. if (rank === void 0) { rank = 0; }
  41312. var lightFallbackRank = 0;
  41313. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41314. if (!defines["LIGHT" + lightIndex]) {
  41315. break;
  41316. }
  41317. if (lightIndex > 0) {
  41318. lightFallbackRank = rank + lightIndex;
  41319. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41320. }
  41321. if (!defines["SHADOWS"]) {
  41322. if (defines["SHADOW" + lightIndex]) {
  41323. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41324. }
  41325. if (defines["SHADOWPCF" + lightIndex]) {
  41326. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41327. }
  41328. if (defines["SHADOWPCSS" + lightIndex]) {
  41329. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41330. }
  41331. if (defines["SHADOWPOISSON" + lightIndex]) {
  41332. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41333. }
  41334. if (defines["SHADOWESM" + lightIndex]) {
  41335. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41336. }
  41337. }
  41338. }
  41339. return lightFallbackRank++;
  41340. };
  41341. /**
  41342. * Prepares the list of attributes required for morph targets according to the effect defines.
  41343. * @param attribs The current list of supported attribs
  41344. * @param mesh The mesh to prepare the morph targets attributes for
  41345. * @param defines The current Defines of the effect
  41346. */
  41347. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41348. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41349. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41350. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41351. var manager = mesh.morphTargetManager;
  41352. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41353. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41354. for (var index = 0; index < influencers; index++) {
  41355. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41356. if (normal) {
  41357. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41358. }
  41359. if (tangent) {
  41360. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41361. }
  41362. if (attribs.length > maxAttributesCount) {
  41363. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41364. }
  41365. }
  41366. }
  41367. };
  41368. /**
  41369. * Prepares the list of attributes required for bones according to the effect defines.
  41370. * @param attribs The current list of supported attribs
  41371. * @param mesh The mesh to prepare the bones attributes for
  41372. * @param defines The current Defines of the effect
  41373. * @param fallbacks The current efffect fallback strategy
  41374. */
  41375. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41376. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41377. fallbacks.addCPUSkinningFallback(0, mesh);
  41378. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41379. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41380. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41381. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41382. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41383. }
  41384. }
  41385. };
  41386. /**
  41387. * Prepares the list of attributes required for instances according to the effect defines.
  41388. * @param attribs The current list of supported attribs
  41389. * @param defines The current Defines of the effect
  41390. */
  41391. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41392. if (defines["INSTANCES"]) {
  41393. attribs.push("world0");
  41394. attribs.push("world1");
  41395. attribs.push("world2");
  41396. attribs.push("world3");
  41397. }
  41398. };
  41399. /**
  41400. * Binds the light shadow information to the effect for the given mesh.
  41401. * @param light The light containing the generator
  41402. * @param scene The scene the lights belongs to
  41403. * @param mesh The mesh we are binding the information to render
  41404. * @param lightIndex The light index in the effect used to render the mesh
  41405. * @param effect The effect we are binding the data to
  41406. */
  41407. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41408. if (light.shadowEnabled && mesh.receiveShadows) {
  41409. var shadowGenerator = light.getShadowGenerator();
  41410. if (shadowGenerator) {
  41411. shadowGenerator.bindShadowLight(lightIndex, effect);
  41412. }
  41413. }
  41414. };
  41415. /**
  41416. * Binds the light information to the effect.
  41417. * @param light The light containing the generator
  41418. * @param effect The effect we are binding the data to
  41419. * @param lightIndex The light index in the effect used to render
  41420. */
  41421. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41422. light.transferToEffect(effect, lightIndex + "");
  41423. };
  41424. /**
  41425. * Binds the lights information from the scene to the effect for the given mesh.
  41426. * @param scene The scene the lights belongs to
  41427. * @param mesh The mesh we are binding the information to render
  41428. * @param effect The effect we are binding the data to
  41429. * @param defines The generated defines for the effect
  41430. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41431. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41432. */
  41433. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41434. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41435. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41436. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41437. for (var i = 0; i < len; i++) {
  41438. var light = mesh._lightSources[i];
  41439. var iAsString = i.toString();
  41440. var scaledIntensity = light.getScaledIntensity();
  41441. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41442. MaterialHelper.BindLightProperties(light, effect, i);
  41443. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41444. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41445. if (defines["SPECULARTERM"]) {
  41446. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41447. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41448. }
  41449. // Shadows
  41450. if (scene.shadowsEnabled) {
  41451. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41452. }
  41453. light._uniformBuffer.update();
  41454. }
  41455. };
  41456. /**
  41457. * Binds the fog information from the scene to the effect for the given mesh.
  41458. * @param scene The scene the lights belongs to
  41459. * @param mesh The mesh we are binding the information to render
  41460. * @param effect The effect we are binding the data to
  41461. * @param linearSpace Defines if the fog effect is applied in linear space
  41462. */
  41463. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41464. if (linearSpace === void 0) { linearSpace = false; }
  41465. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41466. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41467. // Convert fog color to linear space if used in a linear space computed shader.
  41468. if (linearSpace) {
  41469. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41470. effect.setColor3("vFogColor", this._tempFogColor);
  41471. }
  41472. else {
  41473. effect.setColor3("vFogColor", scene.fogColor);
  41474. }
  41475. }
  41476. };
  41477. /**
  41478. * Binds the bones information from the mesh to the effect.
  41479. * @param mesh The mesh we are binding the information to render
  41480. * @param effect The effect we are binding the data to
  41481. */
  41482. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41483. if (!effect || !mesh) {
  41484. return;
  41485. }
  41486. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41487. mesh.computeBonesUsingShaders = false;
  41488. }
  41489. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41490. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41491. if (matrices) {
  41492. effect.setMatrices("mBones", matrices);
  41493. }
  41494. }
  41495. };
  41496. /**
  41497. * Binds the morph targets information from the mesh to the effect.
  41498. * @param abstractMesh The mesh we are binding the information to render
  41499. * @param effect The effect we are binding the data to
  41500. */
  41501. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41502. var manager = abstractMesh.morphTargetManager;
  41503. if (!abstractMesh || !manager) {
  41504. return;
  41505. }
  41506. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41507. };
  41508. /**
  41509. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41510. * @param defines The generated defines used in the effect
  41511. * @param effect The effect we are binding the data to
  41512. * @param scene The scene we are willing to render with logarithmic scale for
  41513. */
  41514. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41515. if (defines["LOGARITHMICDEPTH"]) {
  41516. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41517. }
  41518. };
  41519. /**
  41520. * Binds the clip plane information from the scene to the effect.
  41521. * @param scene The scene the clip plane information are extracted from
  41522. * @param effect The effect we are binding the data to
  41523. */
  41524. MaterialHelper.BindClipPlane = function (effect, scene) {
  41525. if (scene.clipPlane) {
  41526. var clipPlane = scene.clipPlane;
  41527. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41528. }
  41529. if (scene.clipPlane2) {
  41530. var clipPlane = scene.clipPlane2;
  41531. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41532. }
  41533. if (scene.clipPlane3) {
  41534. var clipPlane = scene.clipPlane3;
  41535. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41536. }
  41537. if (scene.clipPlane4) {
  41538. var clipPlane = scene.clipPlane4;
  41539. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41540. }
  41541. };
  41542. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41543. return MaterialHelper;
  41544. }());
  41545. BABYLON.MaterialHelper = MaterialHelper;
  41546. })(BABYLON || (BABYLON = {}));
  41547. //# sourceMappingURL=babylon.materialHelper.js.map
  41548. var BABYLON;
  41549. (function (BABYLON) {
  41550. var PushMaterial = /** @class */ (function (_super) {
  41551. __extends(PushMaterial, _super);
  41552. function PushMaterial(name, scene) {
  41553. var _this = _super.call(this, name, scene) || this;
  41554. _this._normalMatrix = new BABYLON.Matrix();
  41555. _this.storeEffectOnSubMeshes = true;
  41556. return _this;
  41557. }
  41558. PushMaterial.prototype.getEffect = function () {
  41559. return this._activeEffect;
  41560. };
  41561. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41562. if (!mesh) {
  41563. return false;
  41564. }
  41565. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41566. return true;
  41567. }
  41568. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41569. };
  41570. /**
  41571. * Binds the given world matrix to the active effect
  41572. *
  41573. * @param world the matrix to bind
  41574. */
  41575. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41576. this._activeEffect.setMatrix("world", world);
  41577. };
  41578. /**
  41579. * Binds the given normal matrix to the active effect
  41580. *
  41581. * @param normalMatrix the matrix to bind
  41582. */
  41583. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41584. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41585. };
  41586. PushMaterial.prototype.bind = function (world, mesh) {
  41587. if (!mesh) {
  41588. return;
  41589. }
  41590. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41591. };
  41592. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41593. if (effect === void 0) { effect = null; }
  41594. _super.prototype._afterBind.call(this, mesh);
  41595. this.getScene()._cachedEffect = effect;
  41596. };
  41597. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41598. if (visibility === void 0) { visibility = 1; }
  41599. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41600. };
  41601. return PushMaterial;
  41602. }(BABYLON.Material));
  41603. BABYLON.PushMaterial = PushMaterial;
  41604. })(BABYLON || (BABYLON = {}));
  41605. //# sourceMappingURL=babylon.pushMaterial.js.map
  41606. var BABYLON;
  41607. (function (BABYLON) {
  41608. /** @hidden */
  41609. var StandardMaterialDefines = /** @class */ (function (_super) {
  41610. __extends(StandardMaterialDefines, _super);
  41611. function StandardMaterialDefines() {
  41612. var _this = _super.call(this) || this;
  41613. _this.MAINUV1 = false;
  41614. _this.MAINUV2 = false;
  41615. _this.DIFFUSE = false;
  41616. _this.DIFFUSEDIRECTUV = 0;
  41617. _this.AMBIENT = false;
  41618. _this.AMBIENTDIRECTUV = 0;
  41619. _this.OPACITY = false;
  41620. _this.OPACITYDIRECTUV = 0;
  41621. _this.OPACITYRGB = false;
  41622. _this.REFLECTION = false;
  41623. _this.EMISSIVE = false;
  41624. _this.EMISSIVEDIRECTUV = 0;
  41625. _this.SPECULAR = false;
  41626. _this.SPECULARDIRECTUV = 0;
  41627. _this.BUMP = false;
  41628. _this.BUMPDIRECTUV = 0;
  41629. _this.PARALLAX = false;
  41630. _this.PARALLAXOCCLUSION = false;
  41631. _this.SPECULAROVERALPHA = false;
  41632. _this.CLIPPLANE = false;
  41633. _this.CLIPPLANE2 = false;
  41634. _this.CLIPPLANE3 = false;
  41635. _this.CLIPPLANE4 = false;
  41636. _this.ALPHATEST = false;
  41637. _this.DEPTHPREPASS = false;
  41638. _this.ALPHAFROMDIFFUSE = false;
  41639. _this.POINTSIZE = false;
  41640. _this.FOG = false;
  41641. _this.SPECULARTERM = false;
  41642. _this.DIFFUSEFRESNEL = false;
  41643. _this.OPACITYFRESNEL = false;
  41644. _this.REFLECTIONFRESNEL = false;
  41645. _this.REFRACTIONFRESNEL = false;
  41646. _this.EMISSIVEFRESNEL = false;
  41647. _this.FRESNEL = false;
  41648. _this.NORMAL = false;
  41649. _this.UV1 = false;
  41650. _this.UV2 = false;
  41651. _this.VERTEXCOLOR = false;
  41652. _this.VERTEXALPHA = false;
  41653. _this.NUM_BONE_INFLUENCERS = 0;
  41654. _this.BonesPerMesh = 0;
  41655. _this.INSTANCES = false;
  41656. _this.GLOSSINESS = false;
  41657. _this.ROUGHNESS = false;
  41658. _this.EMISSIVEASILLUMINATION = false;
  41659. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41660. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41661. _this.LIGHTMAP = false;
  41662. _this.LIGHTMAPDIRECTUV = 0;
  41663. _this.OBJECTSPACE_NORMALMAP = false;
  41664. _this.USELIGHTMAPASSHADOWMAP = false;
  41665. _this.REFLECTIONMAP_3D = false;
  41666. _this.REFLECTIONMAP_SPHERICAL = false;
  41667. _this.REFLECTIONMAP_PLANAR = false;
  41668. _this.REFLECTIONMAP_CUBIC = false;
  41669. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41670. _this.REFLECTIONMAP_PROJECTION = false;
  41671. _this.REFLECTIONMAP_SKYBOX = false;
  41672. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41673. _this.REFLECTIONMAP_EXPLICIT = false;
  41674. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41675. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41676. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41677. _this.INVERTCUBICMAP = false;
  41678. _this.LOGARITHMICDEPTH = false;
  41679. _this.REFRACTION = false;
  41680. _this.REFRACTIONMAP_3D = false;
  41681. _this.REFLECTIONOVERALPHA = false;
  41682. _this.TWOSIDEDLIGHTING = false;
  41683. _this.SHADOWFLOAT = false;
  41684. _this.MORPHTARGETS = false;
  41685. _this.MORPHTARGETS_NORMAL = false;
  41686. _this.MORPHTARGETS_TANGENT = false;
  41687. _this.NUM_MORPH_INFLUENCERS = 0;
  41688. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41689. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41690. _this.IMAGEPROCESSING = false;
  41691. _this.VIGNETTE = false;
  41692. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41693. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41694. _this.TONEMAPPING = false;
  41695. _this.TONEMAPPING_ACES = false;
  41696. _this.CONTRAST = false;
  41697. _this.COLORCURVES = false;
  41698. _this.COLORGRADING = false;
  41699. _this.COLORGRADING3D = false;
  41700. _this.SAMPLER3DGREENDEPTH = false;
  41701. _this.SAMPLER3DBGRMAP = false;
  41702. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41703. /**
  41704. * If the reflection texture on this material is in linear color space
  41705. * @hidden
  41706. */
  41707. _this.IS_REFLECTION_LINEAR = false;
  41708. /**
  41709. * If the refraction texture on this material is in linear color space
  41710. * @hidden
  41711. */
  41712. _this.IS_REFRACTION_LINEAR = false;
  41713. _this.EXPOSURE = false;
  41714. _this.rebuild();
  41715. return _this;
  41716. }
  41717. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41718. var modes = [
  41719. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41720. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41721. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41722. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41723. ];
  41724. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41725. var mode = modes_1[_i];
  41726. this[mode] = (mode === modeToEnable);
  41727. }
  41728. };
  41729. return StandardMaterialDefines;
  41730. }(BABYLON.MaterialDefines));
  41731. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41732. var StandardMaterial = /** @class */ (function (_super) {
  41733. __extends(StandardMaterial, _super);
  41734. function StandardMaterial(name, scene) {
  41735. var _this = _super.call(this, name, scene) || this;
  41736. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41737. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41738. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41739. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41740. _this.specularPower = 64;
  41741. _this._useAlphaFromDiffuseTexture = false;
  41742. _this._useEmissiveAsIllumination = false;
  41743. _this._linkEmissiveWithDiffuse = false;
  41744. _this._useSpecularOverAlpha = false;
  41745. _this._useReflectionOverAlpha = false;
  41746. _this._disableLighting = false;
  41747. _this._useObjectSpaceNormalMap = false;
  41748. _this._useParallax = false;
  41749. _this._useParallaxOcclusion = false;
  41750. _this.parallaxScaleBias = 0.05;
  41751. _this._roughness = 0;
  41752. _this.indexOfRefraction = 0.98;
  41753. _this.invertRefractionY = true;
  41754. /**
  41755. * Defines the alpha limits in alpha test mode
  41756. */
  41757. _this.alphaCutOff = 0.4;
  41758. _this._useLightmapAsShadowmap = false;
  41759. _this._useReflectionFresnelFromSpecular = false;
  41760. _this._useGlossinessFromSpecularMapAlpha = false;
  41761. _this._maxSimultaneousLights = 4;
  41762. /**
  41763. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41764. */
  41765. _this._invertNormalMapX = false;
  41766. /**
  41767. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41768. */
  41769. _this._invertNormalMapY = false;
  41770. /**
  41771. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41772. */
  41773. _this._twoSidedLighting = false;
  41774. _this._renderTargets = new BABYLON.SmartArray(16);
  41775. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41776. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41777. // Setup the default processing configuration to the scene.
  41778. _this._attachImageProcessingConfiguration(null);
  41779. _this.getRenderTargetTextures = function () {
  41780. _this._renderTargets.reset();
  41781. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41782. _this._renderTargets.push(_this._reflectionTexture);
  41783. }
  41784. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41785. _this._renderTargets.push(_this._refractionTexture);
  41786. }
  41787. return _this._renderTargets;
  41788. };
  41789. return _this;
  41790. }
  41791. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41792. /**
  41793. * Gets the image processing configuration used either in this material.
  41794. */
  41795. get: function () {
  41796. return this._imageProcessingConfiguration;
  41797. },
  41798. /**
  41799. * Sets the Default image processing configuration used either in the this material.
  41800. *
  41801. * If sets to null, the scene one is in use.
  41802. */
  41803. set: function (value) {
  41804. this._attachImageProcessingConfiguration(value);
  41805. // Ensure the effect will be rebuilt.
  41806. this._markAllSubMeshesAsTexturesDirty();
  41807. },
  41808. enumerable: true,
  41809. configurable: true
  41810. });
  41811. /**
  41812. * Attaches a new image processing configuration to the Standard Material.
  41813. * @param configuration
  41814. */
  41815. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41816. var _this = this;
  41817. if (configuration === this._imageProcessingConfiguration) {
  41818. return;
  41819. }
  41820. // Detaches observer.
  41821. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41822. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41823. }
  41824. // Pick the scene configuration if needed.
  41825. if (!configuration) {
  41826. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41827. }
  41828. else {
  41829. this._imageProcessingConfiguration = configuration;
  41830. }
  41831. // Attaches observer.
  41832. if (this._imageProcessingConfiguration) {
  41833. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41834. _this._markAllSubMeshesAsImageProcessingDirty();
  41835. });
  41836. }
  41837. };
  41838. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41839. /**
  41840. * Gets wether the color curves effect is enabled.
  41841. */
  41842. get: function () {
  41843. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41844. },
  41845. /**
  41846. * Sets wether the color curves effect is enabled.
  41847. */
  41848. set: function (value) {
  41849. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41850. },
  41851. enumerable: true,
  41852. configurable: true
  41853. });
  41854. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41855. /**
  41856. * Gets wether the color grading effect is enabled.
  41857. */
  41858. get: function () {
  41859. return this.imageProcessingConfiguration.colorGradingEnabled;
  41860. },
  41861. /**
  41862. * Gets wether the color grading effect is enabled.
  41863. */
  41864. set: function (value) {
  41865. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41866. },
  41867. enumerable: true,
  41868. configurable: true
  41869. });
  41870. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41871. /**
  41872. * Gets wether tonemapping is enabled or not.
  41873. */
  41874. get: function () {
  41875. return this._imageProcessingConfiguration.toneMappingEnabled;
  41876. },
  41877. /**
  41878. * Sets wether tonemapping is enabled or not
  41879. */
  41880. set: function (value) {
  41881. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41882. },
  41883. enumerable: true,
  41884. configurable: true
  41885. });
  41886. ;
  41887. ;
  41888. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41889. /**
  41890. * The camera exposure used on this material.
  41891. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41892. * This corresponds to a photographic exposure.
  41893. */
  41894. get: function () {
  41895. return this._imageProcessingConfiguration.exposure;
  41896. },
  41897. /**
  41898. * The camera exposure used on this material.
  41899. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41900. * This corresponds to a photographic exposure.
  41901. */
  41902. set: function (value) {
  41903. this._imageProcessingConfiguration.exposure = value;
  41904. },
  41905. enumerable: true,
  41906. configurable: true
  41907. });
  41908. ;
  41909. ;
  41910. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41911. /**
  41912. * Gets The camera contrast used on this material.
  41913. */
  41914. get: function () {
  41915. return this._imageProcessingConfiguration.contrast;
  41916. },
  41917. /**
  41918. * Sets The camera contrast used on this material.
  41919. */
  41920. set: function (value) {
  41921. this._imageProcessingConfiguration.contrast = value;
  41922. },
  41923. enumerable: true,
  41924. configurable: true
  41925. });
  41926. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41927. /**
  41928. * Gets the Color Grading 2D Lookup Texture.
  41929. */
  41930. get: function () {
  41931. return this._imageProcessingConfiguration.colorGradingTexture;
  41932. },
  41933. /**
  41934. * Sets the Color Grading 2D Lookup Texture.
  41935. */
  41936. set: function (value) {
  41937. this._imageProcessingConfiguration.colorGradingTexture = value;
  41938. },
  41939. enumerable: true,
  41940. configurable: true
  41941. });
  41942. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41943. /**
  41944. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41945. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41946. * 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;
  41947. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41948. */
  41949. get: function () {
  41950. return this._imageProcessingConfiguration.colorCurves;
  41951. },
  41952. /**
  41953. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41954. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41955. * 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;
  41956. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41957. */
  41958. set: function (value) {
  41959. this._imageProcessingConfiguration.colorCurves = value;
  41960. },
  41961. enumerable: true,
  41962. configurable: true
  41963. });
  41964. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41965. /**
  41966. * Gets a boolean indicating that current material needs to register RTT
  41967. */
  41968. get: function () {
  41969. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41970. return true;
  41971. }
  41972. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41973. return true;
  41974. }
  41975. return false;
  41976. },
  41977. enumerable: true,
  41978. configurable: true
  41979. });
  41980. StandardMaterial.prototype.getClassName = function () {
  41981. return "StandardMaterial";
  41982. };
  41983. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41984. get: function () {
  41985. return this._useLogarithmicDepth;
  41986. },
  41987. set: function (value) {
  41988. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41989. this._markAllSubMeshesAsMiscDirty();
  41990. },
  41991. enumerable: true,
  41992. configurable: true
  41993. });
  41994. StandardMaterial.prototype.needAlphaBlending = function () {
  41995. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41996. };
  41997. StandardMaterial.prototype.needAlphaTesting = function () {
  41998. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41999. };
  42000. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42001. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42002. };
  42003. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42004. return this._diffuseTexture;
  42005. };
  42006. /**
  42007. * Child classes can use it to update shaders
  42008. */
  42009. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42010. if (useInstances === void 0) { useInstances = false; }
  42011. if (subMesh.effect && this.isFrozen) {
  42012. if (this._wasPreviouslyReady) {
  42013. return true;
  42014. }
  42015. }
  42016. if (!subMesh._materialDefines) {
  42017. subMesh._materialDefines = new StandardMaterialDefines();
  42018. }
  42019. var scene = this.getScene();
  42020. var defines = subMesh._materialDefines;
  42021. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42022. if (defines._renderId === scene.getRenderId()) {
  42023. return true;
  42024. }
  42025. }
  42026. var engine = scene.getEngine();
  42027. // Lights
  42028. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42029. // Textures
  42030. if (defines._areTexturesDirty) {
  42031. defines._needUVs = false;
  42032. defines.MAINUV1 = false;
  42033. defines.MAINUV2 = false;
  42034. if (scene.texturesEnabled) {
  42035. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42036. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42037. return false;
  42038. }
  42039. else {
  42040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42041. }
  42042. }
  42043. else {
  42044. defines.DIFFUSE = false;
  42045. }
  42046. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42047. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42048. return false;
  42049. }
  42050. else {
  42051. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42052. }
  42053. }
  42054. else {
  42055. defines.AMBIENT = false;
  42056. }
  42057. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42058. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42059. return false;
  42060. }
  42061. else {
  42062. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42063. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42064. }
  42065. }
  42066. else {
  42067. defines.OPACITY = false;
  42068. }
  42069. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42070. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42071. return false;
  42072. }
  42073. else {
  42074. defines._needNormals = true;
  42075. defines.REFLECTION = true;
  42076. defines.ROUGHNESS = (this._roughness > 0);
  42077. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42078. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42079. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42080. switch (this._reflectionTexture.coordinatesMode) {
  42081. case BABYLON.Texture.EXPLICIT_MODE:
  42082. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42083. break;
  42084. case BABYLON.Texture.PLANAR_MODE:
  42085. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42086. break;
  42087. case BABYLON.Texture.PROJECTION_MODE:
  42088. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42089. break;
  42090. case BABYLON.Texture.SKYBOX_MODE:
  42091. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42092. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42093. break;
  42094. case BABYLON.Texture.SPHERICAL_MODE:
  42095. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42096. break;
  42097. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42098. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42099. break;
  42100. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42101. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42102. break;
  42103. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42104. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42105. break;
  42106. case BABYLON.Texture.CUBIC_MODE:
  42107. case BABYLON.Texture.INVCUBIC_MODE:
  42108. default:
  42109. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42110. break;
  42111. }
  42112. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42113. }
  42114. }
  42115. else {
  42116. defines.REFLECTION = false;
  42117. }
  42118. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42119. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42120. return false;
  42121. }
  42122. else {
  42123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42124. }
  42125. }
  42126. else {
  42127. defines.EMISSIVE = false;
  42128. }
  42129. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42130. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42131. return false;
  42132. }
  42133. else {
  42134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42135. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42136. }
  42137. }
  42138. else {
  42139. defines.LIGHTMAP = false;
  42140. }
  42141. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42142. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42143. return false;
  42144. }
  42145. else {
  42146. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42147. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42148. }
  42149. }
  42150. else {
  42151. defines.SPECULAR = false;
  42152. }
  42153. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42154. // Bump texure can not be not blocking.
  42155. if (!this._bumpTexture.isReady()) {
  42156. return false;
  42157. }
  42158. else {
  42159. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42160. defines.PARALLAX = this._useParallax;
  42161. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42162. }
  42163. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42164. }
  42165. else {
  42166. defines.BUMP = false;
  42167. }
  42168. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42169. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42170. return false;
  42171. }
  42172. else {
  42173. defines._needUVs = true;
  42174. defines.REFRACTION = true;
  42175. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42176. }
  42177. }
  42178. else {
  42179. defines.REFRACTION = false;
  42180. }
  42181. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42182. }
  42183. else {
  42184. defines.DIFFUSE = false;
  42185. defines.AMBIENT = false;
  42186. defines.OPACITY = false;
  42187. defines.REFLECTION = false;
  42188. defines.EMISSIVE = false;
  42189. defines.LIGHTMAP = false;
  42190. defines.BUMP = false;
  42191. defines.REFRACTION = false;
  42192. }
  42193. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42194. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42195. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42196. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42197. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42198. }
  42199. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42200. if (!this._imageProcessingConfiguration.isReady()) {
  42201. return false;
  42202. }
  42203. this._imageProcessingConfiguration.prepareDefines(defines);
  42204. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42205. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42206. }
  42207. if (defines._areFresnelDirty) {
  42208. if (StandardMaterial.FresnelEnabled) {
  42209. // Fresnel
  42210. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42211. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42212. this._reflectionFresnelParameters) {
  42213. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42214. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42215. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42216. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42217. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42218. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42219. defines._needNormals = true;
  42220. defines.FRESNEL = true;
  42221. }
  42222. }
  42223. else {
  42224. defines.FRESNEL = false;
  42225. }
  42226. }
  42227. // Misc.
  42228. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42229. // Attribs
  42230. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42231. // Values that need to be evaluated on every frame
  42232. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42233. // Get correct effect
  42234. if (defines.isDirty) {
  42235. defines.markAsProcessed();
  42236. scene.resetCachedMaterial();
  42237. // Fallbacks
  42238. var fallbacks = new BABYLON.EffectFallbacks();
  42239. if (defines.REFLECTION) {
  42240. fallbacks.addFallback(0, "REFLECTION");
  42241. }
  42242. if (defines.SPECULAR) {
  42243. fallbacks.addFallback(0, "SPECULAR");
  42244. }
  42245. if (defines.BUMP) {
  42246. fallbacks.addFallback(0, "BUMP");
  42247. }
  42248. if (defines.PARALLAX) {
  42249. fallbacks.addFallback(1, "PARALLAX");
  42250. }
  42251. if (defines.PARALLAXOCCLUSION) {
  42252. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42253. }
  42254. if (defines.SPECULAROVERALPHA) {
  42255. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42256. }
  42257. if (defines.FOG) {
  42258. fallbacks.addFallback(1, "FOG");
  42259. }
  42260. if (defines.POINTSIZE) {
  42261. fallbacks.addFallback(0, "POINTSIZE");
  42262. }
  42263. if (defines.LOGARITHMICDEPTH) {
  42264. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42265. }
  42266. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42267. if (defines.SPECULARTERM) {
  42268. fallbacks.addFallback(0, "SPECULARTERM");
  42269. }
  42270. if (defines.DIFFUSEFRESNEL) {
  42271. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42272. }
  42273. if (defines.OPACITYFRESNEL) {
  42274. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42275. }
  42276. if (defines.REFLECTIONFRESNEL) {
  42277. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42278. }
  42279. if (defines.EMISSIVEFRESNEL) {
  42280. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42281. }
  42282. if (defines.FRESNEL) {
  42283. fallbacks.addFallback(4, "FRESNEL");
  42284. }
  42285. //Attributes
  42286. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42287. if (defines.NORMAL) {
  42288. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42289. }
  42290. if (defines.UV1) {
  42291. attribs.push(BABYLON.VertexBuffer.UVKind);
  42292. }
  42293. if (defines.UV2) {
  42294. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42295. }
  42296. if (defines.VERTEXCOLOR) {
  42297. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42298. }
  42299. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42300. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42301. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42302. var shaderName = "default";
  42303. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42304. "vFogInfos", "vFogColor", "pointSize",
  42305. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42306. "mBones",
  42307. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42308. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42309. "vReflectionPosition", "vReflectionSize",
  42310. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42311. ];
  42312. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42313. var uniformBuffers = ["Material", "Scene"];
  42314. if (BABYLON.ImageProcessingConfiguration) {
  42315. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42316. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42317. }
  42318. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42319. uniformsNames: uniforms,
  42320. uniformBuffersNames: uniformBuffers,
  42321. samplers: samplers,
  42322. defines: defines,
  42323. maxSimultaneousLights: this._maxSimultaneousLights
  42324. });
  42325. if (this.customShaderNameResolve) {
  42326. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42327. }
  42328. var join = defines.toString();
  42329. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42330. attributes: attribs,
  42331. uniformsNames: uniforms,
  42332. uniformBuffersNames: uniformBuffers,
  42333. samplers: samplers,
  42334. defines: join,
  42335. fallbacks: fallbacks,
  42336. onCompiled: this.onCompiled,
  42337. onError: this.onError,
  42338. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42339. }, engine), defines);
  42340. this.buildUniformLayout();
  42341. }
  42342. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42343. return false;
  42344. }
  42345. defines._renderId = scene.getRenderId();
  42346. this._wasPreviouslyReady = true;
  42347. return true;
  42348. };
  42349. StandardMaterial.prototype.buildUniformLayout = function () {
  42350. // Order is important !
  42351. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42352. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42353. this._uniformBuffer.addUniform("opacityParts", 4);
  42354. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42355. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42356. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42357. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42358. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42359. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42360. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42361. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42362. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42363. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42364. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42365. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42366. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42367. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42368. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42369. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42370. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42371. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42372. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42373. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42374. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42375. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42376. this._uniformBuffer.addUniform("specularMatrix", 16);
  42377. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42378. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42379. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42380. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42381. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42382. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42383. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42384. this._uniformBuffer.addUniform("pointSize", 1);
  42385. this._uniformBuffer.create();
  42386. };
  42387. StandardMaterial.prototype.unbind = function () {
  42388. if (this._activeEffect) {
  42389. var needFlag = false;
  42390. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42391. this._activeEffect.setTexture("reflection2DSampler", null);
  42392. needFlag = true;
  42393. }
  42394. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42395. this._activeEffect.setTexture("refraction2DSampler", null);
  42396. needFlag = true;
  42397. }
  42398. if (needFlag) {
  42399. this._markAllSubMeshesAsTexturesDirty();
  42400. }
  42401. }
  42402. _super.prototype.unbind.call(this);
  42403. };
  42404. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42405. var scene = this.getScene();
  42406. var defines = subMesh._materialDefines;
  42407. if (!defines) {
  42408. return;
  42409. }
  42410. var effect = subMesh.effect;
  42411. if (!effect) {
  42412. return;
  42413. }
  42414. this._activeEffect = effect;
  42415. // Matrices
  42416. this.bindOnlyWorldMatrix(world);
  42417. // Normal Matrix
  42418. if (defines.OBJECTSPACE_NORMALMAP) {
  42419. world.toNormalMatrix(this._normalMatrix);
  42420. this.bindOnlyNormalMatrix(this._normalMatrix);
  42421. }
  42422. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42423. // Bones
  42424. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42425. if (mustRebind) {
  42426. this._uniformBuffer.bindToEffect(effect, "Material");
  42427. this.bindViewProjection(effect);
  42428. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42429. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42430. // Fresnel
  42431. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42432. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42433. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42434. }
  42435. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42436. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42437. }
  42438. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42439. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42440. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42441. }
  42442. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42443. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42444. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42445. }
  42446. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42447. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42448. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42449. }
  42450. }
  42451. // Textures
  42452. if (scene.texturesEnabled) {
  42453. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42454. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42455. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42456. if (this._diffuseTexture.hasAlpha) {
  42457. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42458. }
  42459. }
  42460. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42461. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42462. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42463. }
  42464. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42465. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42466. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42467. }
  42468. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42469. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42470. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42471. if (this._reflectionTexture.boundingBoxSize) {
  42472. var cubeTexture = this._reflectionTexture;
  42473. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42474. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42475. }
  42476. }
  42477. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42478. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42479. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42480. }
  42481. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42482. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42483. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42484. }
  42485. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42486. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42487. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42488. }
  42489. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42490. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42491. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42492. if (scene._mirroredCameraPosition) {
  42493. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42494. }
  42495. else {
  42496. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42497. }
  42498. }
  42499. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42500. var depth = 1.0;
  42501. if (!this._refractionTexture.isCube) {
  42502. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42503. if (this._refractionTexture.depth) {
  42504. depth = this._refractionTexture.depth;
  42505. }
  42506. }
  42507. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42508. }
  42509. }
  42510. // Point size
  42511. if (this.pointsCloud) {
  42512. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42513. }
  42514. if (defines.SPECULARTERM) {
  42515. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42516. }
  42517. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42518. // Diffuse
  42519. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42520. }
  42521. // Textures
  42522. if (scene.texturesEnabled) {
  42523. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42524. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42525. }
  42526. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42527. effect.setTexture("ambientSampler", this._ambientTexture);
  42528. }
  42529. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42530. effect.setTexture("opacitySampler", this._opacityTexture);
  42531. }
  42532. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42533. if (this._reflectionTexture.isCube) {
  42534. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42535. }
  42536. else {
  42537. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42538. }
  42539. }
  42540. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42541. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42542. }
  42543. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42544. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42545. }
  42546. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42547. effect.setTexture("specularSampler", this._specularTexture);
  42548. }
  42549. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42550. effect.setTexture("bumpSampler", this._bumpTexture);
  42551. }
  42552. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42553. var depth = 1.0;
  42554. if (this._refractionTexture.isCube) {
  42555. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42556. }
  42557. else {
  42558. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42559. }
  42560. }
  42561. }
  42562. // Clip plane
  42563. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42564. // Colors
  42565. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42566. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42567. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42568. }
  42569. if (mustRebind || !this.isFrozen) {
  42570. // Lights
  42571. if (scene.lightsEnabled && !this._disableLighting) {
  42572. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42573. }
  42574. // View
  42575. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42576. this.bindView(effect);
  42577. }
  42578. // Fog
  42579. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42580. // Morph targets
  42581. if (defines.NUM_MORPH_INFLUENCERS) {
  42582. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42583. }
  42584. // Log. depth
  42585. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42586. // image processing
  42587. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42588. this._imageProcessingConfiguration.bind(this._activeEffect);
  42589. }
  42590. }
  42591. this._uniformBuffer.update();
  42592. this._afterBind(mesh, this._activeEffect);
  42593. };
  42594. StandardMaterial.prototype.getAnimatables = function () {
  42595. var results = [];
  42596. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42597. results.push(this._diffuseTexture);
  42598. }
  42599. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42600. results.push(this._ambientTexture);
  42601. }
  42602. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42603. results.push(this._opacityTexture);
  42604. }
  42605. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42606. results.push(this._reflectionTexture);
  42607. }
  42608. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42609. results.push(this._emissiveTexture);
  42610. }
  42611. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42612. results.push(this._specularTexture);
  42613. }
  42614. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42615. results.push(this._bumpTexture);
  42616. }
  42617. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42618. results.push(this._lightmapTexture);
  42619. }
  42620. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42621. results.push(this._refractionTexture);
  42622. }
  42623. return results;
  42624. };
  42625. StandardMaterial.prototype.getActiveTextures = function () {
  42626. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42627. if (this._diffuseTexture) {
  42628. activeTextures.push(this._diffuseTexture);
  42629. }
  42630. if (this._ambientTexture) {
  42631. activeTextures.push(this._ambientTexture);
  42632. }
  42633. if (this._opacityTexture) {
  42634. activeTextures.push(this._opacityTexture);
  42635. }
  42636. if (this._reflectionTexture) {
  42637. activeTextures.push(this._reflectionTexture);
  42638. }
  42639. if (this._emissiveTexture) {
  42640. activeTextures.push(this._emissiveTexture);
  42641. }
  42642. if (this._specularTexture) {
  42643. activeTextures.push(this._specularTexture);
  42644. }
  42645. if (this._bumpTexture) {
  42646. activeTextures.push(this._bumpTexture);
  42647. }
  42648. if (this._lightmapTexture) {
  42649. activeTextures.push(this._lightmapTexture);
  42650. }
  42651. if (this._refractionTexture) {
  42652. activeTextures.push(this._refractionTexture);
  42653. }
  42654. return activeTextures;
  42655. };
  42656. StandardMaterial.prototype.hasTexture = function (texture) {
  42657. if (_super.prototype.hasTexture.call(this, texture)) {
  42658. return true;
  42659. }
  42660. if (this._diffuseTexture === texture) {
  42661. return true;
  42662. }
  42663. if (this._ambientTexture === texture) {
  42664. return true;
  42665. }
  42666. if (this._opacityTexture === texture) {
  42667. return true;
  42668. }
  42669. if (this._reflectionTexture === texture) {
  42670. return true;
  42671. }
  42672. if (this._emissiveTexture === texture) {
  42673. return true;
  42674. }
  42675. if (this._specularTexture === texture) {
  42676. return true;
  42677. }
  42678. if (this._bumpTexture === texture) {
  42679. return true;
  42680. }
  42681. if (this._lightmapTexture === texture) {
  42682. return true;
  42683. }
  42684. if (this._refractionTexture === texture) {
  42685. return true;
  42686. }
  42687. return false;
  42688. };
  42689. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42690. if (forceDisposeTextures) {
  42691. if (this._diffuseTexture) {
  42692. this._diffuseTexture.dispose();
  42693. }
  42694. if (this._ambientTexture) {
  42695. this._ambientTexture.dispose();
  42696. }
  42697. if (this._opacityTexture) {
  42698. this._opacityTexture.dispose();
  42699. }
  42700. if (this._reflectionTexture) {
  42701. this._reflectionTexture.dispose();
  42702. }
  42703. if (this._emissiveTexture) {
  42704. this._emissiveTexture.dispose();
  42705. }
  42706. if (this._specularTexture) {
  42707. this._specularTexture.dispose();
  42708. }
  42709. if (this._bumpTexture) {
  42710. this._bumpTexture.dispose();
  42711. }
  42712. if (this._lightmapTexture) {
  42713. this._lightmapTexture.dispose();
  42714. }
  42715. if (this._refractionTexture) {
  42716. this._refractionTexture.dispose();
  42717. }
  42718. }
  42719. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42720. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42721. }
  42722. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42723. };
  42724. StandardMaterial.prototype.clone = function (name) {
  42725. var _this = this;
  42726. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42727. result.name = name;
  42728. result.id = name;
  42729. return result;
  42730. };
  42731. StandardMaterial.prototype.serialize = function () {
  42732. return BABYLON.SerializationHelper.Serialize(this);
  42733. };
  42734. // Statics
  42735. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42736. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42737. };
  42738. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42739. get: function () {
  42740. return StandardMaterial._DiffuseTextureEnabled;
  42741. },
  42742. set: function (value) {
  42743. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42744. return;
  42745. }
  42746. StandardMaterial._DiffuseTextureEnabled = value;
  42747. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42748. },
  42749. enumerable: true,
  42750. configurable: true
  42751. });
  42752. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42753. get: function () {
  42754. return StandardMaterial._AmbientTextureEnabled;
  42755. },
  42756. set: function (value) {
  42757. if (StandardMaterial._AmbientTextureEnabled === value) {
  42758. return;
  42759. }
  42760. StandardMaterial._AmbientTextureEnabled = value;
  42761. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42762. },
  42763. enumerable: true,
  42764. configurable: true
  42765. });
  42766. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42767. get: function () {
  42768. return StandardMaterial._OpacityTextureEnabled;
  42769. },
  42770. set: function (value) {
  42771. if (StandardMaterial._OpacityTextureEnabled === value) {
  42772. return;
  42773. }
  42774. StandardMaterial._OpacityTextureEnabled = value;
  42775. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42776. },
  42777. enumerable: true,
  42778. configurable: true
  42779. });
  42780. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42781. get: function () {
  42782. return StandardMaterial._ReflectionTextureEnabled;
  42783. },
  42784. set: function (value) {
  42785. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42786. return;
  42787. }
  42788. StandardMaterial._ReflectionTextureEnabled = value;
  42789. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42790. },
  42791. enumerable: true,
  42792. configurable: true
  42793. });
  42794. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42795. get: function () {
  42796. return StandardMaterial._EmissiveTextureEnabled;
  42797. },
  42798. set: function (value) {
  42799. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42800. return;
  42801. }
  42802. StandardMaterial._EmissiveTextureEnabled = value;
  42803. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42804. },
  42805. enumerable: true,
  42806. configurable: true
  42807. });
  42808. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42809. get: function () {
  42810. return StandardMaterial._SpecularTextureEnabled;
  42811. },
  42812. set: function (value) {
  42813. if (StandardMaterial._SpecularTextureEnabled === value) {
  42814. return;
  42815. }
  42816. StandardMaterial._SpecularTextureEnabled = value;
  42817. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42818. },
  42819. enumerable: true,
  42820. configurable: true
  42821. });
  42822. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42823. get: function () {
  42824. return StandardMaterial._BumpTextureEnabled;
  42825. },
  42826. set: function (value) {
  42827. if (StandardMaterial._BumpTextureEnabled === value) {
  42828. return;
  42829. }
  42830. StandardMaterial._BumpTextureEnabled = value;
  42831. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42832. },
  42833. enumerable: true,
  42834. configurable: true
  42835. });
  42836. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42837. get: function () {
  42838. return StandardMaterial._LightmapTextureEnabled;
  42839. },
  42840. set: function (value) {
  42841. if (StandardMaterial._LightmapTextureEnabled === value) {
  42842. return;
  42843. }
  42844. StandardMaterial._LightmapTextureEnabled = value;
  42845. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42846. },
  42847. enumerable: true,
  42848. configurable: true
  42849. });
  42850. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42851. get: function () {
  42852. return StandardMaterial._RefractionTextureEnabled;
  42853. },
  42854. set: function (value) {
  42855. if (StandardMaterial._RefractionTextureEnabled === value) {
  42856. return;
  42857. }
  42858. StandardMaterial._RefractionTextureEnabled = value;
  42859. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42860. },
  42861. enumerable: true,
  42862. configurable: true
  42863. });
  42864. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42865. get: function () {
  42866. return StandardMaterial._ColorGradingTextureEnabled;
  42867. },
  42868. set: function (value) {
  42869. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42870. return;
  42871. }
  42872. StandardMaterial._ColorGradingTextureEnabled = value;
  42873. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42874. },
  42875. enumerable: true,
  42876. configurable: true
  42877. });
  42878. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42879. get: function () {
  42880. return StandardMaterial._FresnelEnabled;
  42881. },
  42882. set: function (value) {
  42883. if (StandardMaterial._FresnelEnabled === value) {
  42884. return;
  42885. }
  42886. StandardMaterial._FresnelEnabled = value;
  42887. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42888. },
  42889. enumerable: true,
  42890. configurable: true
  42891. });
  42892. // Flags used to enable or disable a type of texture for all Standard Materials
  42893. StandardMaterial._DiffuseTextureEnabled = true;
  42894. StandardMaterial._AmbientTextureEnabled = true;
  42895. StandardMaterial._OpacityTextureEnabled = true;
  42896. StandardMaterial._ReflectionTextureEnabled = true;
  42897. StandardMaterial._EmissiveTextureEnabled = true;
  42898. StandardMaterial._SpecularTextureEnabled = true;
  42899. StandardMaterial._BumpTextureEnabled = true;
  42900. StandardMaterial._LightmapTextureEnabled = true;
  42901. StandardMaterial._RefractionTextureEnabled = true;
  42902. StandardMaterial._ColorGradingTextureEnabled = true;
  42903. StandardMaterial._FresnelEnabled = true;
  42904. __decorate([
  42905. BABYLON.serializeAsTexture("diffuseTexture")
  42906. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42907. __decorate([
  42908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42909. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42910. __decorate([
  42911. BABYLON.serializeAsTexture("ambientTexture")
  42912. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42913. __decorate([
  42914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42915. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42916. __decorate([
  42917. BABYLON.serializeAsTexture("opacityTexture")
  42918. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42919. __decorate([
  42920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42921. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42922. __decorate([
  42923. BABYLON.serializeAsTexture("reflectionTexture")
  42924. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42925. __decorate([
  42926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42927. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42928. __decorate([
  42929. BABYLON.serializeAsTexture("emissiveTexture")
  42930. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42931. __decorate([
  42932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42933. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42934. __decorate([
  42935. BABYLON.serializeAsTexture("specularTexture")
  42936. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42937. __decorate([
  42938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42939. ], StandardMaterial.prototype, "specularTexture", void 0);
  42940. __decorate([
  42941. BABYLON.serializeAsTexture("bumpTexture")
  42942. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42943. __decorate([
  42944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42945. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42946. __decorate([
  42947. BABYLON.serializeAsTexture("lightmapTexture")
  42948. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42949. __decorate([
  42950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42951. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42952. __decorate([
  42953. BABYLON.serializeAsTexture("refractionTexture")
  42954. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42955. __decorate([
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42958. __decorate([
  42959. BABYLON.serializeAsColor3("ambient")
  42960. ], StandardMaterial.prototype, "ambientColor", void 0);
  42961. __decorate([
  42962. BABYLON.serializeAsColor3("diffuse")
  42963. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42964. __decorate([
  42965. BABYLON.serializeAsColor3("specular")
  42966. ], StandardMaterial.prototype, "specularColor", void 0);
  42967. __decorate([
  42968. BABYLON.serializeAsColor3("emissive")
  42969. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42970. __decorate([
  42971. BABYLON.serialize()
  42972. ], StandardMaterial.prototype, "specularPower", void 0);
  42973. __decorate([
  42974. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42975. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42976. __decorate([
  42977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42978. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42979. __decorate([
  42980. BABYLON.serialize("useEmissiveAsIllumination")
  42981. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42982. __decorate([
  42983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42984. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42985. __decorate([
  42986. BABYLON.serialize("linkEmissiveWithDiffuse")
  42987. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42988. __decorate([
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42990. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42991. __decorate([
  42992. BABYLON.serialize("useSpecularOverAlpha")
  42993. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42994. __decorate([
  42995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42996. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42997. __decorate([
  42998. BABYLON.serialize("useReflectionOverAlpha")
  42999. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43000. __decorate([
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43002. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43003. __decorate([
  43004. BABYLON.serialize("disableLighting")
  43005. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43006. __decorate([
  43007. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43008. ], StandardMaterial.prototype, "disableLighting", void 0);
  43009. __decorate([
  43010. BABYLON.serialize("useObjectSpaceNormalMap")
  43011. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43012. __decorate([
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43014. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43015. __decorate([
  43016. BABYLON.serialize("useParallax")
  43017. ], StandardMaterial.prototype, "_useParallax", void 0);
  43018. __decorate([
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43020. ], StandardMaterial.prototype, "useParallax", void 0);
  43021. __decorate([
  43022. BABYLON.serialize("useParallaxOcclusion")
  43023. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43024. __decorate([
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43026. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43027. __decorate([
  43028. BABYLON.serialize()
  43029. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43030. __decorate([
  43031. BABYLON.serialize("roughness")
  43032. ], StandardMaterial.prototype, "_roughness", void 0);
  43033. __decorate([
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43035. ], StandardMaterial.prototype, "roughness", void 0);
  43036. __decorate([
  43037. BABYLON.serialize()
  43038. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43039. __decorate([
  43040. BABYLON.serialize()
  43041. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43042. __decorate([
  43043. BABYLON.serialize()
  43044. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43045. __decorate([
  43046. BABYLON.serialize("useLightmapAsShadowmap")
  43047. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43048. __decorate([
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43051. __decorate([
  43052. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43053. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43054. __decorate([
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43056. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43059. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43060. __decorate([
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43062. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43063. __decorate([
  43064. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43065. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43066. __decorate([
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43068. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43071. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43072. __decorate([
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43074. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43075. __decorate([
  43076. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43077. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43078. __decorate([
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43080. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43081. __decorate([
  43082. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43083. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43084. __decorate([
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43086. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43087. __decorate([
  43088. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43089. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43090. __decorate([
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43093. __decorate([
  43094. BABYLON.serialize("maxSimultaneousLights")
  43095. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43096. __decorate([
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43098. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43099. __decorate([
  43100. BABYLON.serialize("invertNormalMapX")
  43101. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43102. __decorate([
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43104. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43105. __decorate([
  43106. BABYLON.serialize("invertNormalMapY")
  43107. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43108. __decorate([
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43111. __decorate([
  43112. BABYLON.serialize("twoSidedLighting")
  43113. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43114. __decorate([
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43117. __decorate([
  43118. BABYLON.serialize()
  43119. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43120. return StandardMaterial;
  43121. }(BABYLON.PushMaterial));
  43122. BABYLON.StandardMaterial = StandardMaterial;
  43123. })(BABYLON || (BABYLON = {}));
  43124. //# sourceMappingURL=babylon.standardMaterial.js.map
  43125. var BABYLON;
  43126. (function (BABYLON) {
  43127. /**
  43128. * Class representing spherical polynomial coefficients to the 3rd degree
  43129. */
  43130. var SphericalPolynomial = /** @class */ (function () {
  43131. function SphericalPolynomial() {
  43132. /**
  43133. * The x coefficients of the spherical polynomial
  43134. */
  43135. this.x = BABYLON.Vector3.Zero();
  43136. /**
  43137. * The y coefficients of the spherical polynomial
  43138. */
  43139. this.y = BABYLON.Vector3.Zero();
  43140. /**
  43141. * The z coefficients of the spherical polynomial
  43142. */
  43143. this.z = BABYLON.Vector3.Zero();
  43144. /**
  43145. * The xx coefficients of the spherical polynomial
  43146. */
  43147. this.xx = BABYLON.Vector3.Zero();
  43148. /**
  43149. * The yy coefficients of the spherical polynomial
  43150. */
  43151. this.yy = BABYLON.Vector3.Zero();
  43152. /**
  43153. * The zz coefficients of the spherical polynomial
  43154. */
  43155. this.zz = BABYLON.Vector3.Zero();
  43156. /**
  43157. * The xy coefficients of the spherical polynomial
  43158. */
  43159. this.xy = BABYLON.Vector3.Zero();
  43160. /**
  43161. * The yz coefficients of the spherical polynomial
  43162. */
  43163. this.yz = BABYLON.Vector3.Zero();
  43164. /**
  43165. * The zx coefficients of the spherical polynomial
  43166. */
  43167. this.zx = BABYLON.Vector3.Zero();
  43168. }
  43169. /**
  43170. * Adds an ambient color to the spherical polynomial
  43171. * @param color the color to add
  43172. */
  43173. SphericalPolynomial.prototype.addAmbient = function (color) {
  43174. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43175. this.xx = this.xx.add(colorVector);
  43176. this.yy = this.yy.add(colorVector);
  43177. this.zz = this.zz.add(colorVector);
  43178. };
  43179. /**
  43180. * Scales the spherical polynomial by the given amount
  43181. * @param scale the amount to scale
  43182. */
  43183. SphericalPolynomial.prototype.scale = function (scale) {
  43184. this.x = this.x.scale(scale);
  43185. this.y = this.y.scale(scale);
  43186. this.z = this.z.scale(scale);
  43187. this.xx = this.xx.scale(scale);
  43188. this.yy = this.yy.scale(scale);
  43189. this.zz = this.zz.scale(scale);
  43190. this.yz = this.yz.scale(scale);
  43191. this.zx = this.zx.scale(scale);
  43192. this.xy = this.xy.scale(scale);
  43193. };
  43194. /**
  43195. * Gets the spherical polynomial from harmonics
  43196. * @param harmonics the spherical harmonics
  43197. * @returns the spherical polynomial
  43198. */
  43199. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43200. var result = new SphericalPolynomial();
  43201. result.x = harmonics.l11.scale(1.02333);
  43202. result.y = harmonics.l1_1.scale(1.02333);
  43203. result.z = harmonics.l10.scale(1.02333);
  43204. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43205. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43206. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43207. result.yz = harmonics.l2_1.scale(0.858086);
  43208. result.zx = harmonics.l21.scale(0.858086);
  43209. result.xy = harmonics.l2_2.scale(0.858086);
  43210. result.scale(1.0 / Math.PI);
  43211. return result;
  43212. };
  43213. /**
  43214. * Constructs a spherical polynomial from an array.
  43215. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43216. * @returns the spherical polynomial
  43217. */
  43218. SphericalPolynomial.FromArray = function (data) {
  43219. var sp = new SphericalPolynomial();
  43220. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43221. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43222. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43223. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43224. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43225. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43226. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43227. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43228. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43229. return sp;
  43230. };
  43231. return SphericalPolynomial;
  43232. }());
  43233. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43234. /**
  43235. * Class representing spherical harmonics coefficients to the 3rd degree
  43236. */
  43237. var SphericalHarmonics = /** @class */ (function () {
  43238. function SphericalHarmonics() {
  43239. /**
  43240. * The l0,0 coefficients of the spherical harmonics
  43241. */
  43242. this.l00 = BABYLON.Vector3.Zero();
  43243. /**
  43244. * The l1,-1 coefficients of the spherical harmonics
  43245. */
  43246. this.l1_1 = BABYLON.Vector3.Zero();
  43247. /**
  43248. * The l1,0 coefficients of the spherical harmonics
  43249. */
  43250. this.l10 = BABYLON.Vector3.Zero();
  43251. /**
  43252. * The l1,1 coefficients of the spherical harmonics
  43253. */
  43254. this.l11 = BABYLON.Vector3.Zero();
  43255. /**
  43256. * The l2,-2 coefficients of the spherical harmonics
  43257. */
  43258. this.l2_2 = BABYLON.Vector3.Zero();
  43259. /**
  43260. * The l2,-1 coefficients of the spherical harmonics
  43261. */
  43262. this.l2_1 = BABYLON.Vector3.Zero();
  43263. /**
  43264. * The l2,0 coefficients of the spherical harmonics
  43265. */
  43266. this.l20 = BABYLON.Vector3.Zero();
  43267. /**
  43268. * The l2,1 coefficients of the spherical harmonics
  43269. */
  43270. this.l21 = BABYLON.Vector3.Zero();
  43271. /**
  43272. * The l2,2 coefficients of the spherical harmonics
  43273. */
  43274. this.lL22 = BABYLON.Vector3.Zero();
  43275. }
  43276. /**
  43277. * Adds a light to the spherical harmonics
  43278. * @param direction the direction of the light
  43279. * @param color the color of the light
  43280. * @param deltaSolidAngle the delta solid angle of the light
  43281. */
  43282. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43283. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43284. var c = colorVector.scale(deltaSolidAngle);
  43285. this.l00 = this.l00.add(c.scale(0.282095));
  43286. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43287. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43288. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43289. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43290. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43291. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43292. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43293. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43294. };
  43295. /**
  43296. * Scales the spherical harmonics by the given amount
  43297. * @param scale the amount to scale
  43298. */
  43299. SphericalHarmonics.prototype.scale = function (scale) {
  43300. this.l00 = this.l00.scale(scale);
  43301. this.l1_1 = this.l1_1.scale(scale);
  43302. this.l10 = this.l10.scale(scale);
  43303. this.l11 = this.l11.scale(scale);
  43304. this.l2_2 = this.l2_2.scale(scale);
  43305. this.l2_1 = this.l2_1.scale(scale);
  43306. this.l20 = this.l20.scale(scale);
  43307. this.l21 = this.l21.scale(scale);
  43308. this.lL22 = this.lL22.scale(scale);
  43309. };
  43310. /**
  43311. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43312. *
  43313. * ```
  43314. * E_lm = A_l * L_lm
  43315. * ```
  43316. *
  43317. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43318. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43319. * the scaling factors are given in equation 9.
  43320. */
  43321. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43322. // Constant (Band 0)
  43323. this.l00 = this.l00.scale(3.141593);
  43324. // Linear (Band 1)
  43325. this.l1_1 = this.l1_1.scale(2.094395);
  43326. this.l10 = this.l10.scale(2.094395);
  43327. this.l11 = this.l11.scale(2.094395);
  43328. // Quadratic (Band 2)
  43329. this.l2_2 = this.l2_2.scale(0.785398);
  43330. this.l2_1 = this.l2_1.scale(0.785398);
  43331. this.l20 = this.l20.scale(0.785398);
  43332. this.l21 = this.l21.scale(0.785398);
  43333. this.lL22 = this.lL22.scale(0.785398);
  43334. };
  43335. /**
  43336. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43337. *
  43338. * ```
  43339. * L = (1/pi) * E * rho
  43340. * ```
  43341. *
  43342. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43343. */
  43344. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43345. this.scale(1.0 / Math.PI);
  43346. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43347. // (The pixel shader must apply albedo after texture fetches, etc).
  43348. };
  43349. /**
  43350. * Gets the spherical harmonics from polynomial
  43351. * @param polynomial the spherical polynomial
  43352. * @returns the spherical harmonics
  43353. */
  43354. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43355. var result = new SphericalHarmonics();
  43356. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43357. result.l1_1 = polynomial.y.scale(0.977204);
  43358. result.l10 = polynomial.z.scale(0.977204);
  43359. result.l11 = polynomial.x.scale(0.977204);
  43360. result.l2_2 = polynomial.xy.scale(1.16538);
  43361. result.l2_1 = polynomial.yz.scale(1.16538);
  43362. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43363. result.l21 = polynomial.zx.scale(1.16538);
  43364. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43365. result.scale(Math.PI);
  43366. return result;
  43367. };
  43368. /**
  43369. * Constructs a spherical harmonics from an array.
  43370. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43371. * @returns the spherical harmonics
  43372. */
  43373. SphericalHarmonics.FromArray = function (data) {
  43374. var sh = new SphericalHarmonics();
  43375. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43376. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43377. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43378. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43379. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43380. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43381. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43382. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43383. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43384. return sh;
  43385. };
  43386. return SphericalHarmonics;
  43387. }());
  43388. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43389. })(BABYLON || (BABYLON = {}));
  43390. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43391. var BABYLON;
  43392. (function (BABYLON) {
  43393. var FileFaceOrientation = /** @class */ (function () {
  43394. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43395. this.name = name;
  43396. this.worldAxisForNormal = worldAxisForNormal;
  43397. this.worldAxisForFileX = worldAxisForFileX;
  43398. this.worldAxisForFileY = worldAxisForFileY;
  43399. }
  43400. return FileFaceOrientation;
  43401. }());
  43402. ;
  43403. /**
  43404. * Helper class dealing with the extraction of spherical polynomial dataArray
  43405. * from a cube map.
  43406. */
  43407. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43408. function CubeMapToSphericalPolynomialTools() {
  43409. }
  43410. /**
  43411. * Converts a texture to the according Spherical Polynomial data.
  43412. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43413. *
  43414. * @param texture The texture to extract the information from.
  43415. * @return The Spherical Polynomial data.
  43416. */
  43417. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43418. if (!texture.isCube) {
  43419. // Only supports cube Textures currently.
  43420. return null;
  43421. }
  43422. var size = texture.getSize().width;
  43423. var right = texture.readPixels(0);
  43424. var left = texture.readPixels(1);
  43425. var up;
  43426. var down;
  43427. if (texture.isRenderTarget) {
  43428. up = texture.readPixels(3);
  43429. down = texture.readPixels(2);
  43430. }
  43431. else {
  43432. up = texture.readPixels(2);
  43433. down = texture.readPixels(3);
  43434. }
  43435. var front = texture.readPixels(4);
  43436. var back = texture.readPixels(5);
  43437. var gammaSpace = texture.gammaSpace;
  43438. // Always read as RGBA.
  43439. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43440. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43441. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43442. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43443. }
  43444. var cubeInfo = {
  43445. size: size,
  43446. right: right,
  43447. left: left,
  43448. up: up,
  43449. down: down,
  43450. front: front,
  43451. back: back,
  43452. format: format,
  43453. type: type,
  43454. gammaSpace: gammaSpace,
  43455. };
  43456. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43457. };
  43458. /**
  43459. * Converts a cubemap to the according Spherical Polynomial data.
  43460. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43461. *
  43462. * @param cubeInfo The Cube map to extract the information from.
  43463. * @return The Spherical Polynomial data.
  43464. */
  43465. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43466. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43467. var totalSolidAngle = 0.0;
  43468. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43469. var du = 2.0 / cubeInfo.size;
  43470. var dv = du;
  43471. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43472. var minUV = du * 0.5 - 1.0;
  43473. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43474. var fileFace = this.FileFaces[faceIndex];
  43475. var dataArray = cubeInfo[fileFace.name];
  43476. var v = minUV;
  43477. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43478. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43479. // Because SP is still linear, so summation is fine in that basis.
  43480. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43481. for (var y = 0; y < cubeInfo.size; y++) {
  43482. var u = minUV;
  43483. for (var x = 0; x < cubeInfo.size; x++) {
  43484. // World direction (not normalised)
  43485. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43486. worldDirection.normalize();
  43487. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43488. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43489. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43490. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43491. // Handle Integer types.
  43492. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43493. r /= 255;
  43494. g /= 255;
  43495. b /= 255;
  43496. }
  43497. // Handle Gamma space textures.
  43498. if (cubeInfo.gammaSpace) {
  43499. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43500. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43501. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43502. }
  43503. var color = new BABYLON.Color3(r, g, b);
  43504. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43505. totalSolidAngle += deltaSolidAngle;
  43506. u += du;
  43507. }
  43508. v += dv;
  43509. }
  43510. }
  43511. // Solid angle for entire sphere is 4*pi
  43512. var sphereSolidAngle = 4.0 * Math.PI;
  43513. // Adjust the solid angle to allow for how many faces we processed.
  43514. var facesProcessed = 6.0;
  43515. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43516. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43517. // This is needed because the numerical integration over the cube uses a
  43518. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43519. // and also to compensate for accumulative error due to float precision in the summation.
  43520. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43521. sphericalHarmonics.scale(correctionFactor);
  43522. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43523. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43524. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43525. };
  43526. CubeMapToSphericalPolynomialTools.FileFaces = [
  43527. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43528. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43529. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43530. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43531. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43532. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43533. ];
  43534. return CubeMapToSphericalPolynomialTools;
  43535. }());
  43536. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43537. })(BABYLON || (BABYLON = {}));
  43538. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43539. var BABYLON;
  43540. (function (BABYLON) {
  43541. /**
  43542. * Manages the defines for the PBR Material.
  43543. * @hiddenChildren
  43544. */
  43545. var PBRMaterialDefines = /** @class */ (function (_super) {
  43546. __extends(PBRMaterialDefines, _super);
  43547. /**
  43548. * Initializes the PBR Material defines.
  43549. */
  43550. function PBRMaterialDefines() {
  43551. var _this = _super.call(this) || this;
  43552. _this.PBR = true;
  43553. _this.MAINUV1 = false;
  43554. _this.MAINUV2 = false;
  43555. _this.UV1 = false;
  43556. _this.UV2 = false;
  43557. _this.ALBEDO = false;
  43558. _this.ALBEDODIRECTUV = 0;
  43559. _this.VERTEXCOLOR = false;
  43560. _this.AMBIENT = false;
  43561. _this.AMBIENTDIRECTUV = 0;
  43562. _this.AMBIENTINGRAYSCALE = false;
  43563. _this.OPACITY = false;
  43564. _this.VERTEXALPHA = false;
  43565. _this.OPACITYDIRECTUV = 0;
  43566. _this.OPACITYRGB = false;
  43567. _this.ALPHATEST = false;
  43568. _this.DEPTHPREPASS = false;
  43569. _this.ALPHABLEND = false;
  43570. _this.ALPHAFROMALBEDO = false;
  43571. _this.ALPHATESTVALUE = "0.5";
  43572. _this.SPECULAROVERALPHA = false;
  43573. _this.RADIANCEOVERALPHA = false;
  43574. _this.ALPHAFRESNEL = false;
  43575. _this.LINEARALPHAFRESNEL = false;
  43576. _this.PREMULTIPLYALPHA = false;
  43577. _this.EMISSIVE = false;
  43578. _this.EMISSIVEDIRECTUV = 0;
  43579. _this.REFLECTIVITY = false;
  43580. _this.REFLECTIVITYDIRECTUV = 0;
  43581. _this.SPECULARTERM = false;
  43582. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43583. _this.MICROSURFACEAUTOMATIC = false;
  43584. _this.LODBASEDMICROSFURACE = false;
  43585. _this.MICROSURFACEMAP = false;
  43586. _this.MICROSURFACEMAPDIRECTUV = 0;
  43587. _this.METALLICWORKFLOW = false;
  43588. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43589. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43590. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43591. _this.AOSTOREINMETALMAPRED = false;
  43592. _this.ENVIRONMENTBRDF = false;
  43593. _this.NORMAL = false;
  43594. _this.TANGENT = false;
  43595. _this.BUMP = false;
  43596. _this.BUMPDIRECTUV = 0;
  43597. _this.OBJECTSPACE_NORMALMAP = false;
  43598. _this.PARALLAX = false;
  43599. _this.PARALLAXOCCLUSION = false;
  43600. _this.NORMALXYSCALE = true;
  43601. _this.LIGHTMAP = false;
  43602. _this.LIGHTMAPDIRECTUV = 0;
  43603. _this.USELIGHTMAPASSHADOWMAP = false;
  43604. _this.GAMMALIGHTMAP = false;
  43605. _this.REFLECTION = false;
  43606. _this.REFLECTIONMAP_3D = false;
  43607. _this.REFLECTIONMAP_SPHERICAL = false;
  43608. _this.REFLECTIONMAP_PLANAR = false;
  43609. _this.REFLECTIONMAP_CUBIC = false;
  43610. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43611. _this.REFLECTIONMAP_PROJECTION = false;
  43612. _this.REFLECTIONMAP_SKYBOX = false;
  43613. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43614. _this.REFLECTIONMAP_EXPLICIT = false;
  43615. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43616. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43617. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43618. _this.INVERTCUBICMAP = false;
  43619. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43620. _this.USESPHERICALINVERTEX = false;
  43621. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43622. _this.LODINREFLECTIONALPHA = false;
  43623. _this.GAMMAREFLECTION = false;
  43624. _this.RGBDREFLECTION = false;
  43625. _this.RADIANCEOCCLUSION = false;
  43626. _this.HORIZONOCCLUSION = false;
  43627. _this.REFRACTION = false;
  43628. _this.REFRACTIONMAP_3D = false;
  43629. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43630. _this.LODINREFRACTIONALPHA = false;
  43631. _this.GAMMAREFRACTION = false;
  43632. _this.RGBDREFRACTION = false;
  43633. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43634. _this.INSTANCES = false;
  43635. _this.NUM_BONE_INFLUENCERS = 0;
  43636. _this.BonesPerMesh = 0;
  43637. _this.NONUNIFORMSCALING = false;
  43638. _this.MORPHTARGETS = false;
  43639. _this.MORPHTARGETS_NORMAL = false;
  43640. _this.MORPHTARGETS_TANGENT = false;
  43641. _this.NUM_MORPH_INFLUENCERS = 0;
  43642. _this.IMAGEPROCESSING = false;
  43643. _this.VIGNETTE = false;
  43644. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43645. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43646. _this.TONEMAPPING = false;
  43647. _this.TONEMAPPING_ACES = false;
  43648. _this.CONTRAST = false;
  43649. _this.COLORCURVES = false;
  43650. _this.COLORGRADING = false;
  43651. _this.COLORGRADING3D = false;
  43652. _this.SAMPLER3DGREENDEPTH = false;
  43653. _this.SAMPLER3DBGRMAP = false;
  43654. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43655. _this.EXPOSURE = false;
  43656. _this.USEPHYSICALLIGHTFALLOFF = false;
  43657. _this.USEGLTFLIGHTFALLOFF = false;
  43658. _this.TWOSIDEDLIGHTING = false;
  43659. _this.SHADOWFLOAT = false;
  43660. _this.CLIPPLANE = false;
  43661. _this.CLIPPLANE2 = false;
  43662. _this.CLIPPLANE3 = false;
  43663. _this.CLIPPLANE4 = false;
  43664. _this.POINTSIZE = false;
  43665. _this.FOG = false;
  43666. _this.LOGARITHMICDEPTH = false;
  43667. _this.FORCENORMALFORWARD = false;
  43668. _this.SPECULARAA = false;
  43669. _this.UNLIT = false;
  43670. _this.rebuild();
  43671. return _this;
  43672. }
  43673. /**
  43674. * Resets the PBR Material defines.
  43675. */
  43676. PBRMaterialDefines.prototype.reset = function () {
  43677. _super.prototype.reset.call(this);
  43678. this.ALPHATESTVALUE = "0.5";
  43679. this.PBR = true;
  43680. };
  43681. return PBRMaterialDefines;
  43682. }(BABYLON.MaterialDefines));
  43683. /**
  43684. * The Physically based material base class of BJS.
  43685. *
  43686. * This offers the main features of a standard PBR material.
  43687. * For more information, please refer to the documentation :
  43688. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43689. */
  43690. var PBRBaseMaterial = /** @class */ (function (_super) {
  43691. __extends(PBRBaseMaterial, _super);
  43692. /**
  43693. * Instantiates a new PBRMaterial instance.
  43694. *
  43695. * @param name The material name
  43696. * @param scene The scene the material will be use in.
  43697. */
  43698. function PBRBaseMaterial(name, scene) {
  43699. var _this = _super.call(this, name, scene) || this;
  43700. /**
  43701. * Intensity of the direct lights e.g. the four lights available in your scene.
  43702. * This impacts both the direct diffuse and specular highlights.
  43703. */
  43704. _this._directIntensity = 1.0;
  43705. /**
  43706. * Intensity of the emissive part of the material.
  43707. * This helps controlling the emissive effect without modifying the emissive color.
  43708. */
  43709. _this._emissiveIntensity = 1.0;
  43710. /**
  43711. * Intensity of the environment e.g. how much the environment will light the object
  43712. * either through harmonics for rough material or through the refelction for shiny ones.
  43713. */
  43714. _this._environmentIntensity = 1.0;
  43715. /**
  43716. * This is a special control allowing the reduction of the specular highlights coming from the
  43717. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43718. */
  43719. _this._specularIntensity = 1.0;
  43720. /**
  43721. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43722. */
  43723. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43724. /**
  43725. * Debug Control allowing disabling the bump map on this material.
  43726. */
  43727. _this._disableBumpMap = false;
  43728. /**
  43729. * AKA Occlusion Texture Intensity in other nomenclature.
  43730. */
  43731. _this._ambientTextureStrength = 1.0;
  43732. /**
  43733. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43734. * 1 means it completely occludes it
  43735. * 0 mean it has no impact
  43736. */
  43737. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43738. /**
  43739. * The color of a material in ambient lighting.
  43740. */
  43741. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43742. /**
  43743. * AKA Diffuse Color in other nomenclature.
  43744. */
  43745. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43746. /**
  43747. * AKA Specular Color in other nomenclature.
  43748. */
  43749. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43750. /**
  43751. * The color applied when light is reflected from a material.
  43752. */
  43753. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43754. /**
  43755. * The color applied when light is emitted from a material.
  43756. */
  43757. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43758. /**
  43759. * AKA Glossiness in other nomenclature.
  43760. */
  43761. _this._microSurface = 0.9;
  43762. /**
  43763. * source material index of refraction (IOR)' / 'destination material IOR.
  43764. */
  43765. _this._indexOfRefraction = 0.66;
  43766. /**
  43767. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43768. */
  43769. _this._invertRefractionY = false;
  43770. /**
  43771. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43772. * Materials half opaque for instance using refraction could benefit from this control.
  43773. */
  43774. _this._linkRefractionWithTransparency = false;
  43775. /**
  43776. * Specifies that the material will use the light map as a show map.
  43777. */
  43778. _this._useLightmapAsShadowmap = false;
  43779. /**
  43780. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43781. * makes the reflect vector face the model (under horizon).
  43782. */
  43783. _this._useHorizonOcclusion = true;
  43784. /**
  43785. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43786. * too much the area relying on ambient texture to define their ambient occlusion.
  43787. */
  43788. _this._useRadianceOcclusion = true;
  43789. /**
  43790. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43791. */
  43792. _this._useAlphaFromAlbedoTexture = false;
  43793. /**
  43794. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43795. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43796. */
  43797. _this._useSpecularOverAlpha = true;
  43798. /**
  43799. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43800. */
  43801. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43802. /**
  43803. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43804. */
  43805. _this._useRoughnessFromMetallicTextureAlpha = true;
  43806. /**
  43807. * Specifies if the metallic texture contains the roughness information in its green channel.
  43808. */
  43809. _this._useRoughnessFromMetallicTextureGreen = false;
  43810. /**
  43811. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43812. */
  43813. _this._useMetallnessFromMetallicTextureBlue = false;
  43814. /**
  43815. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43816. */
  43817. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43818. /**
  43819. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43820. */
  43821. _this._useAmbientInGrayScale = false;
  43822. /**
  43823. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43824. * The material will try to infer what glossiness each pixel should be.
  43825. */
  43826. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43827. /**
  43828. * Defines the falloff type used in this material.
  43829. * It by default is Physical.
  43830. */
  43831. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43832. /**
  43833. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43834. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43835. */
  43836. _this._useRadianceOverAlpha = true;
  43837. /**
  43838. * Allows using an object space normal map (instead of tangent space).
  43839. */
  43840. _this._useObjectSpaceNormalMap = false;
  43841. /**
  43842. * Allows using the bump map in parallax mode.
  43843. */
  43844. _this._useParallax = false;
  43845. /**
  43846. * Allows using the bump map in parallax occlusion mode.
  43847. */
  43848. _this._useParallaxOcclusion = false;
  43849. /**
  43850. * Controls the scale bias of the parallax mode.
  43851. */
  43852. _this._parallaxScaleBias = 0.05;
  43853. /**
  43854. * If sets to true, disables all the lights affecting the material.
  43855. */
  43856. _this._disableLighting = false;
  43857. /**
  43858. * Number of Simultaneous lights allowed on the material.
  43859. */
  43860. _this._maxSimultaneousLights = 4;
  43861. /**
  43862. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43863. */
  43864. _this._invertNormalMapX = false;
  43865. /**
  43866. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43867. */
  43868. _this._invertNormalMapY = false;
  43869. /**
  43870. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43871. */
  43872. _this._twoSidedLighting = false;
  43873. /**
  43874. * Defines the alpha limits in alpha test mode.
  43875. */
  43876. _this._alphaCutOff = 0.4;
  43877. /**
  43878. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43879. */
  43880. _this._forceAlphaTest = false;
  43881. /**
  43882. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43883. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43884. */
  43885. _this._useAlphaFresnel = false;
  43886. /**
  43887. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43888. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43889. */
  43890. _this._useLinearAlphaFresnel = false;
  43891. /**
  43892. * The transparency mode of the material.
  43893. */
  43894. _this._transparencyMode = null;
  43895. /**
  43896. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43897. * from cos thetav and roughness:
  43898. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43899. */
  43900. _this._environmentBRDFTexture = null;
  43901. /**
  43902. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43903. */
  43904. _this._forceIrradianceInFragment = false;
  43905. /**
  43906. * Force normal to face away from face.
  43907. */
  43908. _this._forceNormalForward = false;
  43909. /**
  43910. * Enables specular anti aliasing in the PBR shader.
  43911. * It will both interacts on the Geometry for analytical and IBL lighting.
  43912. * It also prefilter the roughness map based on the bump values.
  43913. */
  43914. _this._enableSpecularAntiAliasing = false;
  43915. /**
  43916. * Stores the available render targets.
  43917. */
  43918. _this._renderTargets = new BABYLON.SmartArray(16);
  43919. /**
  43920. * Sets the global ambient color for the material used in lighting calculations.
  43921. */
  43922. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43923. /**
  43924. * If set to true, no lighting calculations will be applied.
  43925. */
  43926. _this._unlit = false;
  43927. // Setup the default processing configuration to the scene.
  43928. _this._attachImageProcessingConfiguration(null);
  43929. _this.getRenderTargetTextures = function () {
  43930. _this._renderTargets.reset();
  43931. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43932. _this._renderTargets.push(_this._reflectionTexture);
  43933. }
  43934. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43935. _this._renderTargets.push(_this._refractionTexture);
  43936. }
  43937. return _this._renderTargets;
  43938. };
  43939. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43940. return _this;
  43941. }
  43942. /**
  43943. * Attaches a new image processing configuration to the PBR Material.
  43944. * @param configuration
  43945. */
  43946. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43947. var _this = this;
  43948. if (configuration === this._imageProcessingConfiguration) {
  43949. return;
  43950. }
  43951. // Detaches observer.
  43952. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43953. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43954. }
  43955. // Pick the scene configuration if needed.
  43956. if (!configuration) {
  43957. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43958. }
  43959. else {
  43960. this._imageProcessingConfiguration = configuration;
  43961. }
  43962. // Attaches observer.
  43963. if (this._imageProcessingConfiguration) {
  43964. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43965. _this._markAllSubMeshesAsImageProcessingDirty();
  43966. });
  43967. }
  43968. };
  43969. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43970. /**
  43971. * Gets a boolean indicating that current material needs to register RTT
  43972. */
  43973. get: function () {
  43974. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43975. return true;
  43976. }
  43977. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43978. return true;
  43979. }
  43980. return false;
  43981. },
  43982. enumerable: true,
  43983. configurable: true
  43984. });
  43985. /**
  43986. * Gets the name of the material class.
  43987. */
  43988. PBRBaseMaterial.prototype.getClassName = function () {
  43989. return "PBRBaseMaterial";
  43990. };
  43991. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43992. /**
  43993. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43994. */
  43995. get: function () {
  43996. return this._useLogarithmicDepth;
  43997. },
  43998. /**
  43999. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44000. */
  44001. set: function (value) {
  44002. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44003. },
  44004. enumerable: true,
  44005. configurable: true
  44006. });
  44007. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44008. /**
  44009. * Gets the current transparency mode.
  44010. */
  44011. get: function () {
  44012. return this._transparencyMode;
  44013. },
  44014. /**
  44015. * Sets the transparency mode of the material.
  44016. *
  44017. * | Value | Type | Description |
  44018. * | ----- | ----------------------------------- | ----------- |
  44019. * | 0 | OPAQUE | |
  44020. * | 1 | ALPHATEST | |
  44021. * | 2 | ALPHABLEND | |
  44022. * | 3 | ALPHATESTANDBLEND | |
  44023. *
  44024. */
  44025. set: function (value) {
  44026. if (this._transparencyMode === value) {
  44027. return;
  44028. }
  44029. this._transparencyMode = value;
  44030. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44031. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44032. },
  44033. enumerable: true,
  44034. configurable: true
  44035. });
  44036. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44037. /**
  44038. * Returns true if alpha blending should be disabled.
  44039. */
  44040. get: function () {
  44041. return (this._linkRefractionWithTransparency ||
  44042. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44043. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44044. },
  44045. enumerable: true,
  44046. configurable: true
  44047. });
  44048. /**
  44049. * Specifies whether or not this material should be rendered in alpha blend mode.
  44050. */
  44051. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44052. if (this._disableAlphaBlending) {
  44053. return false;
  44054. }
  44055. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44056. };
  44057. /**
  44058. * Specifies if the mesh will require alpha blending.
  44059. * @param mesh - BJS mesh.
  44060. */
  44061. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44062. if (this._disableAlphaBlending) {
  44063. return false;
  44064. }
  44065. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44066. };
  44067. /**
  44068. * Specifies whether or not this material should be rendered in alpha test mode.
  44069. */
  44070. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44071. if (this._forceAlphaTest) {
  44072. return true;
  44073. }
  44074. if (this._linkRefractionWithTransparency) {
  44075. return false;
  44076. }
  44077. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44078. };
  44079. /**
  44080. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44081. */
  44082. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44083. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44084. };
  44085. /**
  44086. * Gets the texture used for the alpha test.
  44087. */
  44088. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44089. return this._albedoTexture;
  44090. };
  44091. /**
  44092. * Specifies that the submesh is ready to be used.
  44093. * @param mesh - BJS mesh.
  44094. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44095. * @param useInstances - Specifies that instances should be used.
  44096. * @returns - boolean indicating that the submesh is ready or not.
  44097. */
  44098. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44099. if (subMesh.effect && this.isFrozen) {
  44100. if (this._wasPreviouslyReady) {
  44101. return true;
  44102. }
  44103. }
  44104. if (!subMesh._materialDefines) {
  44105. subMesh._materialDefines = new PBRMaterialDefines();
  44106. }
  44107. var defines = subMesh._materialDefines;
  44108. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44109. if (defines._renderId === this.getScene().getRenderId()) {
  44110. return true;
  44111. }
  44112. }
  44113. var scene = this.getScene();
  44114. var engine = scene.getEngine();
  44115. if (defines._areTexturesDirty) {
  44116. if (scene.texturesEnabled) {
  44117. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44118. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44119. return false;
  44120. }
  44121. }
  44122. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44123. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44124. return false;
  44125. }
  44126. }
  44127. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44128. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44129. return false;
  44130. }
  44131. }
  44132. var reflectionTexture = this._getReflectionTexture();
  44133. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44134. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44135. return false;
  44136. }
  44137. }
  44138. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44139. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44140. return false;
  44141. }
  44142. }
  44143. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44144. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44145. return false;
  44146. }
  44147. }
  44148. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44149. if (this._metallicTexture) {
  44150. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44151. return false;
  44152. }
  44153. }
  44154. else if (this._reflectivityTexture) {
  44155. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44156. return false;
  44157. }
  44158. }
  44159. if (this._microSurfaceTexture) {
  44160. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44161. return false;
  44162. }
  44163. }
  44164. }
  44165. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44166. // Bump texture cannot be not blocking.
  44167. if (!this._bumpTexture.isReady()) {
  44168. return false;
  44169. }
  44170. }
  44171. var refractionTexture = this._getRefractionTexture();
  44172. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44173. if (!refractionTexture.isReadyOrNotBlocking()) {
  44174. return false;
  44175. }
  44176. }
  44177. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44178. // This is blocking.
  44179. if (!this._environmentBRDFTexture.isReady()) {
  44180. return false;
  44181. }
  44182. }
  44183. }
  44184. }
  44185. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44186. if (!this._imageProcessingConfiguration.isReady()) {
  44187. return false;
  44188. }
  44189. }
  44190. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44191. mesh.createNormals(true);
  44192. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44193. }
  44194. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44195. if (effect) {
  44196. scene.resetCachedMaterial();
  44197. subMesh.setEffect(effect, defines);
  44198. this.buildUniformLayout();
  44199. }
  44200. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44201. return false;
  44202. }
  44203. defines._renderId = scene.getRenderId();
  44204. this._wasPreviouslyReady = true;
  44205. return true;
  44206. };
  44207. /**
  44208. * Specifies if the material uses metallic roughness workflow.
  44209. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44210. */
  44211. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44212. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44213. return true;
  44214. }
  44215. return false;
  44216. };
  44217. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44218. if (onCompiled === void 0) { onCompiled = null; }
  44219. if (onError === void 0) { onError = null; }
  44220. if (useInstances === void 0) { useInstances = null; }
  44221. if (useClipPlane === void 0) { useClipPlane = null; }
  44222. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44223. if (!defines.isDirty) {
  44224. return null;
  44225. }
  44226. defines.markAsProcessed();
  44227. var scene = this.getScene();
  44228. var engine = scene.getEngine();
  44229. // Fallbacks
  44230. var fallbacks = new BABYLON.EffectFallbacks();
  44231. var fallbackRank = 0;
  44232. if (defines.USESPHERICALINVERTEX) {
  44233. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44234. }
  44235. if (defines.FOG) {
  44236. fallbacks.addFallback(fallbackRank, "FOG");
  44237. }
  44238. if (defines.SPECULARAA) {
  44239. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44240. }
  44241. if (defines.POINTSIZE) {
  44242. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44243. }
  44244. if (defines.LOGARITHMICDEPTH) {
  44245. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44246. }
  44247. if (defines.PARALLAX) {
  44248. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44249. }
  44250. if (defines.PARALLAXOCCLUSION) {
  44251. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44252. }
  44253. if (defines.ENVIRONMENTBRDF) {
  44254. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44255. }
  44256. if (defines.TANGENT) {
  44257. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44258. }
  44259. if (defines.BUMP) {
  44260. fallbacks.addFallback(fallbackRank++, "BUMP");
  44261. }
  44262. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44263. if (defines.SPECULARTERM) {
  44264. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44265. }
  44266. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44267. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44268. }
  44269. if (defines.LIGHTMAP) {
  44270. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44271. }
  44272. if (defines.NORMAL) {
  44273. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44274. }
  44275. if (defines.AMBIENT) {
  44276. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44277. }
  44278. if (defines.EMISSIVE) {
  44279. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44280. }
  44281. if (defines.VERTEXCOLOR) {
  44282. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44283. }
  44284. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44285. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44286. }
  44287. if (defines.MORPHTARGETS) {
  44288. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44289. }
  44290. //Attributes
  44291. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44292. if (defines.NORMAL) {
  44293. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44294. }
  44295. if (defines.TANGENT) {
  44296. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44297. }
  44298. if (defines.UV1) {
  44299. attribs.push(BABYLON.VertexBuffer.UVKind);
  44300. }
  44301. if (defines.UV2) {
  44302. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44303. }
  44304. if (defines.VERTEXCOLOR) {
  44305. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44306. }
  44307. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44308. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44309. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44310. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44311. "vFogInfos", "vFogColor", "pointSize",
  44312. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44313. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44314. "mBones",
  44315. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44316. "vLightingIntensity",
  44317. "logarithmicDepthConstant",
  44318. "vSphericalX", "vSphericalY", "vSphericalZ",
  44319. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44320. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44321. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44322. "vTangentSpaceParams"
  44323. ];
  44324. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44325. "bumpSampler", "lightmapSampler", "opacitySampler",
  44326. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44327. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44328. "microSurfaceSampler", "environmentBrdfSampler"];
  44329. var uniformBuffers = ["Material", "Scene"];
  44330. if (BABYLON.ImageProcessingConfiguration) {
  44331. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44332. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44333. }
  44334. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44335. uniformsNames: uniforms,
  44336. uniformBuffersNames: uniformBuffers,
  44337. samplers: samplers,
  44338. defines: defines,
  44339. maxSimultaneousLights: this._maxSimultaneousLights
  44340. });
  44341. var join = defines.toString();
  44342. return engine.createEffect("pbr", {
  44343. attributes: attribs,
  44344. uniformsNames: uniforms,
  44345. uniformBuffersNames: uniformBuffers,
  44346. samplers: samplers,
  44347. defines: join,
  44348. fallbacks: fallbacks,
  44349. onCompiled: onCompiled,
  44350. onError: onError,
  44351. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44352. }, engine);
  44353. };
  44354. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44355. if (useInstances === void 0) { useInstances = null; }
  44356. if (useClipPlane === void 0) { useClipPlane = null; }
  44357. var scene = this.getScene();
  44358. var engine = scene.getEngine();
  44359. // Lights
  44360. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44361. defines._needNormals = true;
  44362. // Textures
  44363. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44364. if (defines._areTexturesDirty) {
  44365. defines._needUVs = false;
  44366. if (scene.texturesEnabled) {
  44367. if (scene.getEngine().getCaps().textureLOD) {
  44368. defines.LODBASEDMICROSFURACE = true;
  44369. }
  44370. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44371. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44372. }
  44373. else {
  44374. defines.ALBEDO = false;
  44375. }
  44376. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44377. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44378. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44379. }
  44380. else {
  44381. defines.AMBIENT = false;
  44382. }
  44383. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44384. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44385. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44386. }
  44387. else {
  44388. defines.OPACITY = false;
  44389. }
  44390. var reflectionTexture = this._getReflectionTexture();
  44391. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44392. defines.REFLECTION = true;
  44393. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44394. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44395. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44396. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44397. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44398. defines.INVERTCUBICMAP = true;
  44399. }
  44400. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44401. switch (reflectionTexture.coordinatesMode) {
  44402. case BABYLON.Texture.EXPLICIT_MODE:
  44403. defines.REFLECTIONMAP_EXPLICIT = true;
  44404. break;
  44405. case BABYLON.Texture.PLANAR_MODE:
  44406. defines.REFLECTIONMAP_PLANAR = true;
  44407. break;
  44408. case BABYLON.Texture.PROJECTION_MODE:
  44409. defines.REFLECTIONMAP_PROJECTION = true;
  44410. break;
  44411. case BABYLON.Texture.SKYBOX_MODE:
  44412. defines.REFLECTIONMAP_SKYBOX = true;
  44413. break;
  44414. case BABYLON.Texture.SPHERICAL_MODE:
  44415. defines.REFLECTIONMAP_SPHERICAL = true;
  44416. break;
  44417. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44418. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44419. break;
  44420. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44421. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44422. break;
  44423. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44424. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44425. break;
  44426. case BABYLON.Texture.CUBIC_MODE:
  44427. case BABYLON.Texture.INVCUBIC_MODE:
  44428. default:
  44429. defines.REFLECTIONMAP_CUBIC = true;
  44430. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44431. break;
  44432. }
  44433. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44434. if (reflectionTexture.sphericalPolynomial) {
  44435. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44436. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44437. defines.USESPHERICALINVERTEX = false;
  44438. }
  44439. else {
  44440. defines.USESPHERICALINVERTEX = true;
  44441. }
  44442. }
  44443. }
  44444. else {
  44445. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44446. }
  44447. }
  44448. else {
  44449. defines.REFLECTION = false;
  44450. defines.REFLECTIONMAP_3D = false;
  44451. defines.REFLECTIONMAP_SPHERICAL = false;
  44452. defines.REFLECTIONMAP_PLANAR = false;
  44453. defines.REFLECTIONMAP_CUBIC = false;
  44454. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44455. defines.REFLECTIONMAP_PROJECTION = false;
  44456. defines.REFLECTIONMAP_SKYBOX = false;
  44457. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44458. defines.REFLECTIONMAP_EXPLICIT = false;
  44459. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44460. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44461. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44462. defines.INVERTCUBICMAP = false;
  44463. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44464. defines.USESPHERICALINVERTEX = false;
  44465. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44466. defines.LODINREFLECTIONALPHA = false;
  44467. defines.GAMMAREFLECTION = false;
  44468. defines.RGBDREFLECTION = false;
  44469. }
  44470. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44472. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44473. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44474. }
  44475. else {
  44476. defines.LIGHTMAP = false;
  44477. }
  44478. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44479. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44480. }
  44481. else {
  44482. defines.EMISSIVE = false;
  44483. }
  44484. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44485. if (this._metallicTexture) {
  44486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44487. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44488. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44489. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44490. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44491. }
  44492. else if (this._reflectivityTexture) {
  44493. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44494. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44495. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44496. }
  44497. else {
  44498. defines.REFLECTIVITY = false;
  44499. }
  44500. if (this._microSurfaceTexture) {
  44501. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44502. }
  44503. else {
  44504. defines.MICROSURFACEMAP = false;
  44505. }
  44506. }
  44507. else {
  44508. defines.REFLECTIVITY = false;
  44509. defines.MICROSURFACEMAP = false;
  44510. }
  44511. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44513. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44514. defines.PARALLAX = true;
  44515. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44516. }
  44517. else {
  44518. defines.PARALLAX = false;
  44519. }
  44520. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44521. }
  44522. else {
  44523. defines.BUMP = false;
  44524. }
  44525. var refractionTexture = this._getRefractionTexture();
  44526. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44527. defines.REFRACTION = true;
  44528. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44529. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44530. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44531. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44532. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44533. if (this._linkRefractionWithTransparency) {
  44534. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44535. }
  44536. }
  44537. else {
  44538. defines.REFRACTION = false;
  44539. }
  44540. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44541. defines.ENVIRONMENTBRDF = true;
  44542. }
  44543. else {
  44544. defines.ENVIRONMENTBRDF = false;
  44545. }
  44546. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44547. defines.ALPHAFROMALBEDO = true;
  44548. }
  44549. else {
  44550. defines.ALPHAFROMALBEDO = false;
  44551. }
  44552. }
  44553. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44554. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44555. defines.USEPHYSICALLIGHTFALLOFF = false;
  44556. defines.USEGLTFLIGHTFALLOFF = false;
  44557. }
  44558. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44559. defines.USEPHYSICALLIGHTFALLOFF = false;
  44560. defines.USEGLTFLIGHTFALLOFF = true;
  44561. }
  44562. else {
  44563. defines.USEPHYSICALLIGHTFALLOFF = true;
  44564. defines.USEGLTFLIGHTFALLOFF = false;
  44565. }
  44566. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44567. if (!this.backFaceCulling && this._twoSidedLighting) {
  44568. defines.TWOSIDEDLIGHTING = true;
  44569. }
  44570. else {
  44571. defines.TWOSIDEDLIGHTING = false;
  44572. }
  44573. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44574. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44575. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44576. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44577. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44578. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44579. }
  44580. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44581. this._imageProcessingConfiguration.prepareDefines(defines);
  44582. }
  44583. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44584. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44585. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44586. // Misc.
  44587. if (defines._areMiscDirty) {
  44588. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44589. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44590. }
  44591. // Values that need to be evaluated on every frame
  44592. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44593. // Attribs
  44594. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44595. };
  44596. /**
  44597. * Force shader compilation
  44598. */
  44599. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44600. var _this = this;
  44601. var localOptions = __assign({ clipPlane: false }, options);
  44602. var defines = new PBRMaterialDefines();
  44603. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44604. if (effect.isReady()) {
  44605. if (onCompiled) {
  44606. onCompiled(this);
  44607. }
  44608. }
  44609. else {
  44610. effect.onCompileObservable.add(function () {
  44611. if (onCompiled) {
  44612. onCompiled(_this);
  44613. }
  44614. });
  44615. }
  44616. };
  44617. /**
  44618. * Initializes the uniform buffer layout for the shader.
  44619. */
  44620. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44621. // Order is important !
  44622. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44623. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44624. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44625. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44626. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44627. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44628. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44629. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44630. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44631. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44632. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44633. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44634. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44635. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44636. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44637. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44638. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44639. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44640. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44641. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44642. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44643. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44644. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44645. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44646. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44647. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44648. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44649. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44650. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44651. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44652. this._uniformBuffer.addUniform("pointSize", 1);
  44653. this._uniformBuffer.create();
  44654. };
  44655. /**
  44656. * Unbinds the textures.
  44657. */
  44658. PBRBaseMaterial.prototype.unbind = function () {
  44659. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44660. this._uniformBuffer.setTexture("reflectionSampler", null);
  44661. }
  44662. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44663. this._uniformBuffer.setTexture("refractionSampler", null);
  44664. }
  44665. _super.prototype.unbind.call(this);
  44666. };
  44667. /**
  44668. * Binds the submesh data.
  44669. * @param world - The world matrix.
  44670. * @param mesh - The BJS mesh.
  44671. * @param subMesh - A submesh of the BJS mesh.
  44672. */
  44673. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44674. var scene = this.getScene();
  44675. var defines = subMesh._materialDefines;
  44676. if (!defines) {
  44677. return;
  44678. }
  44679. var effect = subMesh.effect;
  44680. if (!effect) {
  44681. return;
  44682. }
  44683. this._activeEffect = effect;
  44684. // Matrices
  44685. this.bindOnlyWorldMatrix(world);
  44686. // Normal Matrix
  44687. if (defines.OBJECTSPACE_NORMALMAP) {
  44688. world.toNormalMatrix(this._normalMatrix);
  44689. this.bindOnlyNormalMatrix(this._normalMatrix);
  44690. }
  44691. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44692. // Bones
  44693. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44694. var reflectionTexture = null;
  44695. if (mustRebind) {
  44696. this._uniformBuffer.bindToEffect(effect, "Material");
  44697. this.bindViewProjection(effect);
  44698. reflectionTexture = this._getReflectionTexture();
  44699. var refractionTexture = this._getRefractionTexture();
  44700. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44701. // Texture uniforms
  44702. if (scene.texturesEnabled) {
  44703. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44704. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44705. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44706. }
  44707. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44708. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44709. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44710. }
  44711. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44712. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44713. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44714. }
  44715. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44716. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44717. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44718. if (reflectionTexture.boundingBoxSize) {
  44719. var cubeTexture = reflectionTexture;
  44720. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44721. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44722. }
  44723. var polynomials = reflectionTexture.sphericalPolynomial;
  44724. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44725. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44726. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44727. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44728. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44729. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44730. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44731. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44732. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44733. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44734. }
  44735. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44736. }
  44737. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44738. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44739. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44740. }
  44741. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44742. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44743. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44744. }
  44745. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44746. if (this._metallicTexture) {
  44747. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44748. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44749. }
  44750. else if (this._reflectivityTexture) {
  44751. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44752. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44753. }
  44754. if (this._microSurfaceTexture) {
  44755. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44756. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44757. }
  44758. }
  44759. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44760. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44761. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44762. if (scene._mirroredCameraPosition) {
  44763. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44764. }
  44765. else {
  44766. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44767. }
  44768. }
  44769. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44770. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44771. var depth = 1.0;
  44772. if (!refractionTexture.isCube) {
  44773. if (refractionTexture.depth) {
  44774. depth = refractionTexture.depth;
  44775. }
  44776. }
  44777. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44778. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44779. }
  44780. }
  44781. // Point size
  44782. if (this.pointsCloud) {
  44783. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44784. }
  44785. // Colors
  44786. if (defines.METALLICWORKFLOW) {
  44787. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44788. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44789. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44790. }
  44791. else {
  44792. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44793. }
  44794. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44795. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44796. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44797. // Misc
  44798. this._lightingInfos.x = this._directIntensity;
  44799. this._lightingInfos.y = this._emissiveIntensity;
  44800. this._lightingInfos.z = this._environmentIntensity;
  44801. this._lightingInfos.w = this._specularIntensity;
  44802. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44803. }
  44804. // Textures
  44805. if (scene.texturesEnabled) {
  44806. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44807. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44808. }
  44809. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44810. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44811. }
  44812. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44813. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44814. }
  44815. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44816. if (defines.LODBASEDMICROSFURACE) {
  44817. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44818. }
  44819. else {
  44820. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44821. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44822. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44823. }
  44824. }
  44825. if (defines.ENVIRONMENTBRDF) {
  44826. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44827. }
  44828. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44829. if (defines.LODBASEDMICROSFURACE) {
  44830. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44831. }
  44832. else {
  44833. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44834. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44835. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44836. }
  44837. }
  44838. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44839. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44840. }
  44841. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44842. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44843. }
  44844. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44845. if (this._metallicTexture) {
  44846. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44847. }
  44848. else if (this._reflectivityTexture) {
  44849. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44850. }
  44851. if (this._microSurfaceTexture) {
  44852. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44853. }
  44854. }
  44855. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44856. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44857. }
  44858. }
  44859. // Clip plane
  44860. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44861. // Colors
  44862. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44863. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44864. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44865. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44866. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44867. }
  44868. if (mustRebind || !this.isFrozen) {
  44869. // Lights
  44870. if (scene.lightsEnabled && !this._disableLighting) {
  44871. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44872. }
  44873. // View
  44874. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44875. this.bindView(effect);
  44876. }
  44877. // Fog
  44878. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  44879. // Morph targets
  44880. if (defines.NUM_MORPH_INFLUENCERS) {
  44881. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44882. }
  44883. // image processing
  44884. this._imageProcessingConfiguration.bind(this._activeEffect);
  44885. // Log. depth
  44886. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44887. }
  44888. this._uniformBuffer.update();
  44889. this._afterBind(mesh, this._activeEffect);
  44890. };
  44891. /**
  44892. * Returns the animatable textures.
  44893. * @returns - Array of animatable textures.
  44894. */
  44895. PBRBaseMaterial.prototype.getAnimatables = function () {
  44896. var results = [];
  44897. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44898. results.push(this._albedoTexture);
  44899. }
  44900. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44901. results.push(this._ambientTexture);
  44902. }
  44903. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44904. results.push(this._opacityTexture);
  44905. }
  44906. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44907. results.push(this._reflectionTexture);
  44908. }
  44909. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44910. results.push(this._emissiveTexture);
  44911. }
  44912. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44913. results.push(this._metallicTexture);
  44914. }
  44915. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44916. results.push(this._reflectivityTexture);
  44917. }
  44918. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44919. results.push(this._bumpTexture);
  44920. }
  44921. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44922. results.push(this._lightmapTexture);
  44923. }
  44924. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44925. results.push(this._refractionTexture);
  44926. }
  44927. return results;
  44928. };
  44929. /**
  44930. * Returns the texture used for reflections.
  44931. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44932. */
  44933. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44934. if (this._reflectionTexture) {
  44935. return this._reflectionTexture;
  44936. }
  44937. return this.getScene().environmentTexture;
  44938. };
  44939. /**
  44940. * Returns the texture used for refraction or null if none is used.
  44941. * @returns - Refection texture if present. If no refraction texture and refraction
  44942. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44943. */
  44944. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44945. if (this._refractionTexture) {
  44946. return this._refractionTexture;
  44947. }
  44948. if (this._linkRefractionWithTransparency) {
  44949. return this.getScene().environmentTexture;
  44950. }
  44951. return null;
  44952. };
  44953. /**
  44954. * Disposes the resources of the material.
  44955. * @param forceDisposeEffect - Forces the disposal of effects.
  44956. * @param forceDisposeTextures - Forces the disposal of all textures.
  44957. */
  44958. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44959. if (forceDisposeTextures) {
  44960. if (this._albedoTexture) {
  44961. this._albedoTexture.dispose();
  44962. }
  44963. if (this._ambientTexture) {
  44964. this._ambientTexture.dispose();
  44965. }
  44966. if (this._opacityTexture) {
  44967. this._opacityTexture.dispose();
  44968. }
  44969. if (this._reflectionTexture) {
  44970. this._reflectionTexture.dispose();
  44971. }
  44972. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44973. this._environmentBRDFTexture.dispose();
  44974. }
  44975. if (this._emissiveTexture) {
  44976. this._emissiveTexture.dispose();
  44977. }
  44978. if (this._metallicTexture) {
  44979. this._metallicTexture.dispose();
  44980. }
  44981. if (this._reflectivityTexture) {
  44982. this._reflectivityTexture.dispose();
  44983. }
  44984. if (this._bumpTexture) {
  44985. this._bumpTexture.dispose();
  44986. }
  44987. if (this._lightmapTexture) {
  44988. this._lightmapTexture.dispose();
  44989. }
  44990. if (this._refractionTexture) {
  44991. this._refractionTexture.dispose();
  44992. }
  44993. }
  44994. this._renderTargets.dispose();
  44995. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44996. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44997. }
  44998. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44999. };
  45000. /**
  45001. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45002. */
  45003. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45004. /**
  45005. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45006. * to enhance interoperability with other engines.
  45007. */
  45008. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45009. /**
  45010. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45011. * to enhance interoperability with other materials.
  45012. */
  45013. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45014. /**
  45015. * Stores the reflectivity values based on metallic roughness workflow.
  45016. */
  45017. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45018. __decorate([
  45019. BABYLON.serializeAsImageProcessingConfiguration()
  45020. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45021. __decorate([
  45022. BABYLON.serialize()
  45023. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45024. __decorate([
  45025. BABYLON.serialize()
  45026. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45027. return PBRBaseMaterial;
  45028. }(BABYLON.PushMaterial));
  45029. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45030. })(BABYLON || (BABYLON = {}));
  45031. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45032. var BABYLON;
  45033. (function (BABYLON) {
  45034. /**
  45035. * The Physically based simple base material of BJS.
  45036. *
  45037. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45038. * It is used as the base class for both the specGloss and metalRough conventions.
  45039. */
  45040. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45041. __extends(PBRBaseSimpleMaterial, _super);
  45042. /**
  45043. * Instantiates a new PBRMaterial instance.
  45044. *
  45045. * @param name The material name
  45046. * @param scene The scene the material will be use in.
  45047. */
  45048. function PBRBaseSimpleMaterial(name, scene) {
  45049. var _this = _super.call(this, name, scene) || this;
  45050. /**
  45051. * Number of Simultaneous lights allowed on the material.
  45052. */
  45053. _this.maxSimultaneousLights = 4;
  45054. /**
  45055. * If sets to true, disables all the lights affecting the material.
  45056. */
  45057. _this.disableLighting = false;
  45058. /**
  45059. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45060. */
  45061. _this.invertNormalMapX = false;
  45062. /**
  45063. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45064. */
  45065. _this.invertNormalMapY = false;
  45066. /**
  45067. * Emissivie color used to self-illuminate the model.
  45068. */
  45069. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45070. /**
  45071. * Occlusion Channel Strenght.
  45072. */
  45073. _this.occlusionStrength = 1.0;
  45074. _this.useLightmapAsShadowmap = false;
  45075. _this._useAlphaFromAlbedoTexture = true;
  45076. _this._useAmbientInGrayScale = true;
  45077. return _this;
  45078. }
  45079. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45080. /**
  45081. * Gets the current double sided mode.
  45082. */
  45083. get: function () {
  45084. return this._twoSidedLighting;
  45085. },
  45086. /**
  45087. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45088. */
  45089. set: function (value) {
  45090. if (this._twoSidedLighting === value) {
  45091. return;
  45092. }
  45093. this._twoSidedLighting = value;
  45094. this.backFaceCulling = !value;
  45095. this._markAllSubMeshesAsTexturesDirty();
  45096. },
  45097. enumerable: true,
  45098. configurable: true
  45099. });
  45100. /**
  45101. * Return the active textures of the material.
  45102. */
  45103. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45104. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45105. if (this.environmentTexture) {
  45106. activeTextures.push(this.environmentTexture);
  45107. }
  45108. if (this.normalTexture) {
  45109. activeTextures.push(this.normalTexture);
  45110. }
  45111. if (this.emissiveTexture) {
  45112. activeTextures.push(this.emissiveTexture);
  45113. }
  45114. if (this.occlusionTexture) {
  45115. activeTextures.push(this.occlusionTexture);
  45116. }
  45117. if (this.lightmapTexture) {
  45118. activeTextures.push(this.lightmapTexture);
  45119. }
  45120. return activeTextures;
  45121. };
  45122. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45123. if (_super.prototype.hasTexture.call(this, texture)) {
  45124. return true;
  45125. }
  45126. if (this.lightmapTexture === texture) {
  45127. return true;
  45128. }
  45129. return false;
  45130. };
  45131. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45132. return "PBRBaseSimpleMaterial";
  45133. };
  45134. __decorate([
  45135. BABYLON.serialize(),
  45136. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45137. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45138. __decorate([
  45139. BABYLON.serialize(),
  45140. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45141. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45142. __decorate([
  45143. BABYLON.serializeAsTexture(),
  45144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45145. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45146. __decorate([
  45147. BABYLON.serialize(),
  45148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45149. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45150. __decorate([
  45151. BABYLON.serialize(),
  45152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45153. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45154. __decorate([
  45155. BABYLON.serializeAsTexture(),
  45156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45157. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45158. __decorate([
  45159. BABYLON.serializeAsColor3("emissive"),
  45160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45161. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45162. __decorate([
  45163. BABYLON.serializeAsTexture(),
  45164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45165. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45166. __decorate([
  45167. BABYLON.serialize(),
  45168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45169. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45170. __decorate([
  45171. BABYLON.serializeAsTexture(),
  45172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45173. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45174. __decorate([
  45175. BABYLON.serialize(),
  45176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45177. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45178. __decorate([
  45179. BABYLON.serialize()
  45180. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45181. __decorate([
  45182. BABYLON.serializeAsTexture(),
  45183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45184. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45185. __decorate([
  45186. BABYLON.serialize(),
  45187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45188. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45189. return PBRBaseSimpleMaterial;
  45190. }(BABYLON.PBRBaseMaterial));
  45191. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45192. })(BABYLON || (BABYLON = {}));
  45193. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45194. var BABYLON;
  45195. (function (BABYLON) {
  45196. /**
  45197. * The Physically based material of BJS.
  45198. *
  45199. * This offers the main features of a standard PBR material.
  45200. * For more information, please refer to the documentation :
  45201. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45202. */
  45203. var PBRMaterial = /** @class */ (function (_super) {
  45204. __extends(PBRMaterial, _super);
  45205. /**
  45206. * Instantiates a new PBRMaterial instance.
  45207. *
  45208. * @param name The material name
  45209. * @param scene The scene the material will be use in.
  45210. */
  45211. function PBRMaterial(name, scene) {
  45212. var _this = _super.call(this, name, scene) || this;
  45213. /**
  45214. * Intensity of the direct lights e.g. the four lights available in your scene.
  45215. * This impacts both the direct diffuse and specular highlights.
  45216. */
  45217. _this.directIntensity = 1.0;
  45218. /**
  45219. * Intensity of the emissive part of the material.
  45220. * This helps controlling the emissive effect without modifying the emissive color.
  45221. */
  45222. _this.emissiveIntensity = 1.0;
  45223. /**
  45224. * Intensity of the environment e.g. how much the environment will light the object
  45225. * either through harmonics for rough material or through the refelction for shiny ones.
  45226. */
  45227. _this.environmentIntensity = 1.0;
  45228. /**
  45229. * This is a special control allowing the reduction of the specular highlights coming from the
  45230. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45231. */
  45232. _this.specularIntensity = 1.0;
  45233. /**
  45234. * Debug Control allowing disabling the bump map on this material.
  45235. */
  45236. _this.disableBumpMap = false;
  45237. /**
  45238. * AKA Occlusion Texture Intensity in other nomenclature.
  45239. */
  45240. _this.ambientTextureStrength = 1.0;
  45241. /**
  45242. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45243. * 1 means it completely occludes it
  45244. * 0 mean it has no impact
  45245. */
  45246. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45247. /**
  45248. * The color of a material in ambient lighting.
  45249. */
  45250. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45251. /**
  45252. * AKA Diffuse Color in other nomenclature.
  45253. */
  45254. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45255. /**
  45256. * AKA Specular Color in other nomenclature.
  45257. */
  45258. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45259. /**
  45260. * The color reflected from the material.
  45261. */
  45262. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45263. /**
  45264. * The color emitted from the material.
  45265. */
  45266. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45267. /**
  45268. * AKA Glossiness in other nomenclature.
  45269. */
  45270. _this.microSurface = 1.0;
  45271. /**
  45272. * source material index of refraction (IOR)' / 'destination material IOR.
  45273. */
  45274. _this.indexOfRefraction = 0.66;
  45275. /**
  45276. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45277. */
  45278. _this.invertRefractionY = false;
  45279. /**
  45280. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45281. * Materials half opaque for instance using refraction could benefit from this control.
  45282. */
  45283. _this.linkRefractionWithTransparency = false;
  45284. _this.useLightmapAsShadowmap = false;
  45285. /**
  45286. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45287. */
  45288. _this.useAlphaFromAlbedoTexture = false;
  45289. /**
  45290. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45291. */
  45292. _this.forceAlphaTest = false;
  45293. /**
  45294. * Defines the alpha limits in alpha test mode.
  45295. */
  45296. _this.alphaCutOff = 0.4;
  45297. /**
  45298. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45299. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45300. */
  45301. _this.useSpecularOverAlpha = true;
  45302. /**
  45303. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45304. */
  45305. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45306. /**
  45307. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45308. */
  45309. _this.useRoughnessFromMetallicTextureAlpha = true;
  45310. /**
  45311. * Specifies if the metallic texture contains the roughness information in its green channel.
  45312. */
  45313. _this.useRoughnessFromMetallicTextureGreen = false;
  45314. /**
  45315. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45316. */
  45317. _this.useMetallnessFromMetallicTextureBlue = false;
  45318. /**
  45319. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45320. */
  45321. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45322. /**
  45323. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45324. */
  45325. _this.useAmbientInGrayScale = false;
  45326. /**
  45327. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45328. * The material will try to infer what glossiness each pixel should be.
  45329. */
  45330. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45331. /**
  45332. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45333. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45334. */
  45335. _this.useRadianceOverAlpha = true;
  45336. /**
  45337. * Allows using an object space normal map (instead of tangent space).
  45338. */
  45339. _this.useObjectSpaceNormalMap = false;
  45340. /**
  45341. * Allows using the bump map in parallax mode.
  45342. */
  45343. _this.useParallax = false;
  45344. /**
  45345. * Allows using the bump map in parallax occlusion mode.
  45346. */
  45347. _this.useParallaxOcclusion = false;
  45348. /**
  45349. * Controls the scale bias of the parallax mode.
  45350. */
  45351. _this.parallaxScaleBias = 0.05;
  45352. /**
  45353. * If sets to true, disables all the lights affecting the material.
  45354. */
  45355. _this.disableLighting = false;
  45356. /**
  45357. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45358. */
  45359. _this.forceIrradianceInFragment = false;
  45360. /**
  45361. * Number of Simultaneous lights allowed on the material.
  45362. */
  45363. _this.maxSimultaneousLights = 4;
  45364. /**
  45365. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45366. */
  45367. _this.invertNormalMapX = false;
  45368. /**
  45369. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45370. */
  45371. _this.invertNormalMapY = false;
  45372. /**
  45373. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45374. */
  45375. _this.twoSidedLighting = false;
  45376. /**
  45377. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45378. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45379. */
  45380. _this.useAlphaFresnel = false;
  45381. /**
  45382. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45383. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45384. */
  45385. _this.useLinearAlphaFresnel = false;
  45386. /**
  45387. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45388. * And/Or occlude the blended part.
  45389. */
  45390. _this.environmentBRDFTexture = null;
  45391. /**
  45392. * Force normal to face away from face.
  45393. */
  45394. _this.forceNormalForward = false;
  45395. /**
  45396. * Enables specular anti aliasing in the PBR shader.
  45397. * It will both interacts on the Geometry for analytical and IBL lighting.
  45398. * It also prefilter the roughness map based on the bump values.
  45399. */
  45400. _this.enableSpecularAntiAliasing = false;
  45401. /**
  45402. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45403. * makes the reflect vector face the model (under horizon).
  45404. */
  45405. _this.useHorizonOcclusion = true;
  45406. /**
  45407. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45408. * too much the area relying on ambient texture to define their ambient occlusion.
  45409. */
  45410. _this.useRadianceOcclusion = true;
  45411. /**
  45412. * If set to true, no lighting calculations will be applied.
  45413. */
  45414. _this.unlit = false;
  45415. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45416. return _this;
  45417. }
  45418. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45419. /**
  45420. * BJS is using an harcoded light falloff based on a manually sets up range.
  45421. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45422. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45423. */
  45424. get: function () {
  45425. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45426. },
  45427. /**
  45428. * BJS is using an harcoded light falloff based on a manually sets up range.
  45429. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45430. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45431. */
  45432. set: function (value) {
  45433. if (value !== this.usePhysicalLightFalloff) {
  45434. // Ensure the effect will be rebuilt.
  45435. this._markAllSubMeshesAsTexturesDirty();
  45436. if (value) {
  45437. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45438. }
  45439. else {
  45440. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45441. }
  45442. }
  45443. },
  45444. enumerable: true,
  45445. configurable: true
  45446. });
  45447. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45448. /**
  45449. * In order to support the falloff compatibility with gltf, a special mode has been added
  45450. * to reproduce the gltf light falloff.
  45451. */
  45452. get: function () {
  45453. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45454. },
  45455. /**
  45456. * In order to support the falloff compatibility with gltf, a special mode has been added
  45457. * to reproduce the gltf light falloff.
  45458. */
  45459. set: function (value) {
  45460. if (value !== this.useGLTFLightFalloff) {
  45461. // Ensure the effect will be rebuilt.
  45462. this._markAllSubMeshesAsTexturesDirty();
  45463. if (value) {
  45464. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45465. }
  45466. else {
  45467. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45468. }
  45469. }
  45470. },
  45471. enumerable: true,
  45472. configurable: true
  45473. });
  45474. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45475. /**
  45476. * Gets the image processing configuration used either in this material.
  45477. */
  45478. get: function () {
  45479. return this._imageProcessingConfiguration;
  45480. },
  45481. /**
  45482. * Sets the Default image processing configuration used either in the this material.
  45483. *
  45484. * If sets to null, the scene one is in use.
  45485. */
  45486. set: function (value) {
  45487. this._attachImageProcessingConfiguration(value);
  45488. // Ensure the effect will be rebuilt.
  45489. this._markAllSubMeshesAsTexturesDirty();
  45490. },
  45491. enumerable: true,
  45492. configurable: true
  45493. });
  45494. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45495. /**
  45496. * Gets wether the color curves effect is enabled.
  45497. */
  45498. get: function () {
  45499. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45500. },
  45501. /**
  45502. * Sets wether the color curves effect is enabled.
  45503. */
  45504. set: function (value) {
  45505. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45506. },
  45507. enumerable: true,
  45508. configurable: true
  45509. });
  45510. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45511. /**
  45512. * Gets wether the color grading effect is enabled.
  45513. */
  45514. get: function () {
  45515. return this.imageProcessingConfiguration.colorGradingEnabled;
  45516. },
  45517. /**
  45518. * Gets wether the color grading effect is enabled.
  45519. */
  45520. set: function (value) {
  45521. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45522. },
  45523. enumerable: true,
  45524. configurable: true
  45525. });
  45526. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45527. /**
  45528. * Gets wether tonemapping is enabled or not.
  45529. */
  45530. get: function () {
  45531. return this._imageProcessingConfiguration.toneMappingEnabled;
  45532. },
  45533. /**
  45534. * Sets wether tonemapping is enabled or not
  45535. */
  45536. set: function (value) {
  45537. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45538. },
  45539. enumerable: true,
  45540. configurable: true
  45541. });
  45542. ;
  45543. ;
  45544. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45545. /**
  45546. * The camera exposure used on this material.
  45547. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45548. * This corresponds to a photographic exposure.
  45549. */
  45550. get: function () {
  45551. return this._imageProcessingConfiguration.exposure;
  45552. },
  45553. /**
  45554. * The camera exposure used on this material.
  45555. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45556. * This corresponds to a photographic exposure.
  45557. */
  45558. set: function (value) {
  45559. this._imageProcessingConfiguration.exposure = value;
  45560. },
  45561. enumerable: true,
  45562. configurable: true
  45563. });
  45564. ;
  45565. ;
  45566. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45567. /**
  45568. * Gets The camera contrast used on this material.
  45569. */
  45570. get: function () {
  45571. return this._imageProcessingConfiguration.contrast;
  45572. },
  45573. /**
  45574. * Sets The camera contrast used on this material.
  45575. */
  45576. set: function (value) {
  45577. this._imageProcessingConfiguration.contrast = value;
  45578. },
  45579. enumerable: true,
  45580. configurable: true
  45581. });
  45582. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45583. /**
  45584. * Gets the Color Grading 2D Lookup Texture.
  45585. */
  45586. get: function () {
  45587. return this._imageProcessingConfiguration.colorGradingTexture;
  45588. },
  45589. /**
  45590. * Sets the Color Grading 2D Lookup Texture.
  45591. */
  45592. set: function (value) {
  45593. this._imageProcessingConfiguration.colorGradingTexture = value;
  45594. },
  45595. enumerable: true,
  45596. configurable: true
  45597. });
  45598. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45599. /**
  45600. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45601. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45602. * 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;
  45603. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45604. */
  45605. get: function () {
  45606. return this._imageProcessingConfiguration.colorCurves;
  45607. },
  45608. /**
  45609. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45610. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45611. * 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;
  45612. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45613. */
  45614. set: function (value) {
  45615. this._imageProcessingConfiguration.colorCurves = value;
  45616. },
  45617. enumerable: true,
  45618. configurable: true
  45619. });
  45620. /**
  45621. * Returns the name of this material class.
  45622. */
  45623. PBRMaterial.prototype.getClassName = function () {
  45624. return "PBRMaterial";
  45625. };
  45626. /**
  45627. * Returns an array of the actively used textures.
  45628. * @returns - Array of BaseTextures
  45629. */
  45630. PBRMaterial.prototype.getActiveTextures = function () {
  45631. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45632. if (this._albedoTexture) {
  45633. activeTextures.push(this._albedoTexture);
  45634. }
  45635. if (this._ambientTexture) {
  45636. activeTextures.push(this._ambientTexture);
  45637. }
  45638. if (this._opacityTexture) {
  45639. activeTextures.push(this._opacityTexture);
  45640. }
  45641. if (this._reflectionTexture) {
  45642. activeTextures.push(this._reflectionTexture);
  45643. }
  45644. if (this._emissiveTexture) {
  45645. activeTextures.push(this._emissiveTexture);
  45646. }
  45647. if (this._reflectivityTexture) {
  45648. activeTextures.push(this._reflectivityTexture);
  45649. }
  45650. if (this._metallicTexture) {
  45651. activeTextures.push(this._metallicTexture);
  45652. }
  45653. if (this._microSurfaceTexture) {
  45654. activeTextures.push(this._microSurfaceTexture);
  45655. }
  45656. if (this._bumpTexture) {
  45657. activeTextures.push(this._bumpTexture);
  45658. }
  45659. if (this._lightmapTexture) {
  45660. activeTextures.push(this._lightmapTexture);
  45661. }
  45662. if (this._refractionTexture) {
  45663. activeTextures.push(this._refractionTexture);
  45664. }
  45665. return activeTextures;
  45666. };
  45667. /**
  45668. * Checks to see if a texture is used in the material.
  45669. * @param texture - Base texture to use.
  45670. * @returns - Boolean specifying if a texture is used in the material.
  45671. */
  45672. PBRMaterial.prototype.hasTexture = function (texture) {
  45673. if (_super.prototype.hasTexture.call(this, texture)) {
  45674. return true;
  45675. }
  45676. if (this._albedoTexture === texture) {
  45677. return true;
  45678. }
  45679. if (this._ambientTexture === texture) {
  45680. return true;
  45681. }
  45682. if (this._opacityTexture === texture) {
  45683. return true;
  45684. }
  45685. if (this._reflectionTexture === texture) {
  45686. return true;
  45687. }
  45688. if (this._reflectivityTexture === texture) {
  45689. return true;
  45690. }
  45691. if (this._metallicTexture === texture) {
  45692. return true;
  45693. }
  45694. if (this._microSurfaceTexture === texture) {
  45695. return true;
  45696. }
  45697. if (this._bumpTexture === texture) {
  45698. return true;
  45699. }
  45700. if (this._lightmapTexture === texture) {
  45701. return true;
  45702. }
  45703. if (this._refractionTexture === texture) {
  45704. return true;
  45705. }
  45706. return false;
  45707. };
  45708. /**
  45709. * Makes a duplicate of the current material.
  45710. * @param name - name to use for the new material.
  45711. */
  45712. PBRMaterial.prototype.clone = function (name) {
  45713. var _this = this;
  45714. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45715. clone.id = name;
  45716. clone.name = name;
  45717. return clone;
  45718. };
  45719. /**
  45720. * Serializes this PBR Material.
  45721. * @returns - An object with the serialized material.
  45722. */
  45723. PBRMaterial.prototype.serialize = function () {
  45724. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45725. serializationObject.customType = "BABYLON.PBRMaterial";
  45726. return serializationObject;
  45727. };
  45728. // Statics
  45729. /**
  45730. * Parses a PBR Material from a serialized object.
  45731. * @param source - Serialized object.
  45732. * @param scene - BJS scene instance.
  45733. * @param rootUrl - url for the scene object
  45734. * @returns - PBRMaterial
  45735. */
  45736. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45737. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45738. };
  45739. /**
  45740. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45741. */
  45742. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45743. /**
  45744. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45745. */
  45746. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45747. /**
  45748. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45749. */
  45750. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45751. /**
  45752. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45753. * They are also discarded below the alpha cutoff threshold to improve performances.
  45754. */
  45755. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45756. /**
  45757. * Defines the default value of how much AO map is occluding the analytical lights
  45758. * (point spot...).
  45759. */
  45760. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45761. __decorate([
  45762. BABYLON.serialize(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45764. ], PBRMaterial.prototype, "directIntensity", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45769. __decorate([
  45770. BABYLON.serialize(),
  45771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45772. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45773. __decorate([
  45774. BABYLON.serialize(),
  45775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45776. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45777. __decorate([
  45778. BABYLON.serialize(),
  45779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45780. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45781. __decorate([
  45782. BABYLON.serializeAsTexture(),
  45783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45784. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45785. __decorate([
  45786. BABYLON.serializeAsTexture(),
  45787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45788. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45789. __decorate([
  45790. BABYLON.serialize(),
  45791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45792. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45793. __decorate([
  45794. BABYLON.serialize(),
  45795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45796. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45797. __decorate([
  45798. BABYLON.serializeAsTexture(),
  45799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45800. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45801. __decorate([
  45802. BABYLON.serializeAsTexture(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45804. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45805. __decorate([
  45806. BABYLON.serializeAsTexture(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45808. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45809. __decorate([
  45810. BABYLON.serializeAsTexture(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45812. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45813. __decorate([
  45814. BABYLON.serializeAsTexture(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45816. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45817. __decorate([
  45818. BABYLON.serialize(),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRMaterial.prototype, "metallic", void 0);
  45821. __decorate([
  45822. BABYLON.serialize(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45824. ], PBRMaterial.prototype, "roughness", void 0);
  45825. __decorate([
  45826. BABYLON.serializeAsTexture(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45828. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsTexture(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45832. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45833. __decorate([
  45834. BABYLON.serializeAsTexture(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45836. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45837. __decorate([
  45838. BABYLON.serializeAsTexture(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45840. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45841. __decorate([
  45842. BABYLON.serializeAsColor3("ambient"),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45844. ], PBRMaterial.prototype, "ambientColor", void 0);
  45845. __decorate([
  45846. BABYLON.serializeAsColor3("albedo"),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45848. ], PBRMaterial.prototype, "albedoColor", void 0);
  45849. __decorate([
  45850. BABYLON.serializeAsColor3("reflectivity"),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45852. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45853. __decorate([
  45854. BABYLON.serializeAsColor3("reflection"),
  45855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45856. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45857. __decorate([
  45858. BABYLON.serializeAsColor3("emissive"),
  45859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45860. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45861. __decorate([
  45862. BABYLON.serialize(),
  45863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45864. ], PBRMaterial.prototype, "microSurface", void 0);
  45865. __decorate([
  45866. BABYLON.serialize(),
  45867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45868. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45869. __decorate([
  45870. BABYLON.serialize(),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45872. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45873. __decorate([
  45874. BABYLON.serialize(),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45876. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45877. __decorate([
  45878. BABYLON.serialize(),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45880. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45881. __decorate([
  45882. BABYLON.serialize(),
  45883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45884. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45885. __decorate([
  45886. BABYLON.serialize(),
  45887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45888. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45889. __decorate([
  45890. BABYLON.serialize(),
  45891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45892. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45893. __decorate([
  45894. BABYLON.serialize(),
  45895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45896. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45897. __decorate([
  45898. BABYLON.serialize(),
  45899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45900. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45901. __decorate([
  45902. BABYLON.serialize(),
  45903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45904. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45905. __decorate([
  45906. BABYLON.serialize(),
  45907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45908. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45909. __decorate([
  45910. BABYLON.serialize(),
  45911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45912. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45913. __decorate([
  45914. BABYLON.serialize(),
  45915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45916. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45917. __decorate([
  45918. BABYLON.serialize(),
  45919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45920. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45921. __decorate([
  45922. BABYLON.serialize(),
  45923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45924. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45925. __decorate([
  45926. BABYLON.serialize()
  45927. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45928. __decorate([
  45929. BABYLON.serialize()
  45930. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45931. __decorate([
  45932. BABYLON.serialize(),
  45933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45934. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45935. __decorate([
  45936. BABYLON.serialize(),
  45937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45938. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45939. __decorate([
  45940. BABYLON.serialize(),
  45941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45942. ], PBRMaterial.prototype, "useParallax", void 0);
  45943. __decorate([
  45944. BABYLON.serialize(),
  45945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45946. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45947. __decorate([
  45948. BABYLON.serialize(),
  45949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45950. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45951. __decorate([
  45952. BABYLON.serialize(),
  45953. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45954. ], PBRMaterial.prototype, "disableLighting", void 0);
  45955. __decorate([
  45956. BABYLON.serialize(),
  45957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45958. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45959. __decorate([
  45960. BABYLON.serialize(),
  45961. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45962. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45963. __decorate([
  45964. BABYLON.serialize(),
  45965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45966. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45967. __decorate([
  45968. BABYLON.serialize(),
  45969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45970. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45971. __decorate([
  45972. BABYLON.serialize(),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45974. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45975. __decorate([
  45976. BABYLON.serialize(),
  45977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45978. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45979. __decorate([
  45980. BABYLON.serialize(),
  45981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45982. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45983. __decorate([
  45984. BABYLON.serializeAsTexture(),
  45985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45986. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45987. __decorate([
  45988. BABYLON.serialize(),
  45989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45990. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45991. __decorate([
  45992. BABYLON.serialize(),
  45993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45994. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45995. __decorate([
  45996. BABYLON.serialize(),
  45997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45998. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45999. __decorate([
  46000. BABYLON.serialize(),
  46001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46002. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46003. __decorate([
  46004. BABYLON.serialize(),
  46005. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46006. ], PBRMaterial.prototype, "unlit", void 0);
  46007. return PBRMaterial;
  46008. }(BABYLON.PBRBaseMaterial));
  46009. BABYLON.PBRMaterial = PBRMaterial;
  46010. })(BABYLON || (BABYLON = {}));
  46011. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46012. var BABYLON;
  46013. (function (BABYLON) {
  46014. /**
  46015. * The PBR material of BJS following the metal roughness convention.
  46016. *
  46017. * This fits to the PBR convention in the GLTF definition:
  46018. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46019. */
  46020. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46021. __extends(PBRMetallicRoughnessMaterial, _super);
  46022. /**
  46023. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46024. *
  46025. * @param name The material name
  46026. * @param scene The scene the material will be use in.
  46027. */
  46028. function PBRMetallicRoughnessMaterial(name, scene) {
  46029. var _this = _super.call(this, name, scene) || this;
  46030. _this._useRoughnessFromMetallicTextureAlpha = false;
  46031. _this._useRoughnessFromMetallicTextureGreen = true;
  46032. _this._useMetallnessFromMetallicTextureBlue = true;
  46033. _this.metallic = 1.0;
  46034. _this.roughness = 1.0;
  46035. return _this;
  46036. }
  46037. /**
  46038. * Return the currrent class name of the material.
  46039. */
  46040. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46041. return "PBRMetallicRoughnessMaterial";
  46042. };
  46043. /**
  46044. * Return the active textures of the material.
  46045. */
  46046. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46047. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46048. if (this.baseTexture) {
  46049. activeTextures.push(this.baseTexture);
  46050. }
  46051. if (this.metallicRoughnessTexture) {
  46052. activeTextures.push(this.metallicRoughnessTexture);
  46053. }
  46054. return activeTextures;
  46055. };
  46056. /**
  46057. * Checks to see if a texture is used in the material.
  46058. * @param texture - Base texture to use.
  46059. * @returns - Boolean specifying if a texture is used in the material.
  46060. */
  46061. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46062. if (_super.prototype.hasTexture.call(this, texture)) {
  46063. return true;
  46064. }
  46065. if (this.baseTexture === texture) {
  46066. return true;
  46067. }
  46068. if (this.metallicRoughnessTexture === texture) {
  46069. return true;
  46070. }
  46071. return false;
  46072. };
  46073. /**
  46074. * Makes a duplicate of the current material.
  46075. * @param name - name to use for the new material.
  46076. */
  46077. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46078. var _this = this;
  46079. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46080. clone.id = name;
  46081. clone.name = name;
  46082. return clone;
  46083. };
  46084. /**
  46085. * Serialize the material to a parsable JSON object.
  46086. */
  46087. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46088. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46089. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46090. return serializationObject;
  46091. };
  46092. /**
  46093. * Parses a JSON object correponding to the serialize function.
  46094. */
  46095. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46096. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46097. };
  46098. __decorate([
  46099. BABYLON.serializeAsColor3(),
  46100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46101. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46102. __decorate([
  46103. BABYLON.serializeAsTexture(),
  46104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46105. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46106. __decorate([
  46107. BABYLON.serialize(),
  46108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46109. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46110. __decorate([
  46111. BABYLON.serialize(),
  46112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46113. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46114. __decorate([
  46115. BABYLON.serializeAsTexture(),
  46116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46117. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46118. return PBRMetallicRoughnessMaterial;
  46119. }(BABYLON.PBRBaseSimpleMaterial));
  46120. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46121. })(BABYLON || (BABYLON = {}));
  46122. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46123. var BABYLON;
  46124. (function (BABYLON) {
  46125. /**
  46126. * The PBR material of BJS following the specular glossiness convention.
  46127. *
  46128. * This fits to the PBR convention in the GLTF definition:
  46129. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46130. */
  46131. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46132. __extends(PBRSpecularGlossinessMaterial, _super);
  46133. /**
  46134. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46135. *
  46136. * @param name The material name
  46137. * @param scene The scene the material will be use in.
  46138. */
  46139. function PBRSpecularGlossinessMaterial(name, scene) {
  46140. var _this = _super.call(this, name, scene) || this;
  46141. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46142. return _this;
  46143. }
  46144. /**
  46145. * Return the currrent class name of the material.
  46146. */
  46147. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46148. return "PBRSpecularGlossinessMaterial";
  46149. };
  46150. /**
  46151. * Return the active textures of the material.
  46152. */
  46153. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46154. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46155. if (this.diffuseTexture) {
  46156. activeTextures.push(this.diffuseTexture);
  46157. }
  46158. if (this.specularGlossinessTexture) {
  46159. activeTextures.push(this.specularGlossinessTexture);
  46160. }
  46161. return activeTextures;
  46162. };
  46163. /**
  46164. * Checks to see if a texture is used in the material.
  46165. * @param texture - Base texture to use.
  46166. * @returns - Boolean specifying if a texture is used in the material.
  46167. */
  46168. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46169. if (_super.prototype.hasTexture.call(this, texture)) {
  46170. return true;
  46171. }
  46172. if (this.diffuseTexture === texture) {
  46173. return true;
  46174. }
  46175. if (this.specularGlossinessTexture === texture) {
  46176. return true;
  46177. }
  46178. return false;
  46179. };
  46180. /**
  46181. * Makes a duplicate of the current material.
  46182. * @param name - name to use for the new material.
  46183. */
  46184. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46185. var _this = this;
  46186. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46187. clone.id = name;
  46188. clone.name = name;
  46189. return clone;
  46190. };
  46191. /**
  46192. * Serialize the material to a parsable JSON object.
  46193. */
  46194. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46195. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46196. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46197. return serializationObject;
  46198. };
  46199. /**
  46200. * Parses a JSON object correponding to the serialize function.
  46201. */
  46202. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46203. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46204. };
  46205. __decorate([
  46206. BABYLON.serializeAsColor3("diffuse"),
  46207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46208. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46209. __decorate([
  46210. BABYLON.serializeAsTexture(),
  46211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46212. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46213. __decorate([
  46214. BABYLON.serializeAsColor3("specular"),
  46215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46216. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46217. __decorate([
  46218. BABYLON.serialize(),
  46219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46220. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46221. __decorate([
  46222. BABYLON.serializeAsTexture(),
  46223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46224. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46225. return PBRSpecularGlossinessMaterial;
  46226. }(BABYLON.PBRBaseSimpleMaterial));
  46227. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46228. })(BABYLON || (BABYLON = {}));
  46229. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46230. var BABYLON;
  46231. (function (BABYLON) {
  46232. /**
  46233. * This is a list of all the different input types that are available in the application.
  46234. * Fo instance: ArcRotateCameraGamepadInput...
  46235. */
  46236. BABYLON.CameraInputTypes = {};
  46237. /**
  46238. * This represents the input manager used within a camera.
  46239. * It helps dealing with all the different kind of input attached to a camera.
  46240. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46241. */
  46242. var CameraInputsManager = /** @class */ (function () {
  46243. /**
  46244. * Instantiate a new Camera Input Manager.
  46245. * @param camera Defines the camera the input manager blongs to
  46246. */
  46247. function CameraInputsManager(camera) {
  46248. this.attached = {};
  46249. this.camera = camera;
  46250. this.checkInputs = function () { };
  46251. }
  46252. /**
  46253. * Add an input method to a camera
  46254. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46255. * @param input camera input method
  46256. */
  46257. CameraInputsManager.prototype.add = function (input) {
  46258. var type = input.getSimpleName();
  46259. if (this.attached[type]) {
  46260. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46261. return;
  46262. }
  46263. this.attached[type] = input;
  46264. input.camera = this.camera;
  46265. //for checkInputs, we are dynamically creating a function
  46266. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46267. if (input.checkInputs) {
  46268. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46269. }
  46270. if (this.attachedElement) {
  46271. input.attachControl(this.attachedElement);
  46272. }
  46273. };
  46274. /**
  46275. * Remove a specific input method from a camera
  46276. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46277. * @param inputToRemove camera input method
  46278. */
  46279. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46280. for (var cam in this.attached) {
  46281. var input = this.attached[cam];
  46282. if (input === inputToRemove) {
  46283. input.detachControl(this.attachedElement);
  46284. input.camera = null;
  46285. delete this.attached[cam];
  46286. this.rebuildInputCheck();
  46287. }
  46288. }
  46289. };
  46290. /**
  46291. * Remove a specific input type from a camera
  46292. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46293. * @param inputType the type of the input to remove
  46294. */
  46295. CameraInputsManager.prototype.removeByType = function (inputType) {
  46296. for (var cam in this.attached) {
  46297. var input = this.attached[cam];
  46298. if (input.getClassName() === inputType) {
  46299. input.detachControl(this.attachedElement);
  46300. input.camera = null;
  46301. delete this.attached[cam];
  46302. this.rebuildInputCheck();
  46303. }
  46304. }
  46305. };
  46306. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46307. var current = this.checkInputs;
  46308. return function () {
  46309. current();
  46310. fn();
  46311. };
  46312. };
  46313. /**
  46314. * Attach the input controls to the currently attached dom element to listen the events from.
  46315. * @param input Defines the input to attach
  46316. */
  46317. CameraInputsManager.prototype.attachInput = function (input) {
  46318. if (this.attachedElement) {
  46319. input.attachControl(this.attachedElement, this.noPreventDefault);
  46320. }
  46321. };
  46322. /**
  46323. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46324. * @param element Defines the dom element to collect the events from
  46325. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46326. */
  46327. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46328. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46329. if (this.attachedElement) {
  46330. return;
  46331. }
  46332. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46333. this.attachedElement = element;
  46334. this.noPreventDefault = noPreventDefault;
  46335. for (var cam in this.attached) {
  46336. this.attached[cam].attachControl(element, noPreventDefault);
  46337. }
  46338. };
  46339. /**
  46340. * Detach the current manager inputs controls from a specific dom element.
  46341. * @param element Defines the dom element to collect the events from
  46342. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46343. */
  46344. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46345. if (disconnect === void 0) { disconnect = false; }
  46346. if (this.attachedElement !== element) {
  46347. return;
  46348. }
  46349. for (var cam in this.attached) {
  46350. this.attached[cam].detachControl(element);
  46351. if (disconnect) {
  46352. this.attached[cam].camera = null;
  46353. }
  46354. }
  46355. this.attachedElement = null;
  46356. };
  46357. /**
  46358. * Rebuild the dynamic inputCheck function from the current list of
  46359. * defined inputs in the manager.
  46360. */
  46361. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46362. this.checkInputs = function () { };
  46363. for (var cam in this.attached) {
  46364. var input = this.attached[cam];
  46365. if (input.checkInputs) {
  46366. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46367. }
  46368. }
  46369. };
  46370. /**
  46371. * Remove all attached input methods from a camera
  46372. */
  46373. CameraInputsManager.prototype.clear = function () {
  46374. if (this.attachedElement) {
  46375. this.detachElement(this.attachedElement, true);
  46376. }
  46377. this.attached = {};
  46378. this.attachedElement = null;
  46379. this.checkInputs = function () { };
  46380. };
  46381. /**
  46382. * Serialize the current input manager attached to a camera.
  46383. * This ensures than once parsed,
  46384. * the input associated to the camera will be identical to the current ones
  46385. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46386. */
  46387. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46388. var inputs = {};
  46389. for (var cam in this.attached) {
  46390. var input = this.attached[cam];
  46391. var res = BABYLON.SerializationHelper.Serialize(input);
  46392. inputs[input.getClassName()] = res;
  46393. }
  46394. serializedCamera.inputsmgr = inputs;
  46395. };
  46396. /**
  46397. * Parses an input manager serialized JSON to restore the previous list of inputs
  46398. * and states associated to a camera.
  46399. * @param parsedCamera Defines the JSON to parse
  46400. */
  46401. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46402. var parsedInputs = parsedCamera.inputsmgr;
  46403. if (parsedInputs) {
  46404. this.clear();
  46405. for (var n in parsedInputs) {
  46406. var construct = BABYLON.CameraInputTypes[n];
  46407. if (construct) {
  46408. var parsedinput = parsedInputs[n];
  46409. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46410. this.add(input);
  46411. }
  46412. }
  46413. }
  46414. else {
  46415. //2016-03-08 this part is for managing backward compatibility
  46416. for (var n in this.attached) {
  46417. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46418. if (construct) {
  46419. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46420. this.remove(this.attached[n]);
  46421. this.add(input);
  46422. }
  46423. }
  46424. }
  46425. };
  46426. return CameraInputsManager;
  46427. }());
  46428. BABYLON.CameraInputsManager = CameraInputsManager;
  46429. })(BABYLON || (BABYLON = {}));
  46430. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46431. var BABYLON;
  46432. (function (BABYLON) {
  46433. /**
  46434. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46435. * This is the base of the follow, arc rotate cameras and Free camera
  46436. * @see http://doc.babylonjs.com/features/cameras
  46437. */
  46438. var TargetCamera = /** @class */ (function (_super) {
  46439. __extends(TargetCamera, _super);
  46440. /**
  46441. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46442. * This is the base of the follow, arc rotate cameras and Free camera
  46443. * @see http://doc.babylonjs.com/features/cameras
  46444. * @param name Defines the name of the camera in the scene
  46445. * @param position Defines the start position of the camera in the scene
  46446. * @param scene Defines the scene the camera belongs to
  46447. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46448. */
  46449. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46450. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46451. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46452. /**
  46453. * Define the current direction the camera is moving to
  46454. */
  46455. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46456. /**
  46457. * Define the current rotation the camera is rotating to
  46458. */
  46459. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46460. /**
  46461. * Define the current rotation of the camera
  46462. */
  46463. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46464. /**
  46465. * Define the current speed of the camera
  46466. */
  46467. _this.speed = 2.0;
  46468. /**
  46469. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46470. * around all axis.
  46471. */
  46472. _this.noRotationConstraint = false;
  46473. /**
  46474. * Define the current target of the camera as an object or a position.
  46475. */
  46476. _this.lockedTarget = null;
  46477. /** @hidden */
  46478. _this._currentTarget = BABYLON.Vector3.Zero();
  46479. /** @hidden */
  46480. _this._viewMatrix = BABYLON.Matrix.Zero();
  46481. /** @hidden */
  46482. _this._camMatrix = BABYLON.Matrix.Zero();
  46483. /** @hidden */
  46484. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46485. /** @hidden */
  46486. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46487. /** @hidden */
  46488. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46489. /** @hidden */
  46490. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46491. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46492. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46493. _this._defaultUp = BABYLON.Vector3.Up();
  46494. _this._cachedRotationZ = 0;
  46495. return _this;
  46496. }
  46497. /**
  46498. * Gets the position in front of the camera at a given distance.
  46499. * @param distance The distance from the camera we want the position to be
  46500. * @returns the position
  46501. */
  46502. TargetCamera.prototype.getFrontPosition = function (distance) {
  46503. this.getWorldMatrix();
  46504. var direction = this.getTarget().subtract(this.position);
  46505. direction.normalize();
  46506. direction.scaleInPlace(distance);
  46507. return this.globalPosition.add(direction);
  46508. };
  46509. /** @hidden */
  46510. TargetCamera.prototype._getLockedTargetPosition = function () {
  46511. if (!this.lockedTarget) {
  46512. return null;
  46513. }
  46514. if (this.lockedTarget.absolutePosition) {
  46515. this.lockedTarget.computeWorldMatrix();
  46516. }
  46517. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46518. };
  46519. /**
  46520. * Store current camera state of the camera (fov, position, rotation, etc..)
  46521. * @returns the camera
  46522. */
  46523. TargetCamera.prototype.storeState = function () {
  46524. this._storedPosition = this.position.clone();
  46525. this._storedRotation = this.rotation.clone();
  46526. if (this.rotationQuaternion) {
  46527. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46528. }
  46529. return _super.prototype.storeState.call(this);
  46530. };
  46531. /**
  46532. * Restored camera state. You must call storeState() first
  46533. * @returns whether it was successful or not
  46534. * @hidden
  46535. */
  46536. TargetCamera.prototype._restoreStateValues = function () {
  46537. if (!_super.prototype._restoreStateValues.call(this)) {
  46538. return false;
  46539. }
  46540. this.position = this._storedPosition.clone();
  46541. this.rotation = this._storedRotation.clone();
  46542. if (this.rotationQuaternion) {
  46543. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46544. }
  46545. this.cameraDirection.copyFromFloats(0, 0, 0);
  46546. this.cameraRotation.copyFromFloats(0, 0);
  46547. return true;
  46548. };
  46549. /** @hidden */
  46550. TargetCamera.prototype._initCache = function () {
  46551. _super.prototype._initCache.call(this);
  46552. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46553. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46554. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46555. };
  46556. /** @hidden */
  46557. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46558. if (!ignoreParentClass) {
  46559. _super.prototype._updateCache.call(this);
  46560. }
  46561. var lockedTargetPosition = this._getLockedTargetPosition();
  46562. if (!lockedTargetPosition) {
  46563. this._cache.lockedTarget = null;
  46564. }
  46565. else {
  46566. if (!this._cache.lockedTarget) {
  46567. this._cache.lockedTarget = lockedTargetPosition.clone();
  46568. }
  46569. else {
  46570. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46571. }
  46572. }
  46573. this._cache.rotation.copyFrom(this.rotation);
  46574. if (this.rotationQuaternion)
  46575. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46576. };
  46577. // Synchronized
  46578. /** @hidden */
  46579. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46580. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46581. return false;
  46582. }
  46583. var lockedTargetPosition = this._getLockedTargetPosition();
  46584. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46585. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46586. };
  46587. // Methods
  46588. /** @hidden */
  46589. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46590. var engine = this.getEngine();
  46591. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46592. };
  46593. // Target
  46594. /** @hidden */
  46595. TargetCamera.prototype.setTarget = function (target) {
  46596. this.upVector.normalize();
  46597. if (this.position.z === target.z) {
  46598. this.position.z += BABYLON.Epsilon;
  46599. }
  46600. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46601. this._camMatrix.invert();
  46602. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46603. var vDir = target.subtract(this.position);
  46604. if (vDir.x >= 0.0) {
  46605. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46606. }
  46607. else {
  46608. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46609. }
  46610. this.rotation.z = 0;
  46611. if (isNaN(this.rotation.x)) {
  46612. this.rotation.x = 0;
  46613. }
  46614. if (isNaN(this.rotation.y)) {
  46615. this.rotation.y = 0;
  46616. }
  46617. if (isNaN(this.rotation.z)) {
  46618. this.rotation.z = 0;
  46619. }
  46620. if (this.rotationQuaternion) {
  46621. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46622. }
  46623. };
  46624. /**
  46625. * Return the current target position of the camera. This value is expressed in local space.
  46626. * @returns the target position
  46627. */
  46628. TargetCamera.prototype.getTarget = function () {
  46629. return this._currentTarget;
  46630. };
  46631. /** @hidden */
  46632. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46633. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46634. };
  46635. /** @hidden */
  46636. TargetCamera.prototype._updatePosition = function () {
  46637. if (this.parent) {
  46638. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46639. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46640. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46641. return;
  46642. }
  46643. this.position.addInPlace(this.cameraDirection);
  46644. };
  46645. /** @hidden */
  46646. TargetCamera.prototype._checkInputs = function () {
  46647. var needToMove = this._decideIfNeedsToMove();
  46648. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46649. // Move
  46650. if (needToMove) {
  46651. this._updatePosition();
  46652. }
  46653. // Rotate
  46654. if (needToRotate) {
  46655. this.rotation.x += this.cameraRotation.x;
  46656. this.rotation.y += this.cameraRotation.y;
  46657. //rotate, if quaternion is set and rotation was used
  46658. if (this.rotationQuaternion) {
  46659. var len = this.rotation.lengthSquared();
  46660. if (len) {
  46661. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46662. }
  46663. }
  46664. if (!this.noRotationConstraint) {
  46665. var limit = (Math.PI / 2) * 0.95;
  46666. if (this.rotation.x > limit)
  46667. this.rotation.x = limit;
  46668. if (this.rotation.x < -limit)
  46669. this.rotation.x = -limit;
  46670. }
  46671. }
  46672. // Inertia
  46673. if (needToMove) {
  46674. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46675. this.cameraDirection.x = 0;
  46676. }
  46677. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46678. this.cameraDirection.y = 0;
  46679. }
  46680. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46681. this.cameraDirection.z = 0;
  46682. }
  46683. this.cameraDirection.scaleInPlace(this.inertia);
  46684. }
  46685. if (needToRotate) {
  46686. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46687. this.cameraRotation.x = 0;
  46688. }
  46689. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46690. this.cameraRotation.y = 0;
  46691. }
  46692. this.cameraRotation.scaleInPlace(this.inertia);
  46693. }
  46694. _super.prototype._checkInputs.call(this);
  46695. };
  46696. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46697. if (this.rotationQuaternion) {
  46698. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46699. }
  46700. else {
  46701. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46702. }
  46703. };
  46704. /**
  46705. * 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)
  46706. * @returns the current camera
  46707. */
  46708. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46709. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46710. return this;
  46711. };
  46712. /** @hidden */
  46713. TargetCamera.prototype._getViewMatrix = function () {
  46714. if (this.lockedTarget) {
  46715. this.setTarget(this._getLockedTargetPosition());
  46716. }
  46717. // Compute
  46718. this._updateCameraRotationMatrix();
  46719. // Apply the changed rotation to the upVector.
  46720. if (this._cachedRotationZ != this.rotation.z) {
  46721. this._rotateUpVectorWithCameraRotationMatrix();
  46722. this._cachedRotationZ = this.rotation.z;
  46723. }
  46724. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46725. // Computing target and final matrix
  46726. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46727. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46728. return this._viewMatrix;
  46729. };
  46730. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46731. if (this.parent) {
  46732. var parentWorldMatrix = this.parent.getWorldMatrix();
  46733. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46734. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46735. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46736. this._markSyncedWithParent();
  46737. }
  46738. else {
  46739. this._globalPosition.copyFrom(position);
  46740. this._globalCurrentTarget.copyFrom(target);
  46741. this._globalCurrentUpVector.copyFrom(up);
  46742. }
  46743. if (this.getScene().useRightHandedSystem) {
  46744. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46745. }
  46746. else {
  46747. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46748. }
  46749. };
  46750. /**
  46751. * @hidden
  46752. */
  46753. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46754. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46755. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46756. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46757. if (!this.rotationQuaternion) {
  46758. this.rotationQuaternion = new BABYLON.Quaternion();
  46759. }
  46760. rigCamera._cameraRigParams = {};
  46761. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46762. }
  46763. return rigCamera;
  46764. }
  46765. return null;
  46766. };
  46767. /**
  46768. * @hidden
  46769. */
  46770. TargetCamera.prototype._updateRigCameras = function () {
  46771. var camLeft = this._rigCameras[0];
  46772. var camRight = this._rigCameras[1];
  46773. switch (this.cameraRigMode) {
  46774. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46775. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46776. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46778. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46779. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46780. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46781. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46782. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46783. camLeft.setTarget(this.getTarget());
  46784. camRight.setTarget(this.getTarget());
  46785. break;
  46786. case BABYLON.Camera.RIG_MODE_VR:
  46787. if (camLeft.rotationQuaternion) {
  46788. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46789. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46790. }
  46791. else {
  46792. camLeft.rotation.copyFrom(this.rotation);
  46793. camRight.rotation.copyFrom(this.rotation);
  46794. }
  46795. camLeft.position.copyFrom(this.position);
  46796. camRight.position.copyFrom(this.position);
  46797. break;
  46798. }
  46799. _super.prototype._updateRigCameras.call(this);
  46800. };
  46801. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46802. if (!this._rigCamTransformMatrix) {
  46803. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46804. }
  46805. var target = this.getTarget();
  46806. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46807. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46808. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46809. };
  46810. /**
  46811. * Gets the current object class name.
  46812. * @return the class name
  46813. */
  46814. TargetCamera.prototype.getClassName = function () {
  46815. return "TargetCamera";
  46816. };
  46817. __decorate([
  46818. BABYLON.serializeAsVector3()
  46819. ], TargetCamera.prototype, "rotation", void 0);
  46820. __decorate([
  46821. BABYLON.serialize()
  46822. ], TargetCamera.prototype, "speed", void 0);
  46823. __decorate([
  46824. BABYLON.serializeAsMeshReference("lockedTargetId")
  46825. ], TargetCamera.prototype, "lockedTarget", void 0);
  46826. return TargetCamera;
  46827. }(BABYLON.Camera));
  46828. BABYLON.TargetCamera = TargetCamera;
  46829. })(BABYLON || (BABYLON = {}));
  46830. //# sourceMappingURL=babylon.targetCamera.js.map
  46831. var BABYLON;
  46832. (function (BABYLON) {
  46833. /**
  46834. * Manage the mouse inputs to control the movement of a free camera.
  46835. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46836. */
  46837. var FreeCameraMouseInput = /** @class */ (function () {
  46838. /**
  46839. * Manage the mouse inputs to control the movement of a free camera.
  46840. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46841. * @param touchEnabled Defines if touch is enabled or not
  46842. */
  46843. function FreeCameraMouseInput(
  46844. /**
  46845. * Define if touch is enabled in the mouse input
  46846. */
  46847. touchEnabled) {
  46848. if (touchEnabled === void 0) { touchEnabled = true; }
  46849. this.touchEnabled = touchEnabled;
  46850. /**
  46851. * Defines the buttons associated with the input to handle camera move.
  46852. */
  46853. this.buttons = [0, 1, 2];
  46854. /**
  46855. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46856. */
  46857. this.angularSensibility = 2000.0;
  46858. this.previousPosition = null;
  46859. }
  46860. /**
  46861. * Attach the input controls to a specific dom element to get the input from.
  46862. * @param element Defines the element the controls should be listened from
  46863. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46864. */
  46865. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46866. var _this = this;
  46867. var engine = this.camera.getEngine();
  46868. if (!this._pointerInput) {
  46869. this._pointerInput = function (p, s) {
  46870. var evt = p.event;
  46871. if (engine.isInVRExclusivePointerMode) {
  46872. return;
  46873. }
  46874. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46875. return;
  46876. }
  46877. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46878. return;
  46879. }
  46880. var srcElement = (evt.srcElement || evt.target);
  46881. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46882. try {
  46883. srcElement.setPointerCapture(evt.pointerId);
  46884. }
  46885. catch (e) {
  46886. //Nothing to do with the error. Execution will continue.
  46887. }
  46888. _this.previousPosition = {
  46889. x: evt.clientX,
  46890. y: evt.clientY
  46891. };
  46892. if (!noPreventDefault) {
  46893. evt.preventDefault();
  46894. element.focus();
  46895. }
  46896. }
  46897. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46898. try {
  46899. srcElement.releasePointerCapture(evt.pointerId);
  46900. }
  46901. catch (e) {
  46902. //Nothing to do with the error.
  46903. }
  46904. _this.previousPosition = null;
  46905. if (!noPreventDefault) {
  46906. evt.preventDefault();
  46907. }
  46908. }
  46909. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46910. if (!_this.previousPosition || engine.isPointerLock) {
  46911. return;
  46912. }
  46913. var offsetX = evt.clientX - _this.previousPosition.x;
  46914. if (_this.camera.getScene().useRightHandedSystem)
  46915. offsetX *= -1;
  46916. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46917. offsetX *= -1;
  46918. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46919. var offsetY = evt.clientY - _this.previousPosition.y;
  46920. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46921. _this.previousPosition = {
  46922. x: evt.clientX,
  46923. y: evt.clientY
  46924. };
  46925. if (!noPreventDefault) {
  46926. evt.preventDefault();
  46927. }
  46928. }
  46929. };
  46930. }
  46931. this._onMouseMove = function (evt) {
  46932. if (!engine.isPointerLock) {
  46933. return;
  46934. }
  46935. if (engine.isInVRExclusivePointerMode) {
  46936. return;
  46937. }
  46938. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46939. if (_this.camera.getScene().useRightHandedSystem)
  46940. offsetX *= -1;
  46941. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46942. offsetX *= -1;
  46943. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46944. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46945. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46946. _this.previousPosition = null;
  46947. if (!noPreventDefault) {
  46948. evt.preventDefault();
  46949. }
  46950. };
  46951. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46952. element.addEventListener("mousemove", this._onMouseMove, false);
  46953. };
  46954. /**
  46955. * Detach the current controls from the specified dom element.
  46956. * @param element Defines the element to stop listening the inputs from
  46957. */
  46958. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46959. if (this._observer && element) {
  46960. this.camera.getScene().onPointerObservable.remove(this._observer);
  46961. if (this._onMouseMove) {
  46962. element.removeEventListener("mousemove", this._onMouseMove);
  46963. }
  46964. this._observer = null;
  46965. this._onMouseMove = null;
  46966. this.previousPosition = null;
  46967. }
  46968. };
  46969. /**
  46970. * Gets the class name of the current intput.
  46971. * @returns the class name
  46972. */
  46973. FreeCameraMouseInput.prototype.getClassName = function () {
  46974. return "FreeCameraMouseInput";
  46975. };
  46976. /**
  46977. * Get the friendly name associated with the input class.
  46978. * @returns the input friendly name
  46979. */
  46980. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46981. return "mouse";
  46982. };
  46983. __decorate([
  46984. BABYLON.serialize()
  46985. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46986. __decorate([
  46987. BABYLON.serialize()
  46988. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46989. return FreeCameraMouseInput;
  46990. }());
  46991. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46992. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46993. })(BABYLON || (BABYLON = {}));
  46994. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46995. var BABYLON;
  46996. (function (BABYLON) {
  46997. /**
  46998. * Manage the keyboard inputs to control the movement of a free camera.
  46999. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47000. */
  47001. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47002. function FreeCameraKeyboardMoveInput() {
  47003. /**
  47004. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47005. */
  47006. this.keysUp = [38];
  47007. /**
  47008. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47009. */
  47010. this.keysDown = [40];
  47011. /**
  47012. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47013. */
  47014. this.keysLeft = [37];
  47015. /**
  47016. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47017. */
  47018. this.keysRight = [39];
  47019. this._keys = new Array();
  47020. }
  47021. /**
  47022. * Attach the input controls to a specific dom element to get the input from.
  47023. * @param element Defines the element the controls should be listened from
  47024. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47025. */
  47026. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47027. var _this = this;
  47028. if (this._onCanvasBlurObserver) {
  47029. return;
  47030. }
  47031. this._scene = this.camera.getScene();
  47032. this._engine = this._scene.getEngine();
  47033. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47034. _this._keys = [];
  47035. });
  47036. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47037. var evt = info.event;
  47038. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47039. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47040. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47041. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47042. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47043. var index = _this._keys.indexOf(evt.keyCode);
  47044. if (index === -1) {
  47045. _this._keys.push(evt.keyCode);
  47046. }
  47047. if (!noPreventDefault) {
  47048. evt.preventDefault();
  47049. }
  47050. }
  47051. }
  47052. else {
  47053. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47054. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47055. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47056. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47057. var index = _this._keys.indexOf(evt.keyCode);
  47058. if (index >= 0) {
  47059. _this._keys.splice(index, 1);
  47060. }
  47061. if (!noPreventDefault) {
  47062. evt.preventDefault();
  47063. }
  47064. }
  47065. }
  47066. });
  47067. };
  47068. /**
  47069. * Detach the current controls from the specified dom element.
  47070. * @param element Defines the element to stop listening the inputs from
  47071. */
  47072. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47073. if (this._scene) {
  47074. if (this._onKeyboardObserver) {
  47075. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47076. }
  47077. if (this._onCanvasBlurObserver) {
  47078. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47079. }
  47080. this._onKeyboardObserver = null;
  47081. this._onCanvasBlurObserver = null;
  47082. }
  47083. this._keys = [];
  47084. };
  47085. /**
  47086. * Update the current camera state depending on the inputs that have been used this frame.
  47087. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47088. */
  47089. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47090. if (this._onKeyboardObserver) {
  47091. var camera = this.camera;
  47092. // Keyboard
  47093. for (var index = 0; index < this._keys.length; index++) {
  47094. var keyCode = this._keys[index];
  47095. var speed = camera._computeLocalCameraSpeed();
  47096. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47097. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47098. }
  47099. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47100. camera._localDirection.copyFromFloats(0, 0, speed);
  47101. }
  47102. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47103. camera._localDirection.copyFromFloats(speed, 0, 0);
  47104. }
  47105. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47106. camera._localDirection.copyFromFloats(0, 0, -speed);
  47107. }
  47108. if (camera.getScene().useRightHandedSystem) {
  47109. camera._localDirection.z *= -1;
  47110. }
  47111. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47112. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47113. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47114. }
  47115. }
  47116. };
  47117. /**
  47118. * Gets the class name of the current intput.
  47119. * @returns the class name
  47120. */
  47121. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47122. return "FreeCameraKeyboardMoveInput";
  47123. };
  47124. /** @hidden */
  47125. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47126. this._keys = [];
  47127. };
  47128. /**
  47129. * Get the friendly name associated with the input class.
  47130. * @returns the input friendly name
  47131. */
  47132. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47133. return "keyboard";
  47134. };
  47135. __decorate([
  47136. BABYLON.serialize()
  47137. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47138. __decorate([
  47139. BABYLON.serialize()
  47140. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47141. __decorate([
  47142. BABYLON.serialize()
  47143. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47144. __decorate([
  47145. BABYLON.serialize()
  47146. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47147. return FreeCameraKeyboardMoveInput;
  47148. }());
  47149. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47150. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47151. })(BABYLON || (BABYLON = {}));
  47152. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47153. var BABYLON;
  47154. (function (BABYLON) {
  47155. /**
  47156. * Default Inputs manager for the FreeCamera.
  47157. * It groups all the default supported inputs for ease of use.
  47158. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47159. */
  47160. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47161. __extends(FreeCameraInputsManager, _super);
  47162. /**
  47163. * Instantiates a new FreeCameraInputsManager.
  47164. * @param camera Defines the camera the inputs belong to
  47165. */
  47166. function FreeCameraInputsManager(camera) {
  47167. return _super.call(this, camera) || this;
  47168. }
  47169. /**
  47170. * Add keyboard input support to the input manager.
  47171. * @returns the current input manager
  47172. */
  47173. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47174. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47175. return this;
  47176. };
  47177. /**
  47178. * Add mouse input support to the input manager.
  47179. * @returns the current input manager
  47180. */
  47181. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47182. if (touchEnabled === void 0) { touchEnabled = true; }
  47183. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47184. return this;
  47185. };
  47186. /**
  47187. * Add orientation input support to the input manager.
  47188. * @returns the current input manager
  47189. */
  47190. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47191. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47192. return this;
  47193. };
  47194. /**
  47195. * Add touch input support to the input manager.
  47196. * @returns the current input manager
  47197. */
  47198. FreeCameraInputsManager.prototype.addTouch = function () {
  47199. this.add(new BABYLON.FreeCameraTouchInput());
  47200. return this;
  47201. };
  47202. /**
  47203. * Add virtual joystick input support to the input manager.
  47204. * @returns the current input manager
  47205. */
  47206. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47207. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47208. return this;
  47209. };
  47210. return FreeCameraInputsManager;
  47211. }(BABYLON.CameraInputsManager));
  47212. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47213. })(BABYLON || (BABYLON = {}));
  47214. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47215. var BABYLON;
  47216. (function (BABYLON) {
  47217. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47218. // Forcing to use the Universal camera
  47219. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47220. });
  47221. /**
  47222. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47223. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47224. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47225. */
  47226. var FreeCamera = /** @class */ (function (_super) {
  47227. __extends(FreeCamera, _super);
  47228. /**
  47229. * Instantiates a Free Camera.
  47230. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47231. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47232. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47233. * @param name Define the name of the camera in the scene
  47234. * @param position Define the start position of the camera in the scene
  47235. * @param scene Define the scene the camera belongs to
  47236. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47237. */
  47238. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47239. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47240. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47241. /**
  47242. * Define the collision ellipsoid of the camera.
  47243. * This is helpful to simulate a camera body like the player body around the camera
  47244. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47245. */
  47246. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47247. /**
  47248. * Define an offset for the position of the ellipsoid around the camera.
  47249. * This can be helpful to determine the center of the body near the gravity center of the body
  47250. * instead of its head.
  47251. */
  47252. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47253. /**
  47254. * Enable or disable collisions of the camera with the rest of the scene objects.
  47255. */
  47256. _this.checkCollisions = false;
  47257. /**
  47258. * Enable or disable gravity on the camera.
  47259. */
  47260. _this.applyGravity = false;
  47261. _this._needMoveForGravity = false;
  47262. _this._oldPosition = BABYLON.Vector3.Zero();
  47263. _this._diffPosition = BABYLON.Vector3.Zero();
  47264. _this._newPosition = BABYLON.Vector3.Zero();
  47265. // Collisions
  47266. _this._collisionMask = -1;
  47267. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47268. if (collidedMesh === void 0) { collidedMesh = null; }
  47269. //TODO move this to the collision coordinator!
  47270. if (_this.getScene().workerCollisions)
  47271. newPosition.multiplyInPlace(_this._collider._radius);
  47272. var updatePosition = function (newPos) {
  47273. _this._newPosition.copyFrom(newPos);
  47274. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47275. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47276. _this.position.addInPlace(_this._diffPosition);
  47277. if (_this.onCollide && collidedMesh) {
  47278. _this.onCollide(collidedMesh);
  47279. }
  47280. }
  47281. };
  47282. updatePosition(newPosition);
  47283. };
  47284. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47285. _this.inputs.addKeyboard().addMouse();
  47286. return _this;
  47287. }
  47288. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47289. /**
  47290. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47291. * Higher values reduce sensitivity.
  47292. */
  47293. get: function () {
  47294. var mouse = this.inputs.attached["mouse"];
  47295. if (mouse)
  47296. return mouse.angularSensibility;
  47297. return 0;
  47298. },
  47299. /**
  47300. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47301. * Higher values reduce sensitivity.
  47302. */
  47303. set: function (value) {
  47304. var mouse = this.inputs.attached["mouse"];
  47305. if (mouse)
  47306. mouse.angularSensibility = value;
  47307. },
  47308. enumerable: true,
  47309. configurable: true
  47310. });
  47311. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47312. /**
  47313. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47314. */
  47315. get: function () {
  47316. var keyboard = this.inputs.attached["keyboard"];
  47317. if (keyboard)
  47318. return keyboard.keysUp;
  47319. return [];
  47320. },
  47321. set: function (value) {
  47322. var keyboard = this.inputs.attached["keyboard"];
  47323. if (keyboard)
  47324. keyboard.keysUp = value;
  47325. },
  47326. enumerable: true,
  47327. configurable: true
  47328. });
  47329. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47330. /**
  47331. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47332. */
  47333. get: function () {
  47334. var keyboard = this.inputs.attached["keyboard"];
  47335. if (keyboard)
  47336. return keyboard.keysDown;
  47337. return [];
  47338. },
  47339. set: function (value) {
  47340. var keyboard = this.inputs.attached["keyboard"];
  47341. if (keyboard)
  47342. keyboard.keysDown = value;
  47343. },
  47344. enumerable: true,
  47345. configurable: true
  47346. });
  47347. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47348. /**
  47349. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47350. */
  47351. get: function () {
  47352. var keyboard = this.inputs.attached["keyboard"];
  47353. if (keyboard)
  47354. return keyboard.keysLeft;
  47355. return [];
  47356. },
  47357. set: function (value) {
  47358. var keyboard = this.inputs.attached["keyboard"];
  47359. if (keyboard)
  47360. keyboard.keysLeft = value;
  47361. },
  47362. enumerable: true,
  47363. configurable: true
  47364. });
  47365. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47366. /**
  47367. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47368. */
  47369. get: function () {
  47370. var keyboard = this.inputs.attached["keyboard"];
  47371. if (keyboard)
  47372. return keyboard.keysRight;
  47373. return [];
  47374. },
  47375. set: function (value) {
  47376. var keyboard = this.inputs.attached["keyboard"];
  47377. if (keyboard)
  47378. keyboard.keysRight = value;
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. /**
  47384. * Attached controls to the current camera.
  47385. * @param element Defines the element the controls should be listened from
  47386. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47387. */
  47388. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47389. this.inputs.attachElement(element, noPreventDefault);
  47390. };
  47391. /**
  47392. * Detach the current controls from the camera.
  47393. * The camera will stop reacting to inputs.
  47394. * @param element Defines the element to stop listening the inputs from
  47395. */
  47396. FreeCamera.prototype.detachControl = function (element) {
  47397. this.inputs.detachElement(element);
  47398. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47399. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47400. };
  47401. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47402. /**
  47403. * Define a collision mask to limit the list of object the camera can collide with
  47404. */
  47405. get: function () {
  47406. return this._collisionMask;
  47407. },
  47408. set: function (mask) {
  47409. this._collisionMask = !isNaN(mask) ? mask : -1;
  47410. },
  47411. enumerable: true,
  47412. configurable: true
  47413. });
  47414. /** @hidden */
  47415. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47416. var globalPosition;
  47417. if (this.parent) {
  47418. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47419. }
  47420. else {
  47421. globalPosition = this.position;
  47422. }
  47423. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47424. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47425. if (!this._collider) {
  47426. this._collider = new BABYLON.Collider();
  47427. }
  47428. this._collider._radius = this.ellipsoid;
  47429. this._collider.collisionMask = this._collisionMask;
  47430. //no need for clone, as long as gravity is not on.
  47431. var actualDisplacement = displacement;
  47432. //add gravity to the direction to prevent the dual-collision checking
  47433. if (this.applyGravity) {
  47434. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47435. actualDisplacement = displacement.add(this.getScene().gravity);
  47436. }
  47437. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47438. };
  47439. /** @hidden */
  47440. FreeCamera.prototype._checkInputs = function () {
  47441. if (!this._localDirection) {
  47442. this._localDirection = BABYLON.Vector3.Zero();
  47443. this._transformedDirection = BABYLON.Vector3.Zero();
  47444. }
  47445. this.inputs.checkInputs();
  47446. _super.prototype._checkInputs.call(this);
  47447. };
  47448. /** @hidden */
  47449. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47450. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47451. };
  47452. /** @hidden */
  47453. FreeCamera.prototype._updatePosition = function () {
  47454. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47455. this._collideWithWorld(this.cameraDirection);
  47456. }
  47457. else {
  47458. _super.prototype._updatePosition.call(this);
  47459. }
  47460. };
  47461. /**
  47462. * Destroy the camera and release the current resources hold by it.
  47463. */
  47464. FreeCamera.prototype.dispose = function () {
  47465. this.inputs.clear();
  47466. _super.prototype.dispose.call(this);
  47467. };
  47468. /**
  47469. * Gets the current object class name.
  47470. * @return the class name
  47471. */
  47472. FreeCamera.prototype.getClassName = function () {
  47473. return "FreeCamera";
  47474. };
  47475. __decorate([
  47476. BABYLON.serializeAsVector3()
  47477. ], FreeCamera.prototype, "ellipsoid", void 0);
  47478. __decorate([
  47479. BABYLON.serializeAsVector3()
  47480. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47481. __decorate([
  47482. BABYLON.serialize()
  47483. ], FreeCamera.prototype, "checkCollisions", void 0);
  47484. __decorate([
  47485. BABYLON.serialize()
  47486. ], FreeCamera.prototype, "applyGravity", void 0);
  47487. return FreeCamera;
  47488. }(BABYLON.TargetCamera));
  47489. BABYLON.FreeCamera = FreeCamera;
  47490. })(BABYLON || (BABYLON = {}));
  47491. //# sourceMappingURL=babylon.freeCamera.js.map
  47492. var BABYLON;
  47493. (function (BABYLON) {
  47494. /**
  47495. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47496. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47497. */
  47498. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47499. function ArcRotateCameraKeyboardMoveInput() {
  47500. /**
  47501. * Defines the list of key codes associated with the up action (increase alpha)
  47502. */
  47503. this.keysUp = [38];
  47504. /**
  47505. * Defines the list of key codes associated with the down action (decrease alpha)
  47506. */
  47507. this.keysDown = [40];
  47508. /**
  47509. * Defines the list of key codes associated with the left action (increase beta)
  47510. */
  47511. this.keysLeft = [37];
  47512. /**
  47513. * Defines the list of key codes associated with the right action (decrease beta)
  47514. */
  47515. this.keysRight = [39];
  47516. /**
  47517. * Defines the list of key codes associated with the reset action.
  47518. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47519. */
  47520. this.keysReset = [220];
  47521. /**
  47522. * Defines the panning sensibility of the inputs.
  47523. * (How fast is the camera paning)
  47524. */
  47525. this.panningSensibility = 50.0;
  47526. /**
  47527. * Defines the zooming sensibility of the inputs.
  47528. * (How fast is the camera zooming)
  47529. */
  47530. this.zoomingSensibility = 25.0;
  47531. /**
  47532. * Defines wether maintaining the alt key down switch the movement mode from
  47533. * orientation to zoom.
  47534. */
  47535. this.useAltToZoom = true;
  47536. this._keys = new Array();
  47537. }
  47538. /**
  47539. * Attach the input controls to a specific dom element to get the input from.
  47540. * @param element Defines the element the controls should be listened from
  47541. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47542. */
  47543. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47544. var _this = this;
  47545. if (this._onCanvasBlurObserver) {
  47546. return;
  47547. }
  47548. this._scene = this.camera.getScene();
  47549. this._engine = this._scene.getEngine();
  47550. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47551. _this._keys = [];
  47552. });
  47553. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47554. var evt = info.event;
  47555. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47556. _this._ctrlPressed = evt.ctrlKey;
  47557. _this._altPressed = evt.altKey;
  47558. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47559. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47560. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47561. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47562. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47563. var index = _this._keys.indexOf(evt.keyCode);
  47564. if (index === -1) {
  47565. _this._keys.push(evt.keyCode);
  47566. }
  47567. if (evt.preventDefault) {
  47568. if (!noPreventDefault) {
  47569. evt.preventDefault();
  47570. }
  47571. }
  47572. }
  47573. }
  47574. else {
  47575. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47576. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47577. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47578. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47579. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47580. var index = _this._keys.indexOf(evt.keyCode);
  47581. if (index >= 0) {
  47582. _this._keys.splice(index, 1);
  47583. }
  47584. if (evt.preventDefault) {
  47585. if (!noPreventDefault) {
  47586. evt.preventDefault();
  47587. }
  47588. }
  47589. }
  47590. }
  47591. });
  47592. };
  47593. /**
  47594. * Detach the current controls from the specified dom element.
  47595. * @param element Defines the element to stop listening the inputs from
  47596. */
  47597. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47598. if (this._scene) {
  47599. if (this._onKeyboardObserver) {
  47600. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47601. }
  47602. if (this._onCanvasBlurObserver) {
  47603. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47604. }
  47605. this._onKeyboardObserver = null;
  47606. this._onCanvasBlurObserver = null;
  47607. }
  47608. this._keys = [];
  47609. };
  47610. /**
  47611. * Update the current camera state depending on the inputs that have been used this frame.
  47612. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47613. */
  47614. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47615. if (this._onKeyboardObserver) {
  47616. var camera = this.camera;
  47617. for (var index = 0; index < this._keys.length; index++) {
  47618. var keyCode = this._keys[index];
  47619. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47620. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47621. camera.inertialPanningX -= 1 / this.panningSensibility;
  47622. }
  47623. else {
  47624. camera.inertialAlphaOffset -= 0.01;
  47625. }
  47626. }
  47627. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47628. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47629. camera.inertialPanningY += 1 / this.panningSensibility;
  47630. }
  47631. else if (this._altPressed && this.useAltToZoom) {
  47632. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47633. }
  47634. else {
  47635. camera.inertialBetaOffset -= 0.01;
  47636. }
  47637. }
  47638. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47639. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47640. camera.inertialPanningX += 1 / this.panningSensibility;
  47641. }
  47642. else {
  47643. camera.inertialAlphaOffset += 0.01;
  47644. }
  47645. }
  47646. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47647. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47648. camera.inertialPanningY -= 1 / this.panningSensibility;
  47649. }
  47650. else if (this._altPressed && this.useAltToZoom) {
  47651. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47652. }
  47653. else {
  47654. camera.inertialBetaOffset += 0.01;
  47655. }
  47656. }
  47657. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47658. if (camera.useInputToRestoreState) {
  47659. camera.restoreState();
  47660. }
  47661. }
  47662. }
  47663. }
  47664. };
  47665. /**
  47666. * Gets the class name of the current intput.
  47667. * @returns the class name
  47668. */
  47669. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47670. return "ArcRotateCameraKeyboardMoveInput";
  47671. };
  47672. /**
  47673. * Get the friendly name associated with the input class.
  47674. * @returns the input friendly name
  47675. */
  47676. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47677. return "keyboard";
  47678. };
  47679. __decorate([
  47680. BABYLON.serialize()
  47681. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47682. __decorate([
  47683. BABYLON.serialize()
  47684. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47685. __decorate([
  47686. BABYLON.serialize()
  47687. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47688. __decorate([
  47689. BABYLON.serialize()
  47690. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47691. __decorate([
  47692. BABYLON.serialize()
  47693. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47694. __decorate([
  47695. BABYLON.serialize()
  47696. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47697. __decorate([
  47698. BABYLON.serialize()
  47699. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47700. __decorate([
  47701. BABYLON.serialize()
  47702. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47703. return ArcRotateCameraKeyboardMoveInput;
  47704. }());
  47705. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47706. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47707. })(BABYLON || (BABYLON = {}));
  47708. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47709. var BABYLON;
  47710. (function (BABYLON) {
  47711. /**
  47712. * Manage the mouse wheel inputs to control an arc rotate camera.
  47713. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47714. */
  47715. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47716. function ArcRotateCameraMouseWheelInput() {
  47717. /**
  47718. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47719. */
  47720. this.wheelPrecision = 3.0;
  47721. /**
  47722. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47723. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47724. */
  47725. this.wheelDeltaPercentage = 0;
  47726. }
  47727. /**
  47728. * Attach the input controls to a specific dom element to get the input from.
  47729. * @param element Defines the element the controls should be listened from
  47730. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47731. */
  47732. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47733. var _this = this;
  47734. this._wheel = function (p, s) {
  47735. //sanity check - this should be a PointerWheel event.
  47736. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47737. return;
  47738. var event = p.event;
  47739. var delta = 0;
  47740. if (event.wheelDelta) {
  47741. if (_this.wheelDeltaPercentage) {
  47742. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47743. if (event.wheelDelta > 0) {
  47744. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47745. }
  47746. else {
  47747. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47748. }
  47749. }
  47750. else {
  47751. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47752. }
  47753. }
  47754. else if (event.detail) {
  47755. delta = -event.detail / _this.wheelPrecision;
  47756. }
  47757. if (delta)
  47758. _this.camera.inertialRadiusOffset += delta;
  47759. if (event.preventDefault) {
  47760. if (!noPreventDefault) {
  47761. event.preventDefault();
  47762. }
  47763. }
  47764. };
  47765. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47766. };
  47767. /**
  47768. * Detach the current controls from the specified dom element.
  47769. * @param element Defines the element to stop listening the inputs from
  47770. */
  47771. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47772. if (this._observer && element) {
  47773. this.camera.getScene().onPointerObservable.remove(this._observer);
  47774. this._observer = null;
  47775. this._wheel = null;
  47776. }
  47777. };
  47778. /**
  47779. * Gets the class name of the current intput.
  47780. * @returns the class name
  47781. */
  47782. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47783. return "ArcRotateCameraMouseWheelInput";
  47784. };
  47785. /**
  47786. * Get the friendly name associated with the input class.
  47787. * @returns the input friendly name
  47788. */
  47789. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47790. return "mousewheel";
  47791. };
  47792. __decorate([
  47793. BABYLON.serialize()
  47794. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47795. __decorate([
  47796. BABYLON.serialize()
  47797. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47798. return ArcRotateCameraMouseWheelInput;
  47799. }());
  47800. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47801. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47802. })(BABYLON || (BABYLON = {}));
  47803. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47804. var BABYLON;
  47805. (function (BABYLON) {
  47806. /**
  47807. * Manage the pointers inputs to control an arc rotate camera.
  47808. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47809. */
  47810. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47811. function ArcRotateCameraPointersInput() {
  47812. /**
  47813. * Defines the buttons associated with the input to handle camera move.
  47814. */
  47815. this.buttons = [0, 1, 2];
  47816. /**
  47817. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47818. */
  47819. this.angularSensibilityX = 1000.0;
  47820. /**
  47821. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47822. */
  47823. this.angularSensibilityY = 1000.0;
  47824. /**
  47825. * Defines the pointer pinch precision or how fast is the camera zooming.
  47826. */
  47827. this.pinchPrecision = 12.0;
  47828. /**
  47829. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47830. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47831. */
  47832. this.pinchDeltaPercentage = 0;
  47833. /**
  47834. * Defines the pointer panning sensibility or how fast is the camera moving.
  47835. */
  47836. this.panningSensibility = 1000.0;
  47837. /**
  47838. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47839. */
  47840. this.multiTouchPanning = true;
  47841. /**
  47842. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47843. */
  47844. this.multiTouchPanAndZoom = true;
  47845. /**
  47846. * Revers pinch action direction.
  47847. */
  47848. this.pinchInwards = true;
  47849. this._isPanClick = false;
  47850. }
  47851. /**
  47852. * Attach the input controls to a specific dom element to get the input from.
  47853. * @param element Defines the element the controls should be listened from
  47854. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47855. */
  47856. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47857. var _this = this;
  47858. var engine = this.camera.getEngine();
  47859. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47860. var pointA = null;
  47861. var pointB = null;
  47862. var previousPinchSquaredDistance = 0;
  47863. var initialDistance = 0;
  47864. var twoFingerActivityCount = 0;
  47865. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47866. this._pointerInput = function (p, s) {
  47867. var evt = p.event;
  47868. var isTouch = p.event.pointerType === "touch";
  47869. if (engine.isInVRExclusivePointerMode) {
  47870. return;
  47871. }
  47872. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47873. return;
  47874. }
  47875. var srcElement = (evt.srcElement || evt.target);
  47876. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47877. try {
  47878. srcElement.setPointerCapture(evt.pointerId);
  47879. }
  47880. catch (e) {
  47881. //Nothing to do with the error. Execution will continue.
  47882. }
  47883. // Manage panning with pan button click
  47884. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47885. // manage pointers
  47886. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47887. if (pointA === null) {
  47888. pointA = cacheSoloPointer;
  47889. }
  47890. else if (pointB === null) {
  47891. pointB = cacheSoloPointer;
  47892. }
  47893. if (!noPreventDefault) {
  47894. evt.preventDefault();
  47895. element.focus();
  47896. }
  47897. }
  47898. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47899. if (_this.camera.useInputToRestoreState) {
  47900. _this.camera.restoreState();
  47901. }
  47902. }
  47903. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47904. try {
  47905. srcElement.releasePointerCapture(evt.pointerId);
  47906. }
  47907. catch (e) {
  47908. //Nothing to do with the error.
  47909. }
  47910. cacheSoloPointer = null;
  47911. previousPinchSquaredDistance = 0;
  47912. previousMultiTouchPanPosition.isPaning = false;
  47913. previousMultiTouchPanPosition.isPinching = false;
  47914. twoFingerActivityCount = 0;
  47915. initialDistance = 0;
  47916. if (!isTouch) {
  47917. pointB = null; // Mouse and pen are mono pointer
  47918. }
  47919. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47920. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47921. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47922. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47923. if (engine._badOS) {
  47924. pointA = pointB = null;
  47925. }
  47926. else {
  47927. //only remove the impacted pointer in case of multitouch allowing on most
  47928. //platforms switching from rotate to zoom and pan seamlessly.
  47929. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47930. pointA = pointB;
  47931. pointB = null;
  47932. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47933. }
  47934. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47935. pointB = null;
  47936. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47937. }
  47938. else {
  47939. pointA = pointB = null;
  47940. }
  47941. }
  47942. if (!noPreventDefault) {
  47943. evt.preventDefault();
  47944. }
  47945. }
  47946. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47947. if (!noPreventDefault) {
  47948. evt.preventDefault();
  47949. }
  47950. // One button down
  47951. if (pointA && pointB === null && cacheSoloPointer) {
  47952. if (_this.panningSensibility !== 0 &&
  47953. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47954. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47955. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47956. }
  47957. else {
  47958. var offsetX = evt.clientX - cacheSoloPointer.x;
  47959. var offsetY = evt.clientY - cacheSoloPointer.y;
  47960. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47961. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47962. }
  47963. cacheSoloPointer.x = evt.clientX;
  47964. cacheSoloPointer.y = evt.clientY;
  47965. }
  47966. // Two buttons down: pinch/pan
  47967. else if (pointA && pointB) {
  47968. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47969. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47970. ed.x = evt.clientX;
  47971. ed.y = evt.clientY;
  47972. var direction = _this.pinchInwards ? 1 : -1;
  47973. var distX = pointA.x - pointB.x;
  47974. var distY = pointA.y - pointB.y;
  47975. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47976. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47977. if (previousPinchSquaredDistance === 0) {
  47978. initialDistance = pinchDistance;
  47979. previousPinchSquaredDistance = pinchSquaredDistance;
  47980. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47981. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47982. return;
  47983. }
  47984. if (_this.multiTouchPanAndZoom) {
  47985. if (_this.pinchDeltaPercentage) {
  47986. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47987. }
  47988. else {
  47989. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47990. (_this.pinchPrecision *
  47991. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47992. direction);
  47993. }
  47994. if (_this.panningSensibility !== 0) {
  47995. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47996. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47997. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47998. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47999. previousMultiTouchPanPosition.x = pointersCenterX;
  48000. previousMultiTouchPanPosition.y = pointersCenterY;
  48001. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48002. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48003. }
  48004. }
  48005. else {
  48006. twoFingerActivityCount++;
  48007. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48008. if (_this.pinchDeltaPercentage) {
  48009. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48010. }
  48011. else {
  48012. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48013. (_this.pinchPrecision *
  48014. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48015. direction);
  48016. }
  48017. previousMultiTouchPanPosition.isPaning = false;
  48018. previousMultiTouchPanPosition.isPinching = true;
  48019. }
  48020. else {
  48021. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48022. if (!previousMultiTouchPanPosition.isPaning) {
  48023. previousMultiTouchPanPosition.isPaning = true;
  48024. previousMultiTouchPanPosition.isPinching = false;
  48025. previousMultiTouchPanPosition.x = ed.x;
  48026. previousMultiTouchPanPosition.y = ed.y;
  48027. return;
  48028. }
  48029. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48030. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48031. }
  48032. }
  48033. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48034. previousMultiTouchPanPosition.x = ed.x;
  48035. previousMultiTouchPanPosition.y = ed.y;
  48036. }
  48037. }
  48038. previousPinchSquaredDistance = pinchSquaredDistance;
  48039. }
  48040. }
  48041. };
  48042. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48043. this._onContextMenu = function (evt) {
  48044. evt.preventDefault();
  48045. };
  48046. if (!this.camera._useCtrlForPanning) {
  48047. element.addEventListener("contextmenu", this._onContextMenu, false);
  48048. }
  48049. this._onLostFocus = function () {
  48050. //this._keys = [];
  48051. pointA = pointB = null;
  48052. previousPinchSquaredDistance = 0;
  48053. previousMultiTouchPanPosition.isPaning = false;
  48054. previousMultiTouchPanPosition.isPinching = false;
  48055. twoFingerActivityCount = 0;
  48056. cacheSoloPointer = null;
  48057. initialDistance = 0;
  48058. };
  48059. this._onMouseMove = function (evt) {
  48060. if (!engine.isPointerLock) {
  48061. return;
  48062. }
  48063. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48064. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48065. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48066. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48067. if (!noPreventDefault) {
  48068. evt.preventDefault();
  48069. }
  48070. };
  48071. this._onGestureStart = function (e) {
  48072. if (window.MSGesture === undefined) {
  48073. return;
  48074. }
  48075. if (!_this._MSGestureHandler) {
  48076. _this._MSGestureHandler = new MSGesture();
  48077. _this._MSGestureHandler.target = element;
  48078. }
  48079. _this._MSGestureHandler.addPointer(e.pointerId);
  48080. };
  48081. this._onGesture = function (e) {
  48082. _this.camera.radius *= e.scale;
  48083. if (e.preventDefault) {
  48084. if (!noPreventDefault) {
  48085. e.stopPropagation();
  48086. e.preventDefault();
  48087. }
  48088. }
  48089. };
  48090. element.addEventListener("mousemove", this._onMouseMove, false);
  48091. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48092. element.addEventListener("MSGestureChange", this._onGesture, false);
  48093. BABYLON.Tools.RegisterTopRootEvents([
  48094. { name: "blur", handler: this._onLostFocus }
  48095. ]);
  48096. };
  48097. /**
  48098. * Detach the current controls from the specified dom element.
  48099. * @param element Defines the element to stop listening the inputs from
  48100. */
  48101. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48102. if (this._onLostFocus) {
  48103. BABYLON.Tools.UnregisterTopRootEvents([
  48104. { name: "blur", handler: this._onLostFocus }
  48105. ]);
  48106. }
  48107. if (element && this._observer) {
  48108. this.camera.getScene().onPointerObservable.remove(this._observer);
  48109. this._observer = null;
  48110. if (this._onContextMenu) {
  48111. element.removeEventListener("contextmenu", this._onContextMenu);
  48112. }
  48113. if (this._onMouseMove) {
  48114. element.removeEventListener("mousemove", this._onMouseMove);
  48115. }
  48116. if (this._onGestureStart) {
  48117. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48118. }
  48119. if (this._onGesture) {
  48120. element.removeEventListener("MSGestureChange", this._onGesture);
  48121. }
  48122. this._isPanClick = false;
  48123. this.pinchInwards = true;
  48124. this._onMouseMove = null;
  48125. this._onGestureStart = null;
  48126. this._onGesture = null;
  48127. this._MSGestureHandler = null;
  48128. this._onLostFocus = null;
  48129. this._onContextMenu = null;
  48130. }
  48131. };
  48132. /**
  48133. * Gets the class name of the current intput.
  48134. * @returns the class name
  48135. */
  48136. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48137. return "ArcRotateCameraPointersInput";
  48138. };
  48139. /**
  48140. * Get the friendly name associated with the input class.
  48141. * @returns the input friendly name
  48142. */
  48143. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48144. return "pointers";
  48145. };
  48146. __decorate([
  48147. BABYLON.serialize()
  48148. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48149. __decorate([
  48150. BABYLON.serialize()
  48151. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48152. __decorate([
  48153. BABYLON.serialize()
  48154. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48155. __decorate([
  48156. BABYLON.serialize()
  48157. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48158. __decorate([
  48159. BABYLON.serialize()
  48160. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48161. __decorate([
  48162. BABYLON.serialize()
  48163. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48170. return ArcRotateCameraPointersInput;
  48171. }());
  48172. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48173. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48174. })(BABYLON || (BABYLON = {}));
  48175. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48176. var BABYLON;
  48177. (function (BABYLON) {
  48178. /**
  48179. * Default Inputs manager for the ArcRotateCamera.
  48180. * It groups all the default supported inputs for ease of use.
  48181. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48182. */
  48183. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48184. __extends(ArcRotateCameraInputsManager, _super);
  48185. /**
  48186. * Instantiates a new ArcRotateCameraInputsManager.
  48187. * @param camera Defines the camera the inputs belong to
  48188. */
  48189. function ArcRotateCameraInputsManager(camera) {
  48190. return _super.call(this, camera) || this;
  48191. }
  48192. /**
  48193. * Add mouse wheel input support to the input manager.
  48194. * @returns the current input manager
  48195. */
  48196. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48197. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48198. return this;
  48199. };
  48200. /**
  48201. * Add pointers input support to the input manager.
  48202. * @returns the current input manager
  48203. */
  48204. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48205. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48206. return this;
  48207. };
  48208. /**
  48209. * Add keyboard input support to the input manager.
  48210. * @returns the current input manager
  48211. */
  48212. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48213. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48214. return this;
  48215. };
  48216. /**
  48217. * Add orientation input support to the input manager.
  48218. * @returns the current input manager
  48219. */
  48220. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48221. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48222. return this;
  48223. };
  48224. return ArcRotateCameraInputsManager;
  48225. }(BABYLON.CameraInputsManager));
  48226. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48227. })(BABYLON || (BABYLON = {}));
  48228. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48229. var BABYLON;
  48230. (function (BABYLON) {
  48231. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48232. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48233. });
  48234. /**
  48235. * This represents an orbital type of camera.
  48236. *
  48237. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  48238. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  48239. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48240. */
  48241. var ArcRotateCamera = /** @class */ (function (_super) {
  48242. __extends(ArcRotateCamera, _super);
  48243. /**
  48244. * Instantiates a new ArcRotateCamera in a given scene
  48245. * @param name Defines the name of the camera
  48246. * @param alpha Defines the camera rotation along the logitudinal axis
  48247. * @param beta Defines the camera rotation along the latitudinal axis
  48248. * @param radius Defines the camera distance from its target
  48249. * @param target Defines the camera target
  48250. * @param scene Defines the scene the camera belongs to
  48251. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48252. */
  48253. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48254. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48255. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48256. /**
  48257. * Current inertia value on the longitudinal axis.
  48258. * The bigger this number the longer it will take for the camera to stop.
  48259. */
  48260. _this.inertialAlphaOffset = 0;
  48261. /**
  48262. * Current inertia value on the latitudinal axis.
  48263. * The bigger this number the longer it will take for the camera to stop.
  48264. */
  48265. _this.inertialBetaOffset = 0;
  48266. /**
  48267. * Current inertia value on the radius axis.
  48268. * The bigger this number the longer it will take for the camera to stop.
  48269. */
  48270. _this.inertialRadiusOffset = 0;
  48271. /**
  48272. * Minimum allowed angle on the longitudinal axis.
  48273. * This can help limiting how the Camera is able to move in the scene.
  48274. */
  48275. _this.lowerAlphaLimit = null;
  48276. /**
  48277. * Maximum allowed angle on the longitudinal axis.
  48278. * This can help limiting how the Camera is able to move in the scene.
  48279. */
  48280. _this.upperAlphaLimit = null;
  48281. /**
  48282. * Minimum allowed angle on the latitudinal axis.
  48283. * This can help limiting how the Camera is able to move in the scene.
  48284. */
  48285. _this.lowerBetaLimit = 0.01;
  48286. /**
  48287. * Maximum allowed angle on the latitudinal axis.
  48288. * This can help limiting how the Camera is able to move in the scene.
  48289. */
  48290. _this.upperBetaLimit = Math.PI;
  48291. /**
  48292. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48293. * This can help limiting how the Camera is able to move in the scene.
  48294. */
  48295. _this.lowerRadiusLimit = null;
  48296. /**
  48297. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48298. * This can help limiting how the Camera is able to move in the scene.
  48299. */
  48300. _this.upperRadiusLimit = null;
  48301. /**
  48302. * Defines the current inertia value used during panning of the camera along the X axis.
  48303. */
  48304. _this.inertialPanningX = 0;
  48305. /**
  48306. * Defines the current inertia value used during panning of the camera along the Y axis.
  48307. */
  48308. _this.inertialPanningY = 0;
  48309. /**
  48310. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48311. * Basically if your fingers moves away from more than this distance you will be considered
  48312. * in pinch mode.
  48313. */
  48314. _this.pinchToPanMaxDistance = 20;
  48315. /**
  48316. * Defines the maximum distance the camera can pan.
  48317. * This could help keeping the cammera always in your scene.
  48318. */
  48319. _this.panningDistanceLimit = null;
  48320. /**
  48321. * Defines the target of the camera before paning.
  48322. */
  48323. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48324. /**
  48325. * Defines the value of the inertia used during panning.
  48326. * 0 would mean stop inertia and one would mean no decelleration at all.
  48327. */
  48328. _this.panningInertia = 0.9;
  48329. //-- end properties for backward compatibility for inputs
  48330. /**
  48331. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48332. */
  48333. _this.zoomOnFactor = 1;
  48334. /**
  48335. * Defines a screen offset for the camera position.
  48336. */
  48337. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48338. /**
  48339. * Allows the camera to be completely reversed.
  48340. * If false the camera can not arrive upside down.
  48341. */
  48342. _this.allowUpsideDown = true;
  48343. /**
  48344. * Define if double tap/click is used to restore the previously saved state of the camera.
  48345. */
  48346. _this.useInputToRestoreState = true;
  48347. /** @hidden */
  48348. _this._viewMatrix = new BABYLON.Matrix();
  48349. /**
  48350. * Defines the allowed panning axis.
  48351. */
  48352. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48353. /**
  48354. * Observable triggered when the mesh target has been changed on the camera.
  48355. */
  48356. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48357. /**
  48358. * Defines whether the camera should check collision with the objects oh the scene.
  48359. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48360. */
  48361. _this.checkCollisions = false;
  48362. /**
  48363. * Defines the collision radius of the camera.
  48364. * This simulates a sphere around the camera.
  48365. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48366. */
  48367. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48368. _this._previousPosition = BABYLON.Vector3.Zero();
  48369. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48370. _this._newPosition = BABYLON.Vector3.Zero();
  48371. _this._computationVector = BABYLON.Vector3.Zero();
  48372. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48373. if (collidedMesh === void 0) { collidedMesh = null; }
  48374. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48375. newPosition.multiplyInPlace(_this._collider._radius);
  48376. }
  48377. if (!collidedMesh) {
  48378. _this._previousPosition.copyFrom(_this.position);
  48379. }
  48380. else {
  48381. _this.setPosition(newPosition);
  48382. if (_this.onCollide) {
  48383. _this.onCollide(collidedMesh);
  48384. }
  48385. }
  48386. // Recompute because of constraints
  48387. var cosa = Math.cos(_this.alpha);
  48388. var sina = Math.sin(_this.alpha);
  48389. var cosb = Math.cos(_this.beta);
  48390. var sinb = Math.sin(_this.beta);
  48391. if (sinb === 0) {
  48392. sinb = 0.0001;
  48393. }
  48394. var target = _this._getTargetPosition();
  48395. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48396. target.addToRef(_this._computationVector, _this._newPosition);
  48397. _this.position.copyFrom(_this._newPosition);
  48398. var up = _this.upVector;
  48399. if (_this.allowUpsideDown && _this.beta < 0) {
  48400. up = up.clone();
  48401. up = up.negate();
  48402. }
  48403. _this._computeViewMatrix(_this.position, target, up);
  48404. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48405. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48406. _this._collisionTriggered = false;
  48407. };
  48408. _this._target = BABYLON.Vector3.Zero();
  48409. if (target) {
  48410. _this.setTarget(target);
  48411. }
  48412. _this.alpha = alpha;
  48413. _this.beta = beta;
  48414. _this.radius = radius;
  48415. _this.getViewMatrix();
  48416. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48417. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48418. return _this;
  48419. }
  48420. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48421. /**
  48422. * Defines the target point of the camera.
  48423. * The camera looks towards it form the radius distance.
  48424. */
  48425. get: function () {
  48426. return this._target;
  48427. },
  48428. set: function (value) {
  48429. this.setTarget(value);
  48430. },
  48431. enumerable: true,
  48432. configurable: true
  48433. });
  48434. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48435. //-- begin properties for backward compatibility for inputs
  48436. /**
  48437. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48438. */
  48439. get: function () {
  48440. var pointers = this.inputs.attached["pointers"];
  48441. if (pointers)
  48442. return pointers.angularSensibilityX;
  48443. return 0;
  48444. },
  48445. set: function (value) {
  48446. var pointers = this.inputs.attached["pointers"];
  48447. if (pointers) {
  48448. pointers.angularSensibilityX = value;
  48449. }
  48450. },
  48451. enumerable: true,
  48452. configurable: true
  48453. });
  48454. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48455. /**
  48456. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48457. */
  48458. get: function () {
  48459. var pointers = this.inputs.attached["pointers"];
  48460. if (pointers)
  48461. return pointers.angularSensibilityY;
  48462. return 0;
  48463. },
  48464. set: function (value) {
  48465. var pointers = this.inputs.attached["pointers"];
  48466. if (pointers) {
  48467. pointers.angularSensibilityY = value;
  48468. }
  48469. },
  48470. enumerable: true,
  48471. configurable: true
  48472. });
  48473. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48474. /**
  48475. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48476. */
  48477. get: function () {
  48478. var pointers = this.inputs.attached["pointers"];
  48479. if (pointers)
  48480. return pointers.pinchPrecision;
  48481. return 0;
  48482. },
  48483. set: function (value) {
  48484. var pointers = this.inputs.attached["pointers"];
  48485. if (pointers) {
  48486. pointers.pinchPrecision = value;
  48487. }
  48488. },
  48489. enumerable: true,
  48490. configurable: true
  48491. });
  48492. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48493. /**
  48494. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48495. * It will be used instead of pinchDeltaPrecision if different from 0.
  48496. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48497. */
  48498. get: function () {
  48499. var pointers = this.inputs.attached["pointers"];
  48500. if (pointers)
  48501. return pointers.pinchDeltaPercentage;
  48502. return 0;
  48503. },
  48504. set: function (value) {
  48505. var pointers = this.inputs.attached["pointers"];
  48506. if (pointers) {
  48507. pointers.pinchDeltaPercentage = value;
  48508. }
  48509. },
  48510. enumerable: true,
  48511. configurable: true
  48512. });
  48513. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48514. /**
  48515. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48516. */
  48517. get: function () {
  48518. var pointers = this.inputs.attached["pointers"];
  48519. if (pointers)
  48520. return pointers.panningSensibility;
  48521. return 0;
  48522. },
  48523. set: function (value) {
  48524. var pointers = this.inputs.attached["pointers"];
  48525. if (pointers) {
  48526. pointers.panningSensibility = value;
  48527. }
  48528. },
  48529. enumerable: true,
  48530. configurable: true
  48531. });
  48532. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48533. /**
  48534. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48535. */
  48536. get: function () {
  48537. var keyboard = this.inputs.attached["keyboard"];
  48538. if (keyboard)
  48539. return keyboard.keysUp;
  48540. return [];
  48541. },
  48542. set: function (value) {
  48543. var keyboard = this.inputs.attached["keyboard"];
  48544. if (keyboard)
  48545. keyboard.keysUp = value;
  48546. },
  48547. enumerable: true,
  48548. configurable: true
  48549. });
  48550. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48551. /**
  48552. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48553. */
  48554. get: function () {
  48555. var keyboard = this.inputs.attached["keyboard"];
  48556. if (keyboard)
  48557. return keyboard.keysDown;
  48558. return [];
  48559. },
  48560. set: function (value) {
  48561. var keyboard = this.inputs.attached["keyboard"];
  48562. if (keyboard)
  48563. keyboard.keysDown = value;
  48564. },
  48565. enumerable: true,
  48566. configurable: true
  48567. });
  48568. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48569. /**
  48570. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48571. */
  48572. get: function () {
  48573. var keyboard = this.inputs.attached["keyboard"];
  48574. if (keyboard)
  48575. return keyboard.keysLeft;
  48576. return [];
  48577. },
  48578. set: function (value) {
  48579. var keyboard = this.inputs.attached["keyboard"];
  48580. if (keyboard)
  48581. keyboard.keysLeft = value;
  48582. },
  48583. enumerable: true,
  48584. configurable: true
  48585. });
  48586. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48587. /**
  48588. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48589. */
  48590. get: function () {
  48591. var keyboard = this.inputs.attached["keyboard"];
  48592. if (keyboard)
  48593. return keyboard.keysRight;
  48594. return [];
  48595. },
  48596. set: function (value) {
  48597. var keyboard = this.inputs.attached["keyboard"];
  48598. if (keyboard)
  48599. keyboard.keysRight = value;
  48600. },
  48601. enumerable: true,
  48602. configurable: true
  48603. });
  48604. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48605. /**
  48606. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48607. */
  48608. get: function () {
  48609. var mousewheel = this.inputs.attached["mousewheel"];
  48610. if (mousewheel)
  48611. return mousewheel.wheelPrecision;
  48612. return 0;
  48613. },
  48614. set: function (value) {
  48615. var mousewheel = this.inputs.attached["mousewheel"];
  48616. if (mousewheel)
  48617. mousewheel.wheelPrecision = value;
  48618. },
  48619. enumerable: true,
  48620. configurable: true
  48621. });
  48622. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48623. /**
  48624. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48625. * It will be used instead of pinchDeltaPrecision if different from 0.
  48626. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48627. */
  48628. get: function () {
  48629. var mousewheel = this.inputs.attached["mousewheel"];
  48630. if (mousewheel)
  48631. return mousewheel.wheelDeltaPercentage;
  48632. return 0;
  48633. },
  48634. set: function (value) {
  48635. var mousewheel = this.inputs.attached["mousewheel"];
  48636. if (mousewheel)
  48637. mousewheel.wheelDeltaPercentage = value;
  48638. },
  48639. enumerable: true,
  48640. configurable: true
  48641. });
  48642. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48643. /**
  48644. * Gets the bouncing behavior of the camera if it has been enabled.
  48645. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48646. */
  48647. get: function () {
  48648. return this._bouncingBehavior;
  48649. },
  48650. enumerable: true,
  48651. configurable: true
  48652. });
  48653. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48654. /**
  48655. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48656. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48657. */
  48658. get: function () {
  48659. return this._bouncingBehavior != null;
  48660. },
  48661. set: function (value) {
  48662. if (value === this.useBouncingBehavior) {
  48663. return;
  48664. }
  48665. if (value) {
  48666. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48667. this.addBehavior(this._bouncingBehavior);
  48668. }
  48669. else if (this._bouncingBehavior) {
  48670. this.removeBehavior(this._bouncingBehavior);
  48671. this._bouncingBehavior = null;
  48672. }
  48673. },
  48674. enumerable: true,
  48675. configurable: true
  48676. });
  48677. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48678. /**
  48679. * Gets the framing behavior of the camera if it has been enabled.
  48680. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48681. */
  48682. get: function () {
  48683. return this._framingBehavior;
  48684. },
  48685. enumerable: true,
  48686. configurable: true
  48687. });
  48688. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48689. /**
  48690. * Defines if the framing behavior of the camera is enabled on the camera.
  48691. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48692. */
  48693. get: function () {
  48694. return this._framingBehavior != null;
  48695. },
  48696. set: function (value) {
  48697. if (value === this.useFramingBehavior) {
  48698. return;
  48699. }
  48700. if (value) {
  48701. this._framingBehavior = new BABYLON.FramingBehavior();
  48702. this.addBehavior(this._framingBehavior);
  48703. }
  48704. else if (this._framingBehavior) {
  48705. this.removeBehavior(this._framingBehavior);
  48706. this._framingBehavior = null;
  48707. }
  48708. },
  48709. enumerable: true,
  48710. configurable: true
  48711. });
  48712. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48713. /**
  48714. * Gets the auto rotation behavior of the camera if it has been enabled.
  48715. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48716. */
  48717. get: function () {
  48718. return this._autoRotationBehavior;
  48719. },
  48720. enumerable: true,
  48721. configurable: true
  48722. });
  48723. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48724. /**
  48725. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48726. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48727. */
  48728. get: function () {
  48729. return this._autoRotationBehavior != null;
  48730. },
  48731. set: function (value) {
  48732. if (value === this.useAutoRotationBehavior) {
  48733. return;
  48734. }
  48735. if (value) {
  48736. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48737. this.addBehavior(this._autoRotationBehavior);
  48738. }
  48739. else if (this._autoRotationBehavior) {
  48740. this.removeBehavior(this._autoRotationBehavior);
  48741. this._autoRotationBehavior = null;
  48742. }
  48743. },
  48744. enumerable: true,
  48745. configurable: true
  48746. });
  48747. // Cache
  48748. /** @hidden */
  48749. ArcRotateCamera.prototype._initCache = function () {
  48750. _super.prototype._initCache.call(this);
  48751. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48752. this._cache.alpha = undefined;
  48753. this._cache.beta = undefined;
  48754. this._cache.radius = undefined;
  48755. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48756. };
  48757. /** @hidden */
  48758. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48759. if (!ignoreParentClass) {
  48760. _super.prototype._updateCache.call(this);
  48761. }
  48762. this._cache._target.copyFrom(this._getTargetPosition());
  48763. this._cache.alpha = this.alpha;
  48764. this._cache.beta = this.beta;
  48765. this._cache.radius = this.radius;
  48766. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48767. };
  48768. ArcRotateCamera.prototype._getTargetPosition = function () {
  48769. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48770. var pos = this._targetHost.getAbsolutePosition();
  48771. if (this._targetBoundingCenter) {
  48772. pos.addToRef(this._targetBoundingCenter, this._target);
  48773. }
  48774. else {
  48775. this._target.copyFrom(pos);
  48776. }
  48777. }
  48778. var lockedTargetPosition = this._getLockedTargetPosition();
  48779. if (lockedTargetPosition) {
  48780. return lockedTargetPosition;
  48781. }
  48782. return this._target;
  48783. };
  48784. /**
  48785. * Stores the current state of the camera (alpha, beta, radius and target)
  48786. * @returns the camera itself
  48787. */
  48788. ArcRotateCamera.prototype.storeState = function () {
  48789. this._storedAlpha = this.alpha;
  48790. this._storedBeta = this.beta;
  48791. this._storedRadius = this.radius;
  48792. this._storedTarget = this._getTargetPosition().clone();
  48793. return _super.prototype.storeState.call(this);
  48794. };
  48795. /**
  48796. * @hidden
  48797. * Restored camera state. You must call storeState() first
  48798. */
  48799. ArcRotateCamera.prototype._restoreStateValues = function () {
  48800. if (!_super.prototype._restoreStateValues.call(this)) {
  48801. return false;
  48802. }
  48803. this.alpha = this._storedAlpha;
  48804. this.beta = this._storedBeta;
  48805. this.radius = this._storedRadius;
  48806. this.setTarget(this._storedTarget.clone());
  48807. this.inertialAlphaOffset = 0;
  48808. this.inertialBetaOffset = 0;
  48809. this.inertialRadiusOffset = 0;
  48810. this.inertialPanningX = 0;
  48811. this.inertialPanningY = 0;
  48812. return true;
  48813. };
  48814. // Synchronized
  48815. /** @hidden */
  48816. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48817. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48818. return false;
  48819. return this._cache._target.equals(this._getTargetPosition())
  48820. && this._cache.alpha === this.alpha
  48821. && this._cache.beta === this.beta
  48822. && this._cache.radius === this.radius
  48823. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48824. };
  48825. /**
  48826. * Attached controls to the current camera.
  48827. * @param element Defines the element the controls should be listened from
  48828. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48829. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48830. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48831. */
  48832. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48833. var _this = this;
  48834. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48835. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48836. this._useCtrlForPanning = useCtrlForPanning;
  48837. this._panningMouseButton = panningMouseButton;
  48838. this.inputs.attachElement(element, noPreventDefault);
  48839. this._reset = function () {
  48840. _this.inertialAlphaOffset = 0;
  48841. _this.inertialBetaOffset = 0;
  48842. _this.inertialRadiusOffset = 0;
  48843. _this.inertialPanningX = 0;
  48844. _this.inertialPanningY = 0;
  48845. };
  48846. };
  48847. /**
  48848. * Detach the current controls from the camera.
  48849. * The camera will stop reacting to inputs.
  48850. * @param element Defines the element to stop listening the inputs from
  48851. */
  48852. ArcRotateCamera.prototype.detachControl = function (element) {
  48853. this.inputs.detachElement(element);
  48854. if (this._reset) {
  48855. this._reset();
  48856. }
  48857. };
  48858. /** @hidden */
  48859. ArcRotateCamera.prototype._checkInputs = function () {
  48860. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48861. if (this._collisionTriggered) {
  48862. return;
  48863. }
  48864. this.inputs.checkInputs();
  48865. // Inertia
  48866. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48867. var inertialAlphaOffset = this.inertialAlphaOffset;
  48868. if (this.beta <= 0)
  48869. inertialAlphaOffset *= -1;
  48870. if (this.getScene().useRightHandedSystem)
  48871. inertialAlphaOffset *= -1;
  48872. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48873. inertialAlphaOffset *= -1;
  48874. this.alpha += inertialAlphaOffset;
  48875. this.beta += this.inertialBetaOffset;
  48876. this.radius -= this.inertialRadiusOffset;
  48877. this.inertialAlphaOffset *= this.inertia;
  48878. this.inertialBetaOffset *= this.inertia;
  48879. this.inertialRadiusOffset *= this.inertia;
  48880. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48881. this.inertialAlphaOffset = 0;
  48882. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48883. this.inertialBetaOffset = 0;
  48884. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48885. this.inertialRadiusOffset = 0;
  48886. }
  48887. // Panning inertia
  48888. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48889. if (!this._localDirection) {
  48890. this._localDirection = BABYLON.Vector3.Zero();
  48891. this._transformedDirection = BABYLON.Vector3.Zero();
  48892. }
  48893. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48894. this._localDirection.multiplyInPlace(this.panningAxis);
  48895. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48896. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48897. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48898. if (!this.panningAxis.y) {
  48899. this._transformedDirection.y = 0;
  48900. }
  48901. if (!this._targetHost) {
  48902. if (this.panningDistanceLimit) {
  48903. this._transformedDirection.addInPlace(this._target);
  48904. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48905. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48906. this._target.copyFrom(this._transformedDirection);
  48907. }
  48908. }
  48909. else {
  48910. this._target.addInPlace(this._transformedDirection);
  48911. }
  48912. }
  48913. this.inertialPanningX *= this.panningInertia;
  48914. this.inertialPanningY *= this.panningInertia;
  48915. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48916. this.inertialPanningX = 0;
  48917. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48918. this.inertialPanningY = 0;
  48919. }
  48920. // Limits
  48921. this._checkLimits();
  48922. _super.prototype._checkInputs.call(this);
  48923. };
  48924. ArcRotateCamera.prototype._checkLimits = function () {
  48925. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48926. if (this.allowUpsideDown && this.beta > Math.PI) {
  48927. this.beta = this.beta - (2 * Math.PI);
  48928. }
  48929. }
  48930. else {
  48931. if (this.beta < this.lowerBetaLimit) {
  48932. this.beta = this.lowerBetaLimit;
  48933. }
  48934. }
  48935. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48936. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48937. this.beta = this.beta + (2 * Math.PI);
  48938. }
  48939. }
  48940. else {
  48941. if (this.beta > this.upperBetaLimit) {
  48942. this.beta = this.upperBetaLimit;
  48943. }
  48944. }
  48945. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48946. this.alpha = this.lowerAlphaLimit;
  48947. }
  48948. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48949. this.alpha = this.upperAlphaLimit;
  48950. }
  48951. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48952. this.radius = this.lowerRadiusLimit;
  48953. }
  48954. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48955. this.radius = this.upperRadiusLimit;
  48956. }
  48957. };
  48958. /**
  48959. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48960. */
  48961. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48962. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48963. this.radius = this._computationVector.length();
  48964. if (this.radius === 0) {
  48965. this.radius = 0.0001; // Just to avoid division by zero
  48966. }
  48967. // Alpha
  48968. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48969. if (this._computationVector.z < 0) {
  48970. this.alpha = 2 * Math.PI - this.alpha;
  48971. }
  48972. // Beta
  48973. this.beta = Math.acos(this._computationVector.y / this.radius);
  48974. this._checkLimits();
  48975. };
  48976. /**
  48977. * Use a position to define the current camera related information like aplha, beta and radius
  48978. * @param position Defines the position to set the camera at
  48979. */
  48980. ArcRotateCamera.prototype.setPosition = function (position) {
  48981. if (this.position.equals(position)) {
  48982. return;
  48983. }
  48984. this.position.copyFrom(position);
  48985. this.rebuildAnglesAndRadius();
  48986. };
  48987. /**
  48988. * Defines the target the camera should look at.
  48989. * This will automatically adapt alpha beta and radius to fit within the new target.
  48990. * @param target Defines the new target as a Vector or a mesh
  48991. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48992. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48993. */
  48994. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48995. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48996. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48997. if (target.getBoundingInfo) {
  48998. if (toBoundingCenter) {
  48999. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49000. }
  49001. else {
  49002. this._targetBoundingCenter = null;
  49003. }
  49004. this._targetHost = target;
  49005. this._target = this._getTargetPosition();
  49006. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49007. }
  49008. else {
  49009. var newTarget = target;
  49010. var currentTarget = this._getTargetPosition();
  49011. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49012. return;
  49013. }
  49014. this._targetHost = null;
  49015. this._target = newTarget;
  49016. this._targetBoundingCenter = null;
  49017. this.onMeshTargetChangedObservable.notifyObservers(null);
  49018. }
  49019. this.rebuildAnglesAndRadius();
  49020. };
  49021. /** @hidden */
  49022. ArcRotateCamera.prototype._getViewMatrix = function () {
  49023. // Compute
  49024. var cosa = Math.cos(this.alpha);
  49025. var sina = Math.sin(this.alpha);
  49026. var cosb = Math.cos(this.beta);
  49027. var sinb = Math.sin(this.beta);
  49028. if (sinb === 0) {
  49029. sinb = 0.0001;
  49030. }
  49031. var target = this._getTargetPosition();
  49032. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49033. target.addToRef(this._computationVector, this._newPosition);
  49034. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49035. if (!this._collider) {
  49036. this._collider = new BABYLON.Collider();
  49037. }
  49038. this._collider._radius = this.collisionRadius;
  49039. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49040. this._collisionTriggered = true;
  49041. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49042. }
  49043. else {
  49044. this.position.copyFrom(this._newPosition);
  49045. var up = this.upVector;
  49046. if (this.allowUpsideDown && sinb < 0) {
  49047. up = up.clone();
  49048. up = up.negate();
  49049. }
  49050. this._computeViewMatrix(this.position, target, up);
  49051. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49052. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49053. }
  49054. this._currentTarget = target;
  49055. return this._viewMatrix;
  49056. };
  49057. /**
  49058. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49059. * @param meshes Defines the mesh to zoom on
  49060. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  49061. */
  49062. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49063. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49064. meshes = meshes || this.getScene().meshes;
  49065. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49066. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49067. this.radius = distance * this.zoomOnFactor;
  49068. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49069. };
  49070. /**
  49071. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49072. * The target will be changed but the radius
  49073. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49074. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  49075. */
  49076. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49077. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49078. var meshesOrMinMaxVector;
  49079. var distance;
  49080. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49081. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49082. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49083. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49084. }
  49085. else { //minMaxVector and distance
  49086. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49087. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49088. distance = minMaxVectorAndDistance.distance;
  49089. }
  49090. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49091. if (!doNotUpdateMaxZ) {
  49092. this.maxZ = distance * 2;
  49093. }
  49094. };
  49095. /**
  49096. * @override
  49097. * Override Camera.createRigCamera
  49098. */
  49099. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49100. var alphaShift = 0;
  49101. switch (this.cameraRigMode) {
  49102. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49104. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49105. case BABYLON.Camera.RIG_MODE_VR:
  49106. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49107. break;
  49108. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49109. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49110. break;
  49111. }
  49112. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49113. rigCam._cameraRigParams = {};
  49114. return rigCam;
  49115. };
  49116. /**
  49117. * @hidden
  49118. * @override
  49119. * Override Camera._updateRigCameras
  49120. */
  49121. ArcRotateCamera.prototype._updateRigCameras = function () {
  49122. var camLeft = this._rigCameras[0];
  49123. var camRight = this._rigCameras[1];
  49124. camLeft.beta = camRight.beta = this.beta;
  49125. camLeft.radius = camRight.radius = this.radius;
  49126. switch (this.cameraRigMode) {
  49127. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49128. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49130. case BABYLON.Camera.RIG_MODE_VR:
  49131. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49132. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49133. break;
  49134. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49135. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49136. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49137. break;
  49138. }
  49139. _super.prototype._updateRigCameras.call(this);
  49140. };
  49141. /**
  49142. * Destroy the camera and release the current resources hold by it.
  49143. */
  49144. ArcRotateCamera.prototype.dispose = function () {
  49145. this.inputs.clear();
  49146. _super.prototype.dispose.call(this);
  49147. };
  49148. /**
  49149. * Gets the current object class name.
  49150. * @return the class name
  49151. */
  49152. ArcRotateCamera.prototype.getClassName = function () {
  49153. return "ArcRotateCamera";
  49154. };
  49155. __decorate([
  49156. BABYLON.serialize()
  49157. ], ArcRotateCamera.prototype, "alpha", void 0);
  49158. __decorate([
  49159. BABYLON.serialize()
  49160. ], ArcRotateCamera.prototype, "beta", void 0);
  49161. __decorate([
  49162. BABYLON.serialize()
  49163. ], ArcRotateCamera.prototype, "radius", void 0);
  49164. __decorate([
  49165. BABYLON.serializeAsVector3("target")
  49166. ], ArcRotateCamera.prototype, "_target", void 0);
  49167. __decorate([
  49168. BABYLON.serialize()
  49169. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49170. __decorate([
  49171. BABYLON.serialize()
  49172. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49173. __decorate([
  49174. BABYLON.serialize()
  49175. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49176. __decorate([
  49177. BABYLON.serialize()
  49178. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49179. __decorate([
  49180. BABYLON.serialize()
  49181. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49182. __decorate([
  49183. BABYLON.serialize()
  49184. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49185. __decorate([
  49186. BABYLON.serialize()
  49187. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49188. __decorate([
  49189. BABYLON.serialize()
  49190. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49191. __decorate([
  49192. BABYLON.serialize()
  49193. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49194. __decorate([
  49195. BABYLON.serialize()
  49196. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49197. __decorate([
  49198. BABYLON.serialize()
  49199. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49200. __decorate([
  49201. BABYLON.serialize()
  49202. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49203. __decorate([
  49204. BABYLON.serialize()
  49205. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49206. __decorate([
  49207. BABYLON.serializeAsVector3()
  49208. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49209. __decorate([
  49210. BABYLON.serialize()
  49211. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49212. __decorate([
  49213. BABYLON.serialize()
  49214. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49215. __decorate([
  49216. BABYLON.serialize()
  49217. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49218. __decorate([
  49219. BABYLON.serialize()
  49220. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49221. __decorate([
  49222. BABYLON.serialize()
  49223. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49224. return ArcRotateCamera;
  49225. }(BABYLON.TargetCamera));
  49226. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49227. })(BABYLON || (BABYLON = {}));
  49228. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49229. var BABYLON;
  49230. (function (BABYLON) {
  49231. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49232. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49233. });
  49234. /**
  49235. * The HemisphericLight simulates the ambient environment light,
  49236. * so the passed direction is the light reflection direction, not the incoming direction.
  49237. */
  49238. var HemisphericLight = /** @class */ (function (_super) {
  49239. __extends(HemisphericLight, _super);
  49240. /**
  49241. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49242. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49243. * The HemisphericLight can't cast shadows.
  49244. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49245. * @param name The friendly name of the light
  49246. * @param direction The direction of the light reflection
  49247. * @param scene The scene the light belongs to
  49248. */
  49249. function HemisphericLight(name, direction, scene) {
  49250. var _this = _super.call(this, name, scene) || this;
  49251. /**
  49252. * The groundColor is the light in the opposite direction to the one specified during creation.
  49253. * 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.
  49254. */
  49255. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49256. _this.direction = direction || BABYLON.Vector3.Up();
  49257. return _this;
  49258. }
  49259. HemisphericLight.prototype._buildUniformLayout = function () {
  49260. this._uniformBuffer.addUniform("vLightData", 4);
  49261. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49262. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49263. this._uniformBuffer.addUniform("vLightGround", 3);
  49264. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49265. this._uniformBuffer.addUniform("depthValues", 2);
  49266. this._uniformBuffer.create();
  49267. };
  49268. /**
  49269. * Returns the string "HemisphericLight".
  49270. * @return The class name
  49271. */
  49272. HemisphericLight.prototype.getClassName = function () {
  49273. return "HemisphericLight";
  49274. };
  49275. /**
  49276. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49277. * Returns the updated direction.
  49278. * @param target The target the direction should point to
  49279. * @return The computed direction
  49280. */
  49281. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49282. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49283. return this.direction;
  49284. };
  49285. /**
  49286. * Returns the shadow generator associated to the light.
  49287. * @returns Always null for hemispheric lights because it does not support shadows.
  49288. */
  49289. HemisphericLight.prototype.getShadowGenerator = function () {
  49290. return null;
  49291. };
  49292. /**
  49293. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49294. * @param effect The effect to update
  49295. * @param lightIndex The index of the light in the effect to update
  49296. * @returns The hemispheric light
  49297. */
  49298. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49299. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49300. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49301. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49302. return this;
  49303. };
  49304. /**
  49305. * Computes the world matrix of the node
  49306. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49307. * @param useWasUpdatedFlag defines a reserved property
  49308. * @returns the world matrix
  49309. */
  49310. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49311. if (!this._worldMatrix) {
  49312. this._worldMatrix = BABYLON.Matrix.Identity();
  49313. }
  49314. return this._worldMatrix;
  49315. };
  49316. /**
  49317. * Returns the integer 3.
  49318. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49319. */
  49320. HemisphericLight.prototype.getTypeID = function () {
  49321. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49322. };
  49323. /**
  49324. * Prepares the list of defines specific to the light type.
  49325. * @param defines the list of defines
  49326. * @param lightIndex defines the index of the light for the effect
  49327. */
  49328. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49329. defines["HEMILIGHT" + lightIndex] = true;
  49330. };
  49331. __decorate([
  49332. BABYLON.serializeAsColor3()
  49333. ], HemisphericLight.prototype, "groundColor", void 0);
  49334. __decorate([
  49335. BABYLON.serializeAsVector3()
  49336. ], HemisphericLight.prototype, "direction", void 0);
  49337. return HemisphericLight;
  49338. }(BABYLON.Light));
  49339. BABYLON.HemisphericLight = HemisphericLight;
  49340. })(BABYLON || (BABYLON = {}));
  49341. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49342. var BABYLON;
  49343. (function (BABYLON) {
  49344. /**
  49345. * Base implementation IShadowLight
  49346. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49347. */
  49348. var ShadowLight = /** @class */ (function (_super) {
  49349. __extends(ShadowLight, _super);
  49350. function ShadowLight() {
  49351. var _this = _super !== null && _super.apply(this, arguments) || this;
  49352. _this._needProjectionMatrixCompute = true;
  49353. return _this;
  49354. }
  49355. ShadowLight.prototype._setPosition = function (value) {
  49356. this._position = value;
  49357. };
  49358. Object.defineProperty(ShadowLight.prototype, "position", {
  49359. /**
  49360. * Sets the position the shadow will be casted from. Also use as the light position for both
  49361. * point and spot lights.
  49362. */
  49363. get: function () {
  49364. return this._position;
  49365. },
  49366. /**
  49367. * Sets the position the shadow will be casted from. Also use as the light position for both
  49368. * point and spot lights.
  49369. */
  49370. set: function (value) {
  49371. this._setPosition(value);
  49372. },
  49373. enumerable: true,
  49374. configurable: true
  49375. });
  49376. ShadowLight.prototype._setDirection = function (value) {
  49377. this._direction = value;
  49378. };
  49379. Object.defineProperty(ShadowLight.prototype, "direction", {
  49380. /**
  49381. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49382. * Also use as the light direction on spot and directional lights.
  49383. */
  49384. get: function () {
  49385. return this._direction;
  49386. },
  49387. /**
  49388. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49389. * Also use as the light direction on spot and directional lights.
  49390. */
  49391. set: function (value) {
  49392. this._setDirection(value);
  49393. },
  49394. enumerable: true,
  49395. configurable: true
  49396. });
  49397. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49398. /**
  49399. * Gets the shadow projection clipping minimum z value.
  49400. */
  49401. get: function () {
  49402. return this._shadowMinZ;
  49403. },
  49404. /**
  49405. * Sets the shadow projection clipping minimum z value.
  49406. */
  49407. set: function (value) {
  49408. this._shadowMinZ = value;
  49409. this.forceProjectionMatrixCompute();
  49410. },
  49411. enumerable: true,
  49412. configurable: true
  49413. });
  49414. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49415. /**
  49416. * Sets the shadow projection clipping maximum z value.
  49417. */
  49418. get: function () {
  49419. return this._shadowMaxZ;
  49420. },
  49421. /**
  49422. * Gets the shadow projection clipping maximum z value.
  49423. */
  49424. set: function (value) {
  49425. this._shadowMaxZ = value;
  49426. this.forceProjectionMatrixCompute();
  49427. },
  49428. enumerable: true,
  49429. configurable: true
  49430. });
  49431. /**
  49432. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49433. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49434. */
  49435. ShadowLight.prototype.computeTransformedInformation = function () {
  49436. if (this.parent && this.parent.getWorldMatrix) {
  49437. if (!this.transformedPosition) {
  49438. this.transformedPosition = BABYLON.Vector3.Zero();
  49439. }
  49440. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49441. // In case the direction is present.
  49442. if (this.direction) {
  49443. if (!this.transformedDirection) {
  49444. this.transformedDirection = BABYLON.Vector3.Zero();
  49445. }
  49446. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49447. }
  49448. return true;
  49449. }
  49450. return false;
  49451. };
  49452. /**
  49453. * Return the depth scale used for the shadow map.
  49454. * @returns the depth scale.
  49455. */
  49456. ShadowLight.prototype.getDepthScale = function () {
  49457. return 50.0;
  49458. };
  49459. /**
  49460. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49461. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49462. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49463. */
  49464. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49465. return this.transformedDirection ? this.transformedDirection : this.direction;
  49466. };
  49467. /**
  49468. * Returns the ShadowLight absolute position in the World.
  49469. * @returns the position vector in world space
  49470. */
  49471. ShadowLight.prototype.getAbsolutePosition = function () {
  49472. return this.transformedPosition ? this.transformedPosition : this.position;
  49473. };
  49474. /**
  49475. * Sets the ShadowLight direction toward the passed target.
  49476. * @param target The point tot target in local space
  49477. * @returns the updated ShadowLight direction
  49478. */
  49479. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49480. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49481. return this.direction;
  49482. };
  49483. /**
  49484. * Returns the light rotation in euler definition.
  49485. * @returns the x y z rotation in local space.
  49486. */
  49487. ShadowLight.prototype.getRotation = function () {
  49488. this.direction.normalize();
  49489. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49490. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49491. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49492. };
  49493. /**
  49494. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49495. * @returns true if a cube texture needs to be use
  49496. */
  49497. ShadowLight.prototype.needCube = function () {
  49498. return false;
  49499. };
  49500. /**
  49501. * Detects if the projection matrix requires to be recomputed this frame.
  49502. * @returns true if it requires to be recomputed otherwise, false.
  49503. */
  49504. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49505. return this._needProjectionMatrixCompute;
  49506. };
  49507. /**
  49508. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49509. */
  49510. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49511. this._needProjectionMatrixCompute = true;
  49512. };
  49513. /** @hidden */
  49514. ShadowLight.prototype._initCache = function () {
  49515. _super.prototype._initCache.call(this);
  49516. this._cache.position = BABYLON.Vector3.Zero();
  49517. };
  49518. /** @hidden */
  49519. ShadowLight.prototype._isSynchronized = function () {
  49520. if (!this._cache.position.equals(this.position))
  49521. return false;
  49522. return true;
  49523. };
  49524. /**
  49525. * Computes the world matrix of the node
  49526. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49527. * @returns the world matrix
  49528. */
  49529. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49530. if (!force && this.isSynchronized()) {
  49531. this._currentRenderId = this.getScene().getRenderId();
  49532. return this._worldMatrix;
  49533. }
  49534. this._updateCache();
  49535. this._cache.position.copyFrom(this.position);
  49536. if (!this._worldMatrix) {
  49537. this._worldMatrix = BABYLON.Matrix.Identity();
  49538. }
  49539. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49540. if (this.parent && this.parent.getWorldMatrix) {
  49541. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49542. this._markSyncedWithParent();
  49543. }
  49544. // Cache the determinant
  49545. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49546. return this._worldMatrix;
  49547. };
  49548. /**
  49549. * Gets the minZ used for shadow according to both the scene and the light.
  49550. * @param activeCamera The camera we are returning the min for
  49551. * @returns the depth min z
  49552. */
  49553. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49554. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49555. };
  49556. /**
  49557. * Gets the maxZ used for shadow according to both the scene and the light.
  49558. * @param activeCamera The camera we are returning the max for
  49559. * @returns the depth max z
  49560. */
  49561. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49562. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49563. };
  49564. /**
  49565. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49566. * @param matrix The materix to updated with the projection information
  49567. * @param viewMatrix The transform matrix of the light
  49568. * @param renderList The list of mesh to render in the map
  49569. * @returns The current light
  49570. */
  49571. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49572. if (this.customProjectionMatrixBuilder) {
  49573. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49574. }
  49575. else {
  49576. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49577. }
  49578. return this;
  49579. };
  49580. __decorate([
  49581. BABYLON.serializeAsVector3()
  49582. ], ShadowLight.prototype, "position", null);
  49583. __decorate([
  49584. BABYLON.serializeAsVector3()
  49585. ], ShadowLight.prototype, "direction", null);
  49586. __decorate([
  49587. BABYLON.serialize()
  49588. ], ShadowLight.prototype, "shadowMinZ", null);
  49589. __decorate([
  49590. BABYLON.serialize()
  49591. ], ShadowLight.prototype, "shadowMaxZ", null);
  49592. return ShadowLight;
  49593. }(BABYLON.Light));
  49594. BABYLON.ShadowLight = ShadowLight;
  49595. })(BABYLON || (BABYLON = {}));
  49596. //# sourceMappingURL=babylon.shadowLight.js.map
  49597. var BABYLON;
  49598. (function (BABYLON) {
  49599. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49600. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49601. });
  49602. /**
  49603. * A point light is a light defined by an unique point in world space.
  49604. * The light is emitted in every direction from this point.
  49605. * A good example of a point light is a standard light bulb.
  49606. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49607. */
  49608. var PointLight = /** @class */ (function (_super) {
  49609. __extends(PointLight, _super);
  49610. /**
  49611. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49612. * A PointLight emits the light in every direction.
  49613. * It can cast shadows.
  49614. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49615. * ```javascript
  49616. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49617. * ```
  49618. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49619. * @param name The light friendly name
  49620. * @param position The position of the point light in the scene
  49621. * @param scene The scene the lights belongs to
  49622. */
  49623. function PointLight(name, position, scene) {
  49624. var _this = _super.call(this, name, scene) || this;
  49625. _this._shadowAngle = Math.PI / 2;
  49626. _this.position = position;
  49627. return _this;
  49628. }
  49629. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49630. /**
  49631. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49632. * This specifies what angle the shadow will use to be created.
  49633. *
  49634. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49635. */
  49636. get: function () {
  49637. return this._shadowAngle;
  49638. },
  49639. /**
  49640. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49641. * This specifies what angle the shadow will use to be created.
  49642. *
  49643. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49644. */
  49645. set: function (value) {
  49646. this._shadowAngle = value;
  49647. this.forceProjectionMatrixCompute();
  49648. },
  49649. enumerable: true,
  49650. configurable: true
  49651. });
  49652. Object.defineProperty(PointLight.prototype, "direction", {
  49653. /**
  49654. * Gets the direction if it has been set.
  49655. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49656. */
  49657. get: function () {
  49658. return this._direction;
  49659. },
  49660. /**
  49661. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49662. */
  49663. set: function (value) {
  49664. var previousNeedCube = this.needCube();
  49665. this._direction = value;
  49666. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49667. this._shadowGenerator.recreateShadowMap();
  49668. }
  49669. },
  49670. enumerable: true,
  49671. configurable: true
  49672. });
  49673. /**
  49674. * Returns the string "PointLight"
  49675. * @returns the class name
  49676. */
  49677. PointLight.prototype.getClassName = function () {
  49678. return "PointLight";
  49679. };
  49680. /**
  49681. * Returns the integer 0.
  49682. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49683. */
  49684. PointLight.prototype.getTypeID = function () {
  49685. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49686. };
  49687. /**
  49688. * Specifies wether or not the shadowmap should be a cube texture.
  49689. * @returns true if the shadowmap needs to be a cube texture.
  49690. */
  49691. PointLight.prototype.needCube = function () {
  49692. return !this.direction;
  49693. };
  49694. /**
  49695. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49696. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49697. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49698. */
  49699. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49700. if (this.direction) {
  49701. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49702. }
  49703. else {
  49704. switch (faceIndex) {
  49705. case 0:
  49706. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49707. case 1:
  49708. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49709. case 2:
  49710. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49711. case 3:
  49712. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49713. case 4:
  49714. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49715. case 5:
  49716. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49717. }
  49718. }
  49719. return BABYLON.Vector3.Zero();
  49720. };
  49721. /**
  49722. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49723. * - fov = PI / 2
  49724. * - aspect ratio : 1.0
  49725. * - z-near and far equal to the active camera minZ and maxZ.
  49726. * Returns the PointLight.
  49727. */
  49728. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49729. var activeCamera = this.getScene().activeCamera;
  49730. if (!activeCamera) {
  49731. return;
  49732. }
  49733. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49734. };
  49735. PointLight.prototype._buildUniformLayout = function () {
  49736. this._uniformBuffer.addUniform("vLightData", 4);
  49737. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49738. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49739. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49740. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49741. this._uniformBuffer.addUniform("depthValues", 2);
  49742. this._uniformBuffer.create();
  49743. };
  49744. /**
  49745. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49746. * @param effect The effect to update
  49747. * @param lightIndex The index of the light in the effect to update
  49748. * @returns The point light
  49749. */
  49750. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49751. if (this.computeTransformedInformation()) {
  49752. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49753. }
  49754. else {
  49755. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49756. }
  49757. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49758. return this;
  49759. };
  49760. /**
  49761. * Prepares the list of defines specific to the light type.
  49762. * @param defines the list of defines
  49763. * @param lightIndex defines the index of the light for the effect
  49764. */
  49765. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49766. defines["POINTLIGHT" + lightIndex] = true;
  49767. };
  49768. __decorate([
  49769. BABYLON.serialize()
  49770. ], PointLight.prototype, "shadowAngle", null);
  49771. return PointLight;
  49772. }(BABYLON.ShadowLight));
  49773. BABYLON.PointLight = PointLight;
  49774. })(BABYLON || (BABYLON = {}));
  49775. //# sourceMappingURL=babylon.pointLight.js.map
  49776. var BABYLON;
  49777. (function (BABYLON) {
  49778. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49779. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49780. });
  49781. /**
  49782. * A directional light is defined by a direction (what a surprise!).
  49783. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49784. * 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.
  49785. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49786. */
  49787. var DirectionalLight = /** @class */ (function (_super) {
  49788. __extends(DirectionalLight, _super);
  49789. /**
  49790. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49791. * The directional light is emitted from everywhere in the given direction.
  49792. * It can cast shadows.
  49793. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49794. * @param name The friendly name of the light
  49795. * @param direction The direction of the light
  49796. * @param scene The scene the light belongs to
  49797. */
  49798. function DirectionalLight(name, direction, scene) {
  49799. var _this = _super.call(this, name, scene) || this;
  49800. _this._shadowFrustumSize = 0;
  49801. _this._shadowOrthoScale = 0.1;
  49802. /**
  49803. * Automatically compute the projection matrix to best fit (including all the casters)
  49804. * on each frame.
  49805. */
  49806. _this.autoUpdateExtends = true;
  49807. // Cache
  49808. _this._orthoLeft = Number.MAX_VALUE;
  49809. _this._orthoRight = Number.MIN_VALUE;
  49810. _this._orthoTop = Number.MIN_VALUE;
  49811. _this._orthoBottom = Number.MAX_VALUE;
  49812. _this.position = direction.scale(-1.0);
  49813. _this.direction = direction;
  49814. return _this;
  49815. }
  49816. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49817. /**
  49818. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49819. */
  49820. get: function () {
  49821. return this._shadowFrustumSize;
  49822. },
  49823. /**
  49824. * Specifies a fix frustum size for the shadow generation.
  49825. */
  49826. set: function (value) {
  49827. this._shadowFrustumSize = value;
  49828. this.forceProjectionMatrixCompute();
  49829. },
  49830. enumerable: true,
  49831. configurable: true
  49832. });
  49833. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49834. /**
  49835. * Gets the shadow projection scale against the optimal computed one.
  49836. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49837. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49838. */
  49839. get: function () {
  49840. return this._shadowOrthoScale;
  49841. },
  49842. /**
  49843. * Sets the shadow projection scale against the optimal computed one.
  49844. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49845. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49846. */
  49847. set: function (value) {
  49848. this._shadowOrthoScale = value;
  49849. this.forceProjectionMatrixCompute();
  49850. },
  49851. enumerable: true,
  49852. configurable: true
  49853. });
  49854. /**
  49855. * Returns the string "DirectionalLight".
  49856. * @return The class name
  49857. */
  49858. DirectionalLight.prototype.getClassName = function () {
  49859. return "DirectionalLight";
  49860. };
  49861. /**
  49862. * Returns the integer 1.
  49863. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49864. */
  49865. DirectionalLight.prototype.getTypeID = function () {
  49866. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49867. };
  49868. /**
  49869. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49870. * Returns the DirectionalLight Shadow projection matrix.
  49871. */
  49872. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49873. if (this.shadowFrustumSize > 0) {
  49874. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49875. }
  49876. else {
  49877. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49878. }
  49879. };
  49880. /**
  49881. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49882. * Returns the DirectionalLight Shadow projection matrix.
  49883. */
  49884. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49885. var activeCamera = this.getScene().activeCamera;
  49886. if (!activeCamera) {
  49887. return;
  49888. }
  49889. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49890. };
  49891. /**
  49892. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49893. * Returns the DirectionalLight Shadow projection matrix.
  49894. */
  49895. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49896. var activeCamera = this.getScene().activeCamera;
  49897. if (!activeCamera) {
  49898. return;
  49899. }
  49900. // Check extends
  49901. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49902. var tempVector3 = BABYLON.Vector3.Zero();
  49903. this._orthoLeft = Number.MAX_VALUE;
  49904. this._orthoRight = Number.MIN_VALUE;
  49905. this._orthoTop = Number.MIN_VALUE;
  49906. this._orthoBottom = Number.MAX_VALUE;
  49907. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49908. var mesh = renderList[meshIndex];
  49909. if (!mesh) {
  49910. continue;
  49911. }
  49912. var boundingInfo = mesh.getBoundingInfo();
  49913. var boundingBox = boundingInfo.boundingBox;
  49914. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49915. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49916. if (tempVector3.x < this._orthoLeft)
  49917. this._orthoLeft = tempVector3.x;
  49918. if (tempVector3.y < this._orthoBottom)
  49919. this._orthoBottom = tempVector3.y;
  49920. if (tempVector3.x > this._orthoRight)
  49921. this._orthoRight = tempVector3.x;
  49922. if (tempVector3.y > this._orthoTop)
  49923. this._orthoTop = tempVector3.y;
  49924. }
  49925. }
  49926. }
  49927. var xOffset = this._orthoRight - this._orthoLeft;
  49928. var yOffset = this._orthoTop - this._orthoBottom;
  49929. 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);
  49930. };
  49931. DirectionalLight.prototype._buildUniformLayout = function () {
  49932. this._uniformBuffer.addUniform("vLightData", 4);
  49933. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49934. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49935. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49936. this._uniformBuffer.addUniform("depthValues", 2);
  49937. this._uniformBuffer.create();
  49938. };
  49939. /**
  49940. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49941. * @param effect The effect to update
  49942. * @param lightIndex The index of the light in the effect to update
  49943. * @returns The directional light
  49944. */
  49945. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49946. if (this.computeTransformedInformation()) {
  49947. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49948. return this;
  49949. }
  49950. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49951. return this;
  49952. };
  49953. /**
  49954. * Gets the minZ used for shadow according to both the scene and the light.
  49955. *
  49956. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49957. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49958. * @param activeCamera The camera we are returning the min for
  49959. * @returns the depth min z
  49960. */
  49961. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49962. return 1;
  49963. };
  49964. /**
  49965. * Gets the maxZ used for shadow according to both the scene and the light.
  49966. *
  49967. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49968. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49969. * @param activeCamera The camera we are returning the max for
  49970. * @returns the depth max z
  49971. */
  49972. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49973. return 1;
  49974. };
  49975. /**
  49976. * Prepares the list of defines specific to the light type.
  49977. * @param defines the list of defines
  49978. * @param lightIndex defines the index of the light for the effect
  49979. */
  49980. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49981. defines["DIRLIGHT" + lightIndex] = true;
  49982. };
  49983. __decorate([
  49984. BABYLON.serialize()
  49985. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49986. __decorate([
  49987. BABYLON.serialize()
  49988. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49989. __decorate([
  49990. BABYLON.serialize()
  49991. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49992. return DirectionalLight;
  49993. }(BABYLON.ShadowLight));
  49994. BABYLON.DirectionalLight = DirectionalLight;
  49995. })(BABYLON || (BABYLON = {}));
  49996. //# sourceMappingURL=babylon.directionalLight.js.map
  49997. var BABYLON;
  49998. (function (BABYLON) {
  49999. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50000. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50001. });
  50002. /**
  50003. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50004. * These values define a cone of light starting from the position, emitting toward the direction.
  50005. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50006. * and the exponent defines the speed of the decay of the light with distance (reach).
  50007. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50008. */
  50009. var SpotLight = /** @class */ (function (_super) {
  50010. __extends(SpotLight, _super);
  50011. /**
  50012. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50013. * It can cast shadows.
  50014. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50015. * @param name The light friendly name
  50016. * @param position The position of the spot light in the scene
  50017. * @param direction The direction of the light in the scene
  50018. * @param angle The cone angle of the light in Radians
  50019. * @param exponent The light decay speed with the distance from the emission spot
  50020. * @param scene The scene the lights belongs to
  50021. */
  50022. function SpotLight(name, position, direction, angle, exponent, scene) {
  50023. var _this = _super.call(this, name, scene) || this;
  50024. _this._innerAngle = 0;
  50025. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50026. _this._projectionTextureLightNear = 1e-6;
  50027. _this._projectionTextureLightFar = 1000.0;
  50028. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50029. _this._projectionTextureViewLightDirty = true;
  50030. _this._projectionTextureProjectionLightDirty = true;
  50031. _this._projectionTextureDirty = true;
  50032. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50033. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50034. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50035. _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);
  50036. _this.position = position;
  50037. _this.direction = direction;
  50038. _this.angle = angle;
  50039. _this.exponent = exponent;
  50040. return _this;
  50041. }
  50042. Object.defineProperty(SpotLight.prototype, "angle", {
  50043. /**
  50044. * Gets the cone angle of the spot light in Radians.
  50045. */
  50046. get: function () {
  50047. return this._angle;
  50048. },
  50049. /**
  50050. * Sets the cone angle of the spot light in Radians.
  50051. */
  50052. set: function (value) {
  50053. this._angle = value;
  50054. this._cosHalfAngle = Math.cos(value * 0.5);
  50055. this._projectionTextureProjectionLightDirty = true;
  50056. this.forceProjectionMatrixCompute();
  50057. this._computeAngleValues();
  50058. },
  50059. enumerable: true,
  50060. configurable: true
  50061. });
  50062. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50063. /**
  50064. * Only used in gltf falloff mode, this defines the angle where
  50065. * the directional falloff will start before cutting at angle which could be seen
  50066. * as outer angle.
  50067. */
  50068. get: function () {
  50069. return this._innerAngle;
  50070. },
  50071. /**
  50072. * Only used in gltf falloff mode, this defines the angle where
  50073. * the directional falloff will start before cutting at angle which could be seen
  50074. * as outer angle.
  50075. */
  50076. set: function (value) {
  50077. this._innerAngle = value;
  50078. this._computeAngleValues();
  50079. },
  50080. enumerable: true,
  50081. configurable: true
  50082. });
  50083. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50084. /**
  50085. * Allows scaling the angle of the light for shadow generation only.
  50086. */
  50087. get: function () {
  50088. return this._shadowAngleScale;
  50089. },
  50090. /**
  50091. * Allows scaling the angle of the light for shadow generation only.
  50092. */
  50093. set: function (value) {
  50094. this._shadowAngleScale = value;
  50095. this.forceProjectionMatrixCompute();
  50096. },
  50097. enumerable: true,
  50098. configurable: true
  50099. });
  50100. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50101. /**
  50102. * Allows reading the projecton texture
  50103. */
  50104. get: function () {
  50105. return this._projectionTextureMatrix;
  50106. },
  50107. enumerable: true,
  50108. configurable: true
  50109. });
  50110. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50111. /**
  50112. * Gets the near clip of the Spotlight for texture projection.
  50113. */
  50114. get: function () {
  50115. return this._projectionTextureLightNear;
  50116. },
  50117. /**
  50118. * Sets the near clip of the Spotlight for texture projection.
  50119. */
  50120. set: function (value) {
  50121. this._projectionTextureLightNear = value;
  50122. this._projectionTextureProjectionLightDirty = true;
  50123. },
  50124. enumerable: true,
  50125. configurable: true
  50126. });
  50127. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50128. /**
  50129. * Gets the far clip of the Spotlight for texture projection.
  50130. */
  50131. get: function () {
  50132. return this._projectionTextureLightFar;
  50133. },
  50134. /**
  50135. * Sets the far clip of the Spotlight for texture projection.
  50136. */
  50137. set: function (value) {
  50138. this._projectionTextureLightFar = value;
  50139. this._projectionTextureProjectionLightDirty = true;
  50140. },
  50141. enumerable: true,
  50142. configurable: true
  50143. });
  50144. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50145. /**
  50146. * Gets the Up vector of the Spotlight for texture projection.
  50147. */
  50148. get: function () {
  50149. return this._projectionTextureUpDirection;
  50150. },
  50151. /**
  50152. * Sets the Up vector of the Spotlight for texture projection.
  50153. */
  50154. set: function (value) {
  50155. this._projectionTextureUpDirection = value;
  50156. this._projectionTextureProjectionLightDirty = true;
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50162. /**
  50163. * Gets the projection texture of the light.
  50164. */
  50165. get: function () {
  50166. return this._projectionTexture;
  50167. },
  50168. /**
  50169. * Sets the projection texture of the light.
  50170. */
  50171. set: function (value) {
  50172. this._projectionTexture = value;
  50173. this._projectionTextureDirty = true;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. /**
  50179. * Returns the string "SpotLight".
  50180. * @returns the class name
  50181. */
  50182. SpotLight.prototype.getClassName = function () {
  50183. return "SpotLight";
  50184. };
  50185. /**
  50186. * Returns the integer 2.
  50187. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50188. */
  50189. SpotLight.prototype.getTypeID = function () {
  50190. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50191. };
  50192. /**
  50193. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50194. */
  50195. SpotLight.prototype._setDirection = function (value) {
  50196. _super.prototype._setDirection.call(this, value);
  50197. this._projectionTextureViewLightDirty = true;
  50198. };
  50199. /**
  50200. * Overrides the position setter to recompute the projection texture view light Matrix.
  50201. */
  50202. SpotLight.prototype._setPosition = function (value) {
  50203. _super.prototype._setPosition.call(this, value);
  50204. this._projectionTextureViewLightDirty = true;
  50205. };
  50206. /**
  50207. * 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.
  50208. * Returns the SpotLight.
  50209. */
  50210. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50211. var activeCamera = this.getScene().activeCamera;
  50212. if (!activeCamera) {
  50213. return;
  50214. }
  50215. this._shadowAngleScale = this._shadowAngleScale || 1;
  50216. var angle = this._shadowAngleScale * this._angle;
  50217. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50218. };
  50219. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50220. this._projectionTextureViewLightDirty = false;
  50221. this._projectionTextureDirty = true;
  50222. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50223. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50224. };
  50225. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50226. this._projectionTextureProjectionLightDirty = false;
  50227. this._projectionTextureDirty = true;
  50228. var light_far = this.projectionTextureLightFar;
  50229. var light_near = this.projectionTextureLightNear;
  50230. var P = light_far / (light_far - light_near);
  50231. var Q = -P * light_near;
  50232. var S = 1.0 / Math.tan(this._angle / 2.0);
  50233. var A = 1.0;
  50234. 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);
  50235. };
  50236. /**
  50237. * Main function for light texture projection matrix computing.
  50238. */
  50239. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50240. this._projectionTextureDirty = false;
  50241. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50242. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50243. };
  50244. SpotLight.prototype._buildUniformLayout = function () {
  50245. this._uniformBuffer.addUniform("vLightData", 4);
  50246. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50247. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50248. this._uniformBuffer.addUniform("vLightDirection", 3);
  50249. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50250. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50251. this._uniformBuffer.addUniform("depthValues", 2);
  50252. this._uniformBuffer.create();
  50253. };
  50254. SpotLight.prototype._computeAngleValues = function () {
  50255. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50256. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50257. };
  50258. /**
  50259. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50260. * @param effect The effect to update
  50261. * @param lightIndex The index of the light in the effect to update
  50262. * @returns The spot light
  50263. */
  50264. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50265. var normalizeDirection;
  50266. if (this.computeTransformedInformation()) {
  50267. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50268. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50269. }
  50270. else {
  50271. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50272. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50273. }
  50274. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50275. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50276. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50277. if (this._projectionTextureViewLightDirty) {
  50278. this._computeProjectionTextureViewLightMatrix();
  50279. }
  50280. if (this._projectionTextureProjectionLightDirty) {
  50281. this._computeProjectionTextureProjectionLightMatrix();
  50282. }
  50283. if (this._projectionTextureDirty) {
  50284. this._computeProjectionTextureMatrix();
  50285. }
  50286. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50287. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50288. }
  50289. return this;
  50290. };
  50291. /**
  50292. * Disposes the light and the associated resources.
  50293. */
  50294. SpotLight.prototype.dispose = function () {
  50295. _super.prototype.dispose.call(this);
  50296. if (this._projectionTexture) {
  50297. this._projectionTexture.dispose();
  50298. }
  50299. };
  50300. /**
  50301. * Prepares the list of defines specific to the light type.
  50302. * @param defines the list of defines
  50303. * @param lightIndex defines the index of the light for the effect
  50304. */
  50305. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50306. defines["SPOTLIGHT" + lightIndex] = true;
  50307. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50308. };
  50309. __decorate([
  50310. BABYLON.serialize()
  50311. ], SpotLight.prototype, "angle", null);
  50312. __decorate([
  50313. BABYLON.serialize()
  50314. ], SpotLight.prototype, "innerAngle", null);
  50315. __decorate([
  50316. BABYLON.serialize()
  50317. ], SpotLight.prototype, "shadowAngleScale", null);
  50318. __decorate([
  50319. BABYLON.serialize()
  50320. ], SpotLight.prototype, "exponent", void 0);
  50321. __decorate([
  50322. BABYLON.serialize()
  50323. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50324. __decorate([
  50325. BABYLON.serialize()
  50326. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50327. __decorate([
  50328. BABYLON.serialize()
  50329. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50330. __decorate([
  50331. BABYLON.serializeAsTexture("projectedLightTexture")
  50332. ], SpotLight.prototype, "_projectionTexture", void 0);
  50333. return SpotLight;
  50334. }(BABYLON.ShadowLight));
  50335. BABYLON.SpotLight = SpotLight;
  50336. })(BABYLON || (BABYLON = {}));
  50337. //# sourceMappingURL=babylon.spotLight.js.map
  50338. var BABYLON;
  50339. (function (BABYLON) {
  50340. /**
  50341. * Class used to override all child animations of a given target
  50342. */
  50343. var AnimationPropertiesOverride = /** @class */ (function () {
  50344. function AnimationPropertiesOverride() {
  50345. /**
  50346. * Gets or sets a value indicating if animation blending must be used
  50347. */
  50348. this.enableBlending = false;
  50349. /**
  50350. * Gets or sets the blending speed to use when enableBlending is true
  50351. */
  50352. this.blendingSpeed = 0.01;
  50353. /**
  50354. * Gets or sets the default loop mode to use
  50355. */
  50356. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50357. }
  50358. return AnimationPropertiesOverride;
  50359. }());
  50360. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50361. })(BABYLON || (BABYLON = {}));
  50362. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50363. var BABYLON;
  50364. (function (BABYLON) {
  50365. /**
  50366. * Represents the range of an animation
  50367. */
  50368. var AnimationRange = /** @class */ (function () {
  50369. /**
  50370. * Initializes the range of an animation
  50371. * @param name The name of the animation range
  50372. * @param from The starting frame of the animation
  50373. * @param to The ending frame of the animation
  50374. */
  50375. function AnimationRange(
  50376. /**The name of the animation range**/
  50377. name,
  50378. /**The starting frame of the animation */
  50379. from,
  50380. /**The ending frame of the animation*/
  50381. to) {
  50382. this.name = name;
  50383. this.from = from;
  50384. this.to = to;
  50385. }
  50386. /**
  50387. * Makes a copy of the animation range
  50388. * @returns A copy of the animation range
  50389. */
  50390. AnimationRange.prototype.clone = function () {
  50391. return new AnimationRange(this.name, this.from, this.to);
  50392. };
  50393. return AnimationRange;
  50394. }());
  50395. BABYLON.AnimationRange = AnimationRange;
  50396. /**
  50397. * Composed of a frame, and an action function
  50398. */
  50399. var AnimationEvent = /** @class */ (function () {
  50400. /**
  50401. * Initializes the animation event
  50402. * @param frame The frame for which the event is triggered
  50403. * @param action The event to perform when triggered
  50404. * @param onlyOnce Specifies if the event should be triggered only once
  50405. */
  50406. function AnimationEvent(
  50407. /** The frame for which the event is triggered **/
  50408. frame,
  50409. /** The event to perform when triggered **/
  50410. action,
  50411. /** Specifies if the event should be triggered only once**/
  50412. onlyOnce) {
  50413. this.frame = frame;
  50414. this.action = action;
  50415. this.onlyOnce = onlyOnce;
  50416. /**
  50417. * Specifies if the animation event is done
  50418. */
  50419. this.isDone = false;
  50420. }
  50421. /** @hidden */
  50422. AnimationEvent.prototype._clone = function () {
  50423. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50424. };
  50425. return AnimationEvent;
  50426. }());
  50427. BABYLON.AnimationEvent = AnimationEvent;
  50428. /**
  50429. * A cursor which tracks a point on a path
  50430. */
  50431. var PathCursor = /** @class */ (function () {
  50432. /**
  50433. * Initializes the path cursor
  50434. * @param path The path to track
  50435. */
  50436. function PathCursor(path) {
  50437. this.path = path;
  50438. /**
  50439. * Stores path cursor callbacks for when an onchange event is triggered
  50440. */
  50441. this._onchange = new Array();
  50442. /**
  50443. * The value of the path cursor
  50444. */
  50445. this.value = 0;
  50446. /**
  50447. * The animation array of the path cursor
  50448. */
  50449. this.animations = new Array();
  50450. }
  50451. /**
  50452. * Gets the cursor point on the path
  50453. * @returns A point on the path cursor at the cursor location
  50454. */
  50455. PathCursor.prototype.getPoint = function () {
  50456. var point = this.path.getPointAtLengthPosition(this.value);
  50457. return new BABYLON.Vector3(point.x, 0, point.y);
  50458. };
  50459. /**
  50460. * Moves the cursor ahead by the step amount
  50461. * @param step The amount to move the cursor forward
  50462. * @returns This path cursor
  50463. */
  50464. PathCursor.prototype.moveAhead = function (step) {
  50465. if (step === void 0) { step = 0.002; }
  50466. this.move(step);
  50467. return this;
  50468. };
  50469. /**
  50470. * Moves the cursor behind by the step amount
  50471. * @param step The amount to move the cursor back
  50472. * @returns This path cursor
  50473. */
  50474. PathCursor.prototype.moveBack = function (step) {
  50475. if (step === void 0) { step = 0.002; }
  50476. this.move(-step);
  50477. return this;
  50478. };
  50479. /**
  50480. * Moves the cursor by the step amount
  50481. * If the step amount is greater than one, an exception is thrown
  50482. * @param step The amount to move the cursor
  50483. * @returns This path cursor
  50484. */
  50485. PathCursor.prototype.move = function (step) {
  50486. if (Math.abs(step) > 1) {
  50487. throw "step size should be less than 1.";
  50488. }
  50489. this.value += step;
  50490. this.ensureLimits();
  50491. this.raiseOnChange();
  50492. return this;
  50493. };
  50494. /**
  50495. * Ensures that the value is limited between zero and one
  50496. * @returns This path cursor
  50497. */
  50498. PathCursor.prototype.ensureLimits = function () {
  50499. while (this.value > 1) {
  50500. this.value -= 1;
  50501. }
  50502. while (this.value < 0) {
  50503. this.value += 1;
  50504. }
  50505. return this;
  50506. };
  50507. /**
  50508. * Runs onchange callbacks on change (used by the animation engine)
  50509. * @returns This path cursor
  50510. */
  50511. PathCursor.prototype.raiseOnChange = function () {
  50512. var _this = this;
  50513. this._onchange.forEach(function (f) { return f(_this); });
  50514. return this;
  50515. };
  50516. /**
  50517. * Executes a function on change
  50518. * @param f A path cursor onchange callback
  50519. * @returns This path cursor
  50520. */
  50521. PathCursor.prototype.onchange = function (f) {
  50522. this._onchange.push(f);
  50523. return this;
  50524. };
  50525. return PathCursor;
  50526. }());
  50527. BABYLON.PathCursor = PathCursor;
  50528. /**
  50529. * Enum for the animation key frame interpolation type
  50530. */
  50531. var AnimationKeyInterpolation;
  50532. (function (AnimationKeyInterpolation) {
  50533. /**
  50534. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50535. */
  50536. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50537. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50538. /**
  50539. * Class used to store any kind of animation
  50540. */
  50541. var Animation = /** @class */ (function () {
  50542. /**
  50543. * Initializes the animation
  50544. * @param name Name of the animation
  50545. * @param targetProperty Property to animate
  50546. * @param framePerSecond The frames per second of the animation
  50547. * @param dataType The data type of the animation
  50548. * @param loopMode The loop mode of the animation
  50549. * @param enableBlendings Specifies if blending should be enabled
  50550. */
  50551. function Animation(
  50552. /**Name of the animation */
  50553. name,
  50554. /**Property to animate */
  50555. targetProperty,
  50556. /**The frames per second of the animation */
  50557. framePerSecond,
  50558. /**The data type of the animation */
  50559. dataType,
  50560. /**The loop mode of the animation */
  50561. loopMode,
  50562. /**Specifies if blending should be enabled */
  50563. enableBlending) {
  50564. this.name = name;
  50565. this.targetProperty = targetProperty;
  50566. this.framePerSecond = framePerSecond;
  50567. this.dataType = dataType;
  50568. this.loopMode = loopMode;
  50569. this.enableBlending = enableBlending;
  50570. /**
  50571. * @hidden Internal use only
  50572. */
  50573. this._runtimeAnimations = new Array();
  50574. /**
  50575. * The set of event that will be linked to this animation
  50576. */
  50577. this._events = new Array();
  50578. /**
  50579. * Stores the blending speed of the animation
  50580. */
  50581. this.blendingSpeed = 0.01;
  50582. /**
  50583. * Stores the animation ranges for the animation
  50584. */
  50585. this._ranges = {};
  50586. this.targetPropertyPath = targetProperty.split(".");
  50587. this.dataType = dataType;
  50588. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50589. }
  50590. /**
  50591. * @hidden Internal use
  50592. */
  50593. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50594. var dataType = undefined;
  50595. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50596. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50597. }
  50598. else if (from instanceof BABYLON.Quaternion) {
  50599. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50600. }
  50601. else if (from instanceof BABYLON.Vector3) {
  50602. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50603. }
  50604. else if (from instanceof BABYLON.Vector2) {
  50605. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50606. }
  50607. else if (from instanceof BABYLON.Color3) {
  50608. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50609. }
  50610. else if (from instanceof BABYLON.Size) {
  50611. dataType = Animation.ANIMATIONTYPE_SIZE;
  50612. }
  50613. if (dataType == undefined) {
  50614. return null;
  50615. }
  50616. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50617. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50618. animation.setKeys(keys);
  50619. if (easingFunction !== undefined) {
  50620. animation.setEasingFunction(easingFunction);
  50621. }
  50622. return animation;
  50623. };
  50624. /**
  50625. * Sets up an animation
  50626. * @param property The property to animate
  50627. * @param animationType The animation type to apply
  50628. * @param framePerSecond The frames per second of the animation
  50629. * @param easingFunction The easing function used in the animation
  50630. * @returns The created animation
  50631. */
  50632. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50633. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50634. animation.setEasingFunction(easingFunction);
  50635. return animation;
  50636. };
  50637. /**
  50638. * Create and start an animation on a node
  50639. * @param name defines the name of the global animation that will be run on all nodes
  50640. * @param node defines the root node where the animation will take place
  50641. * @param targetProperty defines property to animate
  50642. * @param framePerSecond defines the number of frame per second yo use
  50643. * @param totalFrame defines the number of frames in total
  50644. * @param from defines the initial value
  50645. * @param to defines the final value
  50646. * @param loopMode defines which loop mode you want to use (off by default)
  50647. * @param easingFunction defines the easing function to use (linear by default)
  50648. * @param onAnimationEnd defines the callback to call when animation end
  50649. * @returns the animatable created for this animation
  50650. */
  50651. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50652. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50653. if (!animation) {
  50654. return null;
  50655. }
  50656. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50657. };
  50658. /**
  50659. * Create and start an animation on a node and its descendants
  50660. * @param name defines the name of the global animation that will be run on all nodes
  50661. * @param node defines the root node where the animation will take place
  50662. * @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
  50663. * @param targetProperty defines property to animate
  50664. * @param framePerSecond defines the number of frame per second to use
  50665. * @param totalFrame defines the number of frames in total
  50666. * @param from defines the initial value
  50667. * @param to defines the final value
  50668. * @param loopMode defines which loop mode you want to use (off by default)
  50669. * @param easingFunction defines the easing function to use (linear by default)
  50670. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50671. * @returns the list of animatables created for all nodes
  50672. * @example https://www.babylonjs-playground.com/#MH0VLI
  50673. */
  50674. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50675. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50676. if (!animation) {
  50677. return null;
  50678. }
  50679. var scene = node.getScene();
  50680. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50681. };
  50682. /**
  50683. * Creates a new animation, merges it with the existing animations and starts it
  50684. * @param name Name of the animation
  50685. * @param node Node which contains the scene that begins the animations
  50686. * @param targetProperty Specifies which property to animate
  50687. * @param framePerSecond The frames per second of the animation
  50688. * @param totalFrame The total number of frames
  50689. * @param from The frame at the beginning of the animation
  50690. * @param to The frame at the end of the animation
  50691. * @param loopMode Specifies the loop mode of the animation
  50692. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50693. * @param onAnimationEnd Callback to run once the animation is complete
  50694. * @returns Nullable animation
  50695. */
  50696. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50697. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50698. if (!animation) {
  50699. return null;
  50700. }
  50701. node.animations.push(animation);
  50702. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50703. };
  50704. /**
  50705. * Transition property of an host to the target Value
  50706. * @param property The property to transition
  50707. * @param targetValue The target Value of the property
  50708. * @param host The object where the property to animate belongs
  50709. * @param scene Scene used to run the animation
  50710. * @param frameRate Framerate (in frame/s) to use
  50711. * @param transition The transition type we want to use
  50712. * @param duration The duration of the animation, in milliseconds
  50713. * @param onAnimationEnd Callback trigger at the end of the animation
  50714. * @returns Nullable animation
  50715. */
  50716. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50717. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50718. if (duration <= 0) {
  50719. host[property] = targetValue;
  50720. if (onAnimationEnd) {
  50721. onAnimationEnd();
  50722. }
  50723. return null;
  50724. }
  50725. var endFrame = frameRate * (duration / 1000);
  50726. transition.setKeys([{
  50727. frame: 0,
  50728. value: host[property].clone ? host[property].clone() : host[property]
  50729. },
  50730. {
  50731. frame: endFrame,
  50732. value: targetValue
  50733. }]);
  50734. if (!host.animations) {
  50735. host.animations = [];
  50736. }
  50737. host.animations.push(transition);
  50738. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50739. animation.onAnimationEnd = onAnimationEnd;
  50740. return animation;
  50741. };
  50742. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50743. /**
  50744. * Return the array of runtime animations currently using this animation
  50745. */
  50746. get: function () {
  50747. return this._runtimeAnimations;
  50748. },
  50749. enumerable: true,
  50750. configurable: true
  50751. });
  50752. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50753. /**
  50754. * Specifies if any of the runtime animations are currently running
  50755. */
  50756. get: function () {
  50757. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50758. var runtimeAnimation = _a[_i];
  50759. if (!runtimeAnimation.isStopped) {
  50760. return true;
  50761. }
  50762. }
  50763. return false;
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. // Methods
  50769. /**
  50770. * Converts the animation to a string
  50771. * @param fullDetails support for multiple levels of logging within scene loading
  50772. * @returns String form of the animation
  50773. */
  50774. Animation.prototype.toString = function (fullDetails) {
  50775. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50776. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50777. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50778. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50779. if (fullDetails) {
  50780. ret += ", Ranges: {";
  50781. var first = true;
  50782. for (var name in this._ranges) {
  50783. if (first) {
  50784. ret += ", ";
  50785. first = false;
  50786. }
  50787. ret += name;
  50788. }
  50789. ret += "}";
  50790. }
  50791. return ret;
  50792. };
  50793. /**
  50794. * Add an event to this animation
  50795. * @param event Event to add
  50796. */
  50797. Animation.prototype.addEvent = function (event) {
  50798. this._events.push(event);
  50799. };
  50800. /**
  50801. * Remove all events found at the given frame
  50802. * @param frame The frame to remove events from
  50803. */
  50804. Animation.prototype.removeEvents = function (frame) {
  50805. for (var index = 0; index < this._events.length; index++) {
  50806. if (this._events[index].frame === frame) {
  50807. this._events.splice(index, 1);
  50808. index--;
  50809. }
  50810. }
  50811. };
  50812. /**
  50813. * Retrieves all the events from the animation
  50814. * @returns Events from the animation
  50815. */
  50816. Animation.prototype.getEvents = function () {
  50817. return this._events;
  50818. };
  50819. /**
  50820. * Creates an animation range
  50821. * @param name Name of the animation range
  50822. * @param from Starting frame of the animation range
  50823. * @param to Ending frame of the animation
  50824. */
  50825. Animation.prototype.createRange = function (name, from, to) {
  50826. // check name not already in use; could happen for bones after serialized
  50827. if (!this._ranges[name]) {
  50828. this._ranges[name] = new AnimationRange(name, from, to);
  50829. }
  50830. };
  50831. /**
  50832. * Deletes an animation range by name
  50833. * @param name Name of the animation range to delete
  50834. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50835. */
  50836. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50837. if (deleteFrames === void 0) { deleteFrames = true; }
  50838. var range = this._ranges[name];
  50839. if (!range) {
  50840. return;
  50841. }
  50842. if (deleteFrames) {
  50843. var from = range.from;
  50844. var to = range.to;
  50845. // this loop MUST go high to low for multiple splices to work
  50846. for (var key = this._keys.length - 1; key >= 0; key--) {
  50847. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50848. this._keys.splice(key, 1);
  50849. }
  50850. }
  50851. }
  50852. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50853. };
  50854. /**
  50855. * Gets the animation range by name, or null if not defined
  50856. * @param name Name of the animation range
  50857. * @returns Nullable animation range
  50858. */
  50859. Animation.prototype.getRange = function (name) {
  50860. return this._ranges[name];
  50861. };
  50862. /**
  50863. * Gets the key frames from the animation
  50864. * @returns The key frames of the animation
  50865. */
  50866. Animation.prototype.getKeys = function () {
  50867. return this._keys;
  50868. };
  50869. /**
  50870. * Gets the highest frame rate of the animation
  50871. * @returns Highest frame rate of the animation
  50872. */
  50873. Animation.prototype.getHighestFrame = function () {
  50874. var ret = 0;
  50875. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50876. if (ret < this._keys[key].frame) {
  50877. ret = this._keys[key].frame;
  50878. }
  50879. }
  50880. return ret;
  50881. };
  50882. /**
  50883. * Gets the easing function of the animation
  50884. * @returns Easing function of the animation
  50885. */
  50886. Animation.prototype.getEasingFunction = function () {
  50887. return this._easingFunction;
  50888. };
  50889. /**
  50890. * Sets the easing function of the animation
  50891. * @param easingFunction A custom mathematical formula for animation
  50892. */
  50893. Animation.prototype.setEasingFunction = function (easingFunction) {
  50894. this._easingFunction = easingFunction;
  50895. };
  50896. /**
  50897. * Interpolates a scalar linearly
  50898. * @param startValue Start value of the animation curve
  50899. * @param endValue End value of the animation curve
  50900. * @param gradient Scalar amount to interpolate
  50901. * @returns Interpolated scalar value
  50902. */
  50903. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50904. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50905. };
  50906. /**
  50907. * Interpolates a scalar cubically
  50908. * @param startValue Start value of the animation curve
  50909. * @param outTangent End tangent of the animation
  50910. * @param endValue End value of the animation curve
  50911. * @param inTangent Start tangent of the animation curve
  50912. * @param gradient Scalar amount to interpolate
  50913. * @returns Interpolated scalar value
  50914. */
  50915. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50916. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50917. };
  50918. /**
  50919. * Interpolates a quaternion using a spherical linear interpolation
  50920. * @param startValue Start value of the animation curve
  50921. * @param endValue End value of the animation curve
  50922. * @param gradient Scalar amount to interpolate
  50923. * @returns Interpolated quaternion value
  50924. */
  50925. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50926. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50927. };
  50928. /**
  50929. * Interpolates a quaternion cubically
  50930. * @param startValue Start value of the animation curve
  50931. * @param outTangent End tangent of the animation curve
  50932. * @param endValue End value of the animation curve
  50933. * @param inTangent Start tangent of the animation curve
  50934. * @param gradient Scalar amount to interpolate
  50935. * @returns Interpolated quaternion value
  50936. */
  50937. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50938. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50939. };
  50940. /**
  50941. * Interpolates a Vector3 linearl
  50942. * @param startValue Start value of the animation curve
  50943. * @param endValue End value of the animation curve
  50944. * @param gradient Scalar amount to interpolate
  50945. * @returns Interpolated scalar value
  50946. */
  50947. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50948. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50949. };
  50950. /**
  50951. * Interpolates a Vector3 cubically
  50952. * @param startValue Start value of the animation curve
  50953. * @param outTangent End tangent of the animation
  50954. * @param endValue End value of the animation curve
  50955. * @param inTangent Start tangent of the animation curve
  50956. * @param gradient Scalar amount to interpolate
  50957. * @returns InterpolatedVector3 value
  50958. */
  50959. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50960. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50961. };
  50962. /**
  50963. * Interpolates a Vector2 linearly
  50964. * @param startValue Start value of the animation curve
  50965. * @param endValue End value of the animation curve
  50966. * @param gradient Scalar amount to interpolate
  50967. * @returns Interpolated Vector2 value
  50968. */
  50969. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50970. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50971. };
  50972. /**
  50973. * Interpolates a Vector2 cubically
  50974. * @param startValue Start value of the animation curve
  50975. * @param outTangent End tangent of the animation
  50976. * @param endValue End value of the animation curve
  50977. * @param inTangent Start tangent of the animation curve
  50978. * @param gradient Scalar amount to interpolate
  50979. * @returns Interpolated Vector2 value
  50980. */
  50981. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50982. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50983. };
  50984. /**
  50985. * Interpolates a size linearly
  50986. * @param startValue Start value of the animation curve
  50987. * @param endValue End value of the animation curve
  50988. * @param gradient Scalar amount to interpolate
  50989. * @returns Interpolated Size value
  50990. */
  50991. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50992. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50993. };
  50994. /**
  50995. * Interpolates a Color3 linearly
  50996. * @param startValue Start value of the animation curve
  50997. * @param endValue End value of the animation curve
  50998. * @param gradient Scalar amount to interpolate
  50999. * @returns Interpolated Color3 value
  51000. */
  51001. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51002. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51003. };
  51004. /**
  51005. * @hidden Internal use only
  51006. */
  51007. Animation.prototype._getKeyValue = function (value) {
  51008. if (typeof value === "function") {
  51009. return value();
  51010. }
  51011. return value;
  51012. };
  51013. /**
  51014. * @hidden Internal use only
  51015. */
  51016. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51017. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51018. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51019. }
  51020. var keys = this.getKeys();
  51021. // Try to get a hash to find the right key
  51022. 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));
  51023. if (keys[startKeyIndex].frame >= currentFrame) {
  51024. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51025. startKeyIndex--;
  51026. }
  51027. }
  51028. for (var key = startKeyIndex; key < keys.length; key++) {
  51029. var endKey = keys[key + 1];
  51030. if (endKey.frame >= currentFrame) {
  51031. var startKey = keys[key];
  51032. var startValue = this._getKeyValue(startKey.value);
  51033. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51034. return startValue;
  51035. }
  51036. var endValue = this._getKeyValue(endKey.value);
  51037. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51038. var frameDelta = endKey.frame - startKey.frame;
  51039. // gradient : percent of currentFrame between the frame inf and the frame sup
  51040. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51041. // check for easingFunction and correction of gradient
  51042. var easingFunction = this.getEasingFunction();
  51043. if (easingFunction != null) {
  51044. gradient = easingFunction.ease(gradient);
  51045. }
  51046. switch (this.dataType) {
  51047. // Float
  51048. case Animation.ANIMATIONTYPE_FLOAT:
  51049. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51050. switch (loopMode) {
  51051. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51052. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51053. return floatValue;
  51054. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51055. return offsetValue * repeatCount + floatValue;
  51056. }
  51057. break;
  51058. // Quaternion
  51059. case Animation.ANIMATIONTYPE_QUATERNION:
  51060. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51061. switch (loopMode) {
  51062. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51063. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51064. return quatValue;
  51065. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51066. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51067. }
  51068. return quatValue;
  51069. // Vector3
  51070. case Animation.ANIMATIONTYPE_VECTOR3:
  51071. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51072. switch (loopMode) {
  51073. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51074. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51075. return vec3Value;
  51076. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51077. return vec3Value.add(offsetValue.scale(repeatCount));
  51078. }
  51079. // Vector2
  51080. case Animation.ANIMATIONTYPE_VECTOR2:
  51081. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51082. switch (loopMode) {
  51083. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51084. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51085. return vec2Value;
  51086. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51087. return vec2Value.add(offsetValue.scale(repeatCount));
  51088. }
  51089. // Size
  51090. case Animation.ANIMATIONTYPE_SIZE:
  51091. switch (loopMode) {
  51092. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51093. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51094. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51095. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51096. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51097. }
  51098. // Color3
  51099. case Animation.ANIMATIONTYPE_COLOR3:
  51100. switch (loopMode) {
  51101. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51102. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51103. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51104. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51105. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51106. }
  51107. // Matrix
  51108. case Animation.ANIMATIONTYPE_MATRIX:
  51109. switch (loopMode) {
  51110. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51111. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51112. if (Animation.AllowMatricesInterpolation) {
  51113. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51114. }
  51115. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51116. return startValue;
  51117. }
  51118. default:
  51119. break;
  51120. }
  51121. break;
  51122. }
  51123. }
  51124. return this._getKeyValue(keys[keys.length - 1].value);
  51125. };
  51126. /**
  51127. * Defines the function to use to interpolate matrices
  51128. * @param startValue defines the start matrix
  51129. * @param endValue defines the end matrix
  51130. * @param gradient defines the gradient between both matrices
  51131. * @param result defines an optional target matrix where to store the interpolation
  51132. * @returns the interpolated matrix
  51133. */
  51134. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51135. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51136. if (result) {
  51137. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51138. return result;
  51139. }
  51140. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51141. }
  51142. if (result) {
  51143. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51144. return result;
  51145. }
  51146. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51147. };
  51148. /**
  51149. * Makes a copy of the animation
  51150. * @returns Cloned animation
  51151. */
  51152. Animation.prototype.clone = function () {
  51153. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51154. clone.enableBlending = this.enableBlending;
  51155. clone.blendingSpeed = this.blendingSpeed;
  51156. if (this._keys) {
  51157. clone.setKeys(this._keys);
  51158. }
  51159. if (this._ranges) {
  51160. clone._ranges = {};
  51161. for (var name in this._ranges) {
  51162. var range = this._ranges[name];
  51163. if (!range) {
  51164. continue;
  51165. }
  51166. clone._ranges[name] = range.clone();
  51167. }
  51168. }
  51169. return clone;
  51170. };
  51171. /**
  51172. * Sets the key frames of the animation
  51173. * @param values The animation key frames to set
  51174. */
  51175. Animation.prototype.setKeys = function (values) {
  51176. this._keys = values.slice(0);
  51177. };
  51178. /**
  51179. * Serializes the animation to an object
  51180. * @returns Serialized object
  51181. */
  51182. Animation.prototype.serialize = function () {
  51183. var serializationObject = {};
  51184. serializationObject.name = this.name;
  51185. serializationObject.property = this.targetProperty;
  51186. serializationObject.framePerSecond = this.framePerSecond;
  51187. serializationObject.dataType = this.dataType;
  51188. serializationObject.loopBehavior = this.loopMode;
  51189. serializationObject.enableBlending = this.enableBlending;
  51190. serializationObject.blendingSpeed = this.blendingSpeed;
  51191. var dataType = this.dataType;
  51192. serializationObject.keys = [];
  51193. var keys = this.getKeys();
  51194. for (var index = 0; index < keys.length; index++) {
  51195. var animationKey = keys[index];
  51196. var key = {};
  51197. key.frame = animationKey.frame;
  51198. switch (dataType) {
  51199. case Animation.ANIMATIONTYPE_FLOAT:
  51200. key.values = [animationKey.value];
  51201. break;
  51202. case Animation.ANIMATIONTYPE_QUATERNION:
  51203. case Animation.ANIMATIONTYPE_MATRIX:
  51204. case Animation.ANIMATIONTYPE_VECTOR3:
  51205. case Animation.ANIMATIONTYPE_COLOR3:
  51206. key.values = animationKey.value.asArray();
  51207. break;
  51208. }
  51209. serializationObject.keys.push(key);
  51210. }
  51211. serializationObject.ranges = [];
  51212. for (var name in this._ranges) {
  51213. var source = this._ranges[name];
  51214. if (!source) {
  51215. continue;
  51216. }
  51217. var range = {};
  51218. range.name = name;
  51219. range.from = source.from;
  51220. range.to = source.to;
  51221. serializationObject.ranges.push(range);
  51222. }
  51223. return serializationObject;
  51224. };
  51225. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51226. /**
  51227. * Get the float animation type
  51228. */
  51229. get: function () {
  51230. return Animation._ANIMATIONTYPE_FLOAT;
  51231. },
  51232. enumerable: true,
  51233. configurable: true
  51234. });
  51235. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51236. /**
  51237. * Get the Vector3 animation type
  51238. */
  51239. get: function () {
  51240. return Animation._ANIMATIONTYPE_VECTOR3;
  51241. },
  51242. enumerable: true,
  51243. configurable: true
  51244. });
  51245. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51246. /**
  51247. * Get the Vector2 animation type
  51248. */
  51249. get: function () {
  51250. return Animation._ANIMATIONTYPE_VECTOR2;
  51251. },
  51252. enumerable: true,
  51253. configurable: true
  51254. });
  51255. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51256. /**
  51257. * Get the Size animation type
  51258. */
  51259. get: function () {
  51260. return Animation._ANIMATIONTYPE_SIZE;
  51261. },
  51262. enumerable: true,
  51263. configurable: true
  51264. });
  51265. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51266. /**
  51267. * Get the Quaternion animation type
  51268. */
  51269. get: function () {
  51270. return Animation._ANIMATIONTYPE_QUATERNION;
  51271. },
  51272. enumerable: true,
  51273. configurable: true
  51274. });
  51275. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51276. /**
  51277. * Get the Matrix animation type
  51278. */
  51279. get: function () {
  51280. return Animation._ANIMATIONTYPE_MATRIX;
  51281. },
  51282. enumerable: true,
  51283. configurable: true
  51284. });
  51285. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51286. /**
  51287. * Get the Color3 animation type
  51288. */
  51289. get: function () {
  51290. return Animation._ANIMATIONTYPE_COLOR3;
  51291. },
  51292. enumerable: true,
  51293. configurable: true
  51294. });
  51295. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51296. /**
  51297. * Get the Relative Loop Mode
  51298. */
  51299. get: function () {
  51300. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51301. },
  51302. enumerable: true,
  51303. configurable: true
  51304. });
  51305. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51306. /**
  51307. * Get the Cycle Loop Mode
  51308. */
  51309. get: function () {
  51310. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51311. },
  51312. enumerable: true,
  51313. configurable: true
  51314. });
  51315. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51316. /**
  51317. * Get the Constant Loop Mode
  51318. */
  51319. get: function () {
  51320. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51321. },
  51322. enumerable: true,
  51323. configurable: true
  51324. });
  51325. /** @hidden */
  51326. Animation._UniversalLerp = function (left, right, amount) {
  51327. var constructor = left.constructor;
  51328. if (constructor.Lerp) { // Lerp supported
  51329. return constructor.Lerp(left, right, amount);
  51330. }
  51331. else if (constructor.Slerp) { // Slerp supported
  51332. return constructor.Slerp(left, right, amount);
  51333. }
  51334. else if (left.toFixed) { // Number
  51335. return left * (1.0 - amount) + amount * right;
  51336. }
  51337. else { // Blending not supported
  51338. return right;
  51339. }
  51340. };
  51341. /**
  51342. * Parses an animation object and creates an animation
  51343. * @param parsedAnimation Parsed animation object
  51344. * @returns Animation object
  51345. */
  51346. Animation.Parse = function (parsedAnimation) {
  51347. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51348. var dataType = parsedAnimation.dataType;
  51349. var keys = [];
  51350. var data;
  51351. var index;
  51352. if (parsedAnimation.enableBlending) {
  51353. animation.enableBlending = parsedAnimation.enableBlending;
  51354. }
  51355. if (parsedAnimation.blendingSpeed) {
  51356. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51357. }
  51358. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51359. var key = parsedAnimation.keys[index];
  51360. var inTangent;
  51361. var outTangent;
  51362. switch (dataType) {
  51363. case Animation.ANIMATIONTYPE_FLOAT:
  51364. data = key.values[0];
  51365. if (key.values.length >= 1) {
  51366. inTangent = key.values[1];
  51367. }
  51368. if (key.values.length >= 2) {
  51369. outTangent = key.values[2];
  51370. }
  51371. break;
  51372. case Animation.ANIMATIONTYPE_QUATERNION:
  51373. data = BABYLON.Quaternion.FromArray(key.values);
  51374. if (key.values.length >= 8) {
  51375. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51376. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51377. inTangent = _inTangent;
  51378. }
  51379. }
  51380. if (key.values.length >= 12) {
  51381. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51382. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51383. outTangent = _outTangent;
  51384. }
  51385. }
  51386. break;
  51387. case Animation.ANIMATIONTYPE_MATRIX:
  51388. data = BABYLON.Matrix.FromArray(key.values);
  51389. break;
  51390. case Animation.ANIMATIONTYPE_COLOR3:
  51391. data = BABYLON.Color3.FromArray(key.values);
  51392. break;
  51393. case Animation.ANIMATIONTYPE_VECTOR3:
  51394. default:
  51395. data = BABYLON.Vector3.FromArray(key.values);
  51396. break;
  51397. }
  51398. var keyData = {};
  51399. keyData.frame = key.frame;
  51400. keyData.value = data;
  51401. if (inTangent != undefined) {
  51402. keyData.inTangent = inTangent;
  51403. }
  51404. if (outTangent != undefined) {
  51405. keyData.outTangent = outTangent;
  51406. }
  51407. keys.push(keyData);
  51408. }
  51409. animation.setKeys(keys);
  51410. if (parsedAnimation.ranges) {
  51411. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51412. data = parsedAnimation.ranges[index];
  51413. animation.createRange(data.name, data.from, data.to);
  51414. }
  51415. }
  51416. return animation;
  51417. };
  51418. /**
  51419. * Appends the serialized animations from the source animations
  51420. * @param source Source containing the animations
  51421. * @param destination Target to store the animations
  51422. */
  51423. Animation.AppendSerializedAnimations = function (source, destination) {
  51424. if (source.animations) {
  51425. destination.animations = [];
  51426. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51427. var animation = source.animations[animationIndex];
  51428. destination.animations.push(animation.serialize());
  51429. }
  51430. }
  51431. };
  51432. /**
  51433. * Use matrix interpolation instead of using direct key value when animating matrices
  51434. */
  51435. Animation.AllowMatricesInterpolation = false;
  51436. /**
  51437. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51438. */
  51439. Animation.AllowMatrixDecomposeForInterpolation = true;
  51440. // Statics
  51441. /**
  51442. * Float animation type
  51443. */
  51444. Animation._ANIMATIONTYPE_FLOAT = 0;
  51445. /**
  51446. * Vector3 animation type
  51447. */
  51448. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51449. /**
  51450. * Quaternion animation type
  51451. */
  51452. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51453. /**
  51454. * Matrix animation type
  51455. */
  51456. Animation._ANIMATIONTYPE_MATRIX = 3;
  51457. /**
  51458. * Color3 animation type
  51459. */
  51460. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51461. /**
  51462. * Vector2 animation type
  51463. */
  51464. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51465. /**
  51466. * Size animation type
  51467. */
  51468. Animation._ANIMATIONTYPE_SIZE = 6;
  51469. /**
  51470. * Relative Loop Mode
  51471. */
  51472. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51473. /**
  51474. * Cycle Loop Mode
  51475. */
  51476. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51477. /**
  51478. * Constant Loop Mode
  51479. */
  51480. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51481. return Animation;
  51482. }());
  51483. BABYLON.Animation = Animation;
  51484. })(BABYLON || (BABYLON = {}));
  51485. //# sourceMappingURL=babylon.animation.js.map
  51486. var BABYLON;
  51487. (function (BABYLON) {
  51488. /**
  51489. * This class defines the direct association between an animation and a target
  51490. */
  51491. var TargetedAnimation = /** @class */ (function () {
  51492. function TargetedAnimation() {
  51493. }
  51494. return TargetedAnimation;
  51495. }());
  51496. BABYLON.TargetedAnimation = TargetedAnimation;
  51497. /**
  51498. * Use this class to create coordinated animations on multiple targets
  51499. */
  51500. var AnimationGroup = /** @class */ (function () {
  51501. /**
  51502. * Instantiates a new Animation Group.
  51503. * This helps managing several animations at once.
  51504. * @see http://doc.babylonjs.com/how_to/group
  51505. * @param name Defines the name of the group
  51506. * @param scene Defines the scene the group belongs to
  51507. */
  51508. function AnimationGroup(
  51509. /** The name of the animation group */
  51510. name, scene) {
  51511. if (scene === void 0) { scene = null; }
  51512. this.name = name;
  51513. this._targetedAnimations = new Array();
  51514. this._animatables = new Array();
  51515. this._from = Number.MAX_VALUE;
  51516. this._to = -Number.MAX_VALUE;
  51517. this._speedRatio = 1;
  51518. /**
  51519. * This observable will notify when one animation have ended.
  51520. */
  51521. this.onAnimationEndObservable = new BABYLON.Observable();
  51522. /**
  51523. * This observable will notify when all animations have ended.
  51524. */
  51525. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51526. /**
  51527. * This observable will notify when all animations have paused.
  51528. */
  51529. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51531. this._scene.animationGroups.push(this);
  51532. }
  51533. Object.defineProperty(AnimationGroup.prototype, "from", {
  51534. /**
  51535. * Gets the first frame
  51536. */
  51537. get: function () {
  51538. return this._from;
  51539. },
  51540. enumerable: true,
  51541. configurable: true
  51542. });
  51543. Object.defineProperty(AnimationGroup.prototype, "to", {
  51544. /**
  51545. * Gets the last frame
  51546. */
  51547. get: function () {
  51548. return this._to;
  51549. },
  51550. enumerable: true,
  51551. configurable: true
  51552. });
  51553. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51554. /**
  51555. * Define if the animations are started
  51556. */
  51557. get: function () {
  51558. return this._isStarted;
  51559. },
  51560. enumerable: true,
  51561. configurable: true
  51562. });
  51563. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51564. /**
  51565. * Gets or sets the speed ratio to use for all animations
  51566. */
  51567. get: function () {
  51568. return this._speedRatio;
  51569. },
  51570. /**
  51571. * Gets or sets the speed ratio to use for all animations
  51572. */
  51573. set: function (value) {
  51574. if (this._speedRatio === value) {
  51575. return;
  51576. }
  51577. this._speedRatio = value;
  51578. for (var index = 0; index < this._animatables.length; index++) {
  51579. var animatable = this._animatables[index];
  51580. animatable.speedRatio = this._speedRatio;
  51581. }
  51582. },
  51583. enumerable: true,
  51584. configurable: true
  51585. });
  51586. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51587. /**
  51588. * Gets the targeted animations for this animation group
  51589. */
  51590. get: function () {
  51591. return this._targetedAnimations;
  51592. },
  51593. enumerable: true,
  51594. configurable: true
  51595. });
  51596. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51597. /**
  51598. * returning the list of animatables controlled by this animation group.
  51599. */
  51600. get: function () {
  51601. return this._animatables;
  51602. },
  51603. enumerable: true,
  51604. configurable: true
  51605. });
  51606. /**
  51607. * Add an animation (with its target) in the group
  51608. * @param animation defines the animation we want to add
  51609. * @param target defines the target of the animation
  51610. * @returns the {BABYLON.TargetedAnimation} object
  51611. */
  51612. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51613. var targetedAnimation = {
  51614. animation: animation,
  51615. target: target
  51616. };
  51617. var keys = animation.getKeys();
  51618. if (this._from > keys[0].frame) {
  51619. this._from = keys[0].frame;
  51620. }
  51621. if (this._to < keys[keys.length - 1].frame) {
  51622. this._to = keys[keys.length - 1].frame;
  51623. }
  51624. this._targetedAnimations.push(targetedAnimation);
  51625. return targetedAnimation;
  51626. };
  51627. /**
  51628. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51629. * It can add constant keys at begin or end
  51630. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51631. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51632. * @returns the animation group
  51633. */
  51634. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51635. if (beginFrame === void 0) { beginFrame = null; }
  51636. if (endFrame === void 0) { endFrame = null; }
  51637. if (beginFrame == null)
  51638. beginFrame = this._from;
  51639. if (endFrame == null)
  51640. endFrame = this._to;
  51641. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51642. var targetedAnimation = this._targetedAnimations[index];
  51643. var keys = targetedAnimation.animation.getKeys();
  51644. var startKey = keys[0];
  51645. var endKey = keys[keys.length - 1];
  51646. if (startKey.frame > beginFrame) {
  51647. var newKey = {
  51648. frame: beginFrame,
  51649. value: startKey.value,
  51650. inTangent: startKey.inTangent,
  51651. outTangent: startKey.outTangent,
  51652. interpolation: startKey.interpolation
  51653. };
  51654. keys.splice(0, 0, newKey);
  51655. }
  51656. if (endKey.frame < endFrame) {
  51657. var newKey = {
  51658. frame: endFrame,
  51659. value: endKey.value,
  51660. inTangent: endKey.outTangent,
  51661. outTangent: endKey.outTangent,
  51662. interpolation: endKey.interpolation
  51663. };
  51664. keys.push(newKey);
  51665. }
  51666. }
  51667. this._from = beginFrame;
  51668. this._to = endFrame;
  51669. return this;
  51670. };
  51671. /**
  51672. * Start all animations on given targets
  51673. * @param loop defines if animations must loop
  51674. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51675. * @param from defines the from key (optional)
  51676. * @param to defines the to key (optional)
  51677. * @returns the current animation group
  51678. */
  51679. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51680. var _this = this;
  51681. if (loop === void 0) { loop = false; }
  51682. if (speedRatio === void 0) { speedRatio = 1; }
  51683. if (this._isStarted || this._targetedAnimations.length === 0) {
  51684. return this;
  51685. }
  51686. var _loop_1 = function (targetedAnimation) {
  51687. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51688. animatable.onAnimationEnd = function () {
  51689. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51690. _this._checkAnimationGroupEnded(animatable);
  51691. };
  51692. this_1._animatables.push(animatable);
  51693. };
  51694. var this_1 = this;
  51695. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51696. var targetedAnimation = _a[_i];
  51697. _loop_1(targetedAnimation);
  51698. }
  51699. this._speedRatio = speedRatio;
  51700. this._isStarted = true;
  51701. return this;
  51702. };
  51703. /**
  51704. * Pause all animations
  51705. * @returns the animation group
  51706. */
  51707. AnimationGroup.prototype.pause = function () {
  51708. if (!this._isStarted) {
  51709. return this;
  51710. }
  51711. for (var index = 0; index < this._animatables.length; index++) {
  51712. var animatable = this._animatables[index];
  51713. animatable.pause();
  51714. }
  51715. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51716. return this;
  51717. };
  51718. /**
  51719. * Play all animations to initial state
  51720. * This function will start() the animations if they were not started or will restart() them if they were paused
  51721. * @param loop defines if animations must loop
  51722. * @returns the animation group
  51723. */
  51724. AnimationGroup.prototype.play = function (loop) {
  51725. // only if all animatables are ready and exist
  51726. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51727. if (loop !== undefined) {
  51728. for (var index = 0; index < this._animatables.length; index++) {
  51729. var animatable = this._animatables[index];
  51730. animatable.loopAnimation = loop;
  51731. }
  51732. }
  51733. this.restart();
  51734. }
  51735. else {
  51736. this.stop();
  51737. this.start(loop, this._speedRatio);
  51738. }
  51739. return this;
  51740. };
  51741. /**
  51742. * Reset all animations to initial state
  51743. * @returns the animation group
  51744. */
  51745. AnimationGroup.prototype.reset = function () {
  51746. if (!this._isStarted) {
  51747. return this;
  51748. }
  51749. for (var index = 0; index < this._animatables.length; index++) {
  51750. var animatable = this._animatables[index];
  51751. animatable.reset();
  51752. }
  51753. return this;
  51754. };
  51755. /**
  51756. * Restart animations from key 0
  51757. * @returns the animation group
  51758. */
  51759. AnimationGroup.prototype.restart = function () {
  51760. if (!this._isStarted) {
  51761. return this;
  51762. }
  51763. for (var index = 0; index < this._animatables.length; index++) {
  51764. var animatable = this._animatables[index];
  51765. animatable.restart();
  51766. }
  51767. return this;
  51768. };
  51769. /**
  51770. * Stop all animations
  51771. * @returns the animation group
  51772. */
  51773. AnimationGroup.prototype.stop = function () {
  51774. if (!this._isStarted) {
  51775. return this;
  51776. }
  51777. var list = this._animatables.slice();
  51778. for (var index = 0; index < list.length; index++) {
  51779. list[index].stop();
  51780. }
  51781. this._isStarted = false;
  51782. return this;
  51783. };
  51784. /**
  51785. * Set animation weight for all animatables
  51786. * @param weight defines the weight to use
  51787. * @return the animationGroup
  51788. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51789. */
  51790. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51791. for (var index = 0; index < this._animatables.length; index++) {
  51792. var animatable = this._animatables[index];
  51793. animatable.weight = weight;
  51794. }
  51795. return this;
  51796. };
  51797. /**
  51798. * Synchronize and normalize all animatables with a source animatable
  51799. * @param root defines the root animatable to synchronize with
  51800. * @return the animationGroup
  51801. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51802. */
  51803. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51804. for (var index = 0; index < this._animatables.length; index++) {
  51805. var animatable = this._animatables[index];
  51806. animatable.syncWith(root);
  51807. }
  51808. return this;
  51809. };
  51810. /**
  51811. * Goes to a specific frame in this animation group
  51812. * @param frame the frame number to go to
  51813. * @return the animationGroup
  51814. */
  51815. AnimationGroup.prototype.goToFrame = function (frame) {
  51816. if (!this._isStarted) {
  51817. return this;
  51818. }
  51819. for (var index = 0; index < this._animatables.length; index++) {
  51820. var animatable = this._animatables[index];
  51821. animatable.goToFrame(frame);
  51822. }
  51823. return this;
  51824. };
  51825. /**
  51826. * Dispose all associated resources
  51827. */
  51828. AnimationGroup.prototype.dispose = function () {
  51829. this._targetedAnimations = [];
  51830. this._animatables = [];
  51831. var index = this._scene.animationGroups.indexOf(this);
  51832. if (index > -1) {
  51833. this._scene.animationGroups.splice(index, 1);
  51834. }
  51835. };
  51836. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51837. // animatable should be taken out of the array
  51838. var idx = this._animatables.indexOf(animatable);
  51839. if (idx > -1) {
  51840. this._animatables.splice(idx, 1);
  51841. }
  51842. // all animatables were removed? animation group ended!
  51843. if (this._animatables.length === 0) {
  51844. this._isStarted = false;
  51845. this.onAnimationGroupEndObservable.notifyObservers(this);
  51846. }
  51847. };
  51848. // Statics
  51849. /**
  51850. * Returns a new AnimationGroup object parsed from the source provided.
  51851. * @param parsedAnimationGroup defines the source
  51852. * @param scene defines the scene that will receive the animationGroup
  51853. * @returns a new AnimationGroup
  51854. */
  51855. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51856. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51857. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51858. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51859. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51860. var id = targetedAnimation.targetId;
  51861. var targetNode = scene.getNodeByID(id);
  51862. if (targetNode != null)
  51863. animationGroup.addTargetedAnimation(animation, targetNode);
  51864. }
  51865. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51866. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51867. return animationGroup;
  51868. };
  51869. /**
  51870. * Returns the string "AnimationGroup"
  51871. * @returns "AnimationGroup"
  51872. */
  51873. AnimationGroup.prototype.getClassName = function () {
  51874. return "AnimationGroup";
  51875. };
  51876. /**
  51877. * Creates a detailled string about the object
  51878. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51879. * @returns a string representing the object
  51880. */
  51881. AnimationGroup.prototype.toString = function (fullDetails) {
  51882. var ret = "Name: " + this.name;
  51883. ret += ", type: " + this.getClassName();
  51884. if (fullDetails) {
  51885. ret += ", from: " + this._from;
  51886. ret += ", to: " + this._to;
  51887. ret += ", isStarted: " + this._isStarted;
  51888. ret += ", speedRatio: " + this._speedRatio;
  51889. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51890. ret += ", animatables length: " + this._animatables;
  51891. }
  51892. return ret;
  51893. };
  51894. return AnimationGroup;
  51895. }());
  51896. BABYLON.AnimationGroup = AnimationGroup;
  51897. })(BABYLON || (BABYLON = {}));
  51898. //# sourceMappingURL=babylon.animationGroup.js.map
  51899. var BABYLON;
  51900. (function (BABYLON) {
  51901. // Static values to help the garbage collector
  51902. // Quaternion
  51903. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51904. // Vector3
  51905. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51906. // Vector2
  51907. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51908. // Size
  51909. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51910. // Color3
  51911. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51912. /**
  51913. * Defines a runtime animation
  51914. */
  51915. var RuntimeAnimation = /** @class */ (function () {
  51916. /**
  51917. * Create a new RuntimeAnimation object
  51918. * @param target defines the target of the animation
  51919. * @param animation defines the source animation object
  51920. * @param scene defines the hosting scene
  51921. * @param host defines the initiating Animatable
  51922. */
  51923. function RuntimeAnimation(target, animation, scene, host) {
  51924. var _this = this;
  51925. this._events = new Array();
  51926. /**
  51927. * The current frame of the runtime animation
  51928. */
  51929. this._currentFrame = 0;
  51930. /**
  51931. * The original value of the runtime animation
  51932. */
  51933. this._originalValue = new Array();
  51934. /**
  51935. * The offsets cache of the runtime animation
  51936. */
  51937. this._offsetsCache = {};
  51938. /**
  51939. * The high limits cache of the runtime animation
  51940. */
  51941. this._highLimitsCache = {};
  51942. /**
  51943. * Specifies if the runtime animation has been stopped
  51944. */
  51945. this._stopped = false;
  51946. /**
  51947. * The blending factor of the runtime animation
  51948. */
  51949. this._blendingFactor = 0;
  51950. /**
  51951. * The target path of the runtime animation
  51952. */
  51953. this._targetPath = "";
  51954. /**
  51955. * The weight of the runtime animation
  51956. */
  51957. this._weight = 1.0;
  51958. /**
  51959. * The ratio offset of the runtime animation
  51960. */
  51961. this._ratioOffset = 0;
  51962. /**
  51963. * The previous delay of the runtime animation
  51964. */
  51965. this._previousDelay = 0;
  51966. /**
  51967. * The previous ratio of the runtime animation
  51968. */
  51969. this._previousRatio = 0;
  51970. this._animation = animation;
  51971. this._target = target;
  51972. this._scene = scene;
  51973. this._host = host;
  51974. animation._runtimeAnimations.push(this);
  51975. // Cloning events locally
  51976. var events = animation.getEvents();
  51977. if (events && events.length > 0) {
  51978. events.forEach(function (e) {
  51979. _this._events.push(e._clone());
  51980. });
  51981. }
  51982. }
  51983. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51984. /**
  51985. * Gets the current frame of the runtime animation
  51986. */
  51987. get: function () {
  51988. return this._currentFrame;
  51989. },
  51990. enumerable: true,
  51991. configurable: true
  51992. });
  51993. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51994. /**
  51995. * Gets the weight of the runtime animation
  51996. */
  51997. get: function () {
  51998. return this._weight;
  51999. },
  52000. enumerable: true,
  52001. configurable: true
  52002. });
  52003. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52004. /**
  52005. * Gets the current value of the runtime animation
  52006. */
  52007. get: function () {
  52008. return this._currentValue;
  52009. },
  52010. enumerable: true,
  52011. configurable: true
  52012. });
  52013. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52014. /**
  52015. * Gets the target path of the runtime animation
  52016. */
  52017. get: function () {
  52018. return this._targetPath;
  52019. },
  52020. enumerable: true,
  52021. configurable: true
  52022. });
  52023. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52024. /**
  52025. * Gets the actual target of the runtime animation
  52026. */
  52027. get: function () {
  52028. return this._activeTarget;
  52029. },
  52030. enumerable: true,
  52031. configurable: true
  52032. });
  52033. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52034. /**
  52035. * Gets the animation from the runtime animation
  52036. */
  52037. get: function () {
  52038. return this._animation;
  52039. },
  52040. enumerable: true,
  52041. configurable: true
  52042. });
  52043. /**
  52044. * Resets the runtime animation to the beginning
  52045. * @param restoreOriginal defines whether to restore the target property to the original value
  52046. */
  52047. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52048. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52049. if (restoreOriginal) {
  52050. if (this._target instanceof Array) {
  52051. var index = 0;
  52052. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52053. var target = _a[_i];
  52054. if (this._originalValue[index] !== undefined) {
  52055. this._setValue(target, this._originalValue[index], -1);
  52056. }
  52057. index++;
  52058. }
  52059. }
  52060. else {
  52061. if (this._originalValue[0] !== undefined) {
  52062. this._setValue(this._target, this._originalValue[0], -1);
  52063. }
  52064. }
  52065. }
  52066. this._offsetsCache = {};
  52067. this._highLimitsCache = {};
  52068. this._currentFrame = 0;
  52069. this._blendingFactor = 0;
  52070. this._originalValue = new Array();
  52071. // Events
  52072. for (var index = 0; index < this._events.length; index++) {
  52073. this._events[index].isDone = false;
  52074. }
  52075. };
  52076. /**
  52077. * Specifies if the runtime animation is stopped
  52078. * @returns Boolean specifying if the runtime animation is stopped
  52079. */
  52080. RuntimeAnimation.prototype.isStopped = function () {
  52081. return this._stopped;
  52082. };
  52083. /**
  52084. * Disposes of the runtime animation
  52085. */
  52086. RuntimeAnimation.prototype.dispose = function () {
  52087. var index = this._animation.runtimeAnimations.indexOf(this);
  52088. if (index > -1) {
  52089. this._animation.runtimeAnimations.splice(index, 1);
  52090. }
  52091. };
  52092. /**
  52093. * Interpolates the animation from the current frame
  52094. * @param currentFrame The frame to interpolate the animation to
  52095. * @param repeatCount The number of times that the animation should loop
  52096. * @param loopMode The type of looping mode to use
  52097. * @param offsetValue Animation offset value
  52098. * @param highLimitValue The high limit value
  52099. * @returns The interpolated value
  52100. */
  52101. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52102. this._currentFrame = currentFrame;
  52103. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52104. this._workValue = BABYLON.Matrix.Zero();
  52105. }
  52106. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52107. };
  52108. /**
  52109. * Apply the interpolated value to the target
  52110. * @param currentValue defines the value computed by the animation
  52111. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52112. */
  52113. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52114. if (weight === void 0) { weight = 1.0; }
  52115. if (this._target instanceof Array) {
  52116. var index = 0;
  52117. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52118. var target = _a[_i];
  52119. this._setValue(target, currentValue, weight, index);
  52120. index++;
  52121. }
  52122. }
  52123. else {
  52124. this._setValue(this._target, currentValue, weight);
  52125. }
  52126. };
  52127. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52128. if (targetIndex === void 0) { targetIndex = 0; }
  52129. // Set value
  52130. var path;
  52131. var destination;
  52132. var targetPropertyPath = this._animation.targetPropertyPath;
  52133. if (targetPropertyPath.length > 1) {
  52134. var property = target[targetPropertyPath[0]];
  52135. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52136. property = property[targetPropertyPath[index]];
  52137. }
  52138. path = targetPropertyPath[targetPropertyPath.length - 1];
  52139. destination = property;
  52140. }
  52141. else {
  52142. path = targetPropertyPath[0];
  52143. destination = target;
  52144. }
  52145. this._targetPath = path;
  52146. this._activeTarget = destination;
  52147. this._weight = weight;
  52148. if (this._originalValue[targetIndex] === undefined) {
  52149. var originalValue = void 0;
  52150. if (destination.getRestPose && path === "_matrix") { // For bones
  52151. originalValue = destination.getRestPose();
  52152. }
  52153. else {
  52154. originalValue = destination[path];
  52155. }
  52156. if (originalValue && originalValue.clone) {
  52157. this._originalValue[targetIndex] = originalValue.clone();
  52158. }
  52159. else {
  52160. this._originalValue[targetIndex] = originalValue;
  52161. }
  52162. }
  52163. // Blending
  52164. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52165. if (enableBlending && this._blendingFactor <= 1.0) {
  52166. if (!this._originalBlendValue) {
  52167. var originalValue = destination[path];
  52168. if (originalValue.clone) {
  52169. this._originalBlendValue = originalValue.clone();
  52170. }
  52171. else {
  52172. this._originalBlendValue = originalValue;
  52173. }
  52174. }
  52175. if (this._originalBlendValue.m) { // Matrix
  52176. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52177. if (this._currentValue) {
  52178. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52179. }
  52180. else {
  52181. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52182. }
  52183. }
  52184. else {
  52185. if (this._currentValue) {
  52186. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52187. }
  52188. else {
  52189. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52190. }
  52191. }
  52192. }
  52193. else {
  52194. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52195. }
  52196. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52197. this._blendingFactor += blendingSpeed;
  52198. }
  52199. else {
  52200. this._currentValue = currentValue;
  52201. }
  52202. if (weight !== -1.0) {
  52203. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52204. }
  52205. else {
  52206. destination[path] = this._currentValue;
  52207. }
  52208. if (target.markAsDirty) {
  52209. target.markAsDirty(this._animation.targetProperty);
  52210. }
  52211. };
  52212. /**
  52213. * Gets the loop pmode of the runtime animation
  52214. * @returns Loop Mode
  52215. */
  52216. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52217. if (this._target && this._target.animationPropertiesOverride) {
  52218. return this._target.animationPropertiesOverride.loopMode;
  52219. }
  52220. return this._animation.loopMode;
  52221. };
  52222. /**
  52223. * Move the current animation to a given frame
  52224. * @param frame defines the frame to move to
  52225. */
  52226. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52227. var keys = this._animation.getKeys();
  52228. if (frame < keys[0].frame) {
  52229. frame = keys[0].frame;
  52230. }
  52231. else if (frame > keys[keys.length - 1].frame) {
  52232. frame = keys[keys.length - 1].frame;
  52233. }
  52234. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52235. this.setValue(currentValue, -1);
  52236. };
  52237. /**
  52238. * @hidden Internal use only
  52239. */
  52240. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52241. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52242. this._ratioOffset = this._previousRatio - newRatio;
  52243. };
  52244. /**
  52245. * Execute the current animation
  52246. * @param delay defines the delay to add to the current frame
  52247. * @param from defines the lower bound of the animation range
  52248. * @param to defines the upper bound of the animation range
  52249. * @param loop defines if the current animation must loop
  52250. * @param speedRatio defines the current speed ratio
  52251. * @param weight defines the weight of the animation (default is -1 so no weight)
  52252. * @returns a boolean indicating if the animation is running
  52253. */
  52254. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52255. if (weight === void 0) { weight = -1.0; }
  52256. var targetPropertyPath = this._animation.targetPropertyPath;
  52257. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52258. this._stopped = true;
  52259. return false;
  52260. }
  52261. var returnValue = true;
  52262. var keys = this._animation.getKeys();
  52263. // Adding a start key at frame 0 if missing
  52264. if (keys[0].frame !== 0) {
  52265. var newKey = { frame: 0, value: keys[0].value };
  52266. keys.splice(0, 0, newKey);
  52267. }
  52268. // Adding a duplicate key when there is only one key at frame zero
  52269. else if (keys.length === 1) {
  52270. var newKey = { frame: 0.001, value: keys[0].value };
  52271. keys.push(newKey);
  52272. }
  52273. // Check limits
  52274. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52275. from = keys[0].frame;
  52276. }
  52277. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52278. to = keys[keys.length - 1].frame;
  52279. }
  52280. //to and from cannot be the same key
  52281. if (from === to) {
  52282. if (from > keys[0].frame) {
  52283. from--;
  52284. }
  52285. else if (to < keys[keys.length - 1].frame) {
  52286. to++;
  52287. }
  52288. }
  52289. // Compute ratio
  52290. var range = to - from;
  52291. var offsetValue;
  52292. // ratio represents the frame delta between from and to
  52293. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52294. var highLimitValue = 0;
  52295. this._previousDelay = delay;
  52296. this._previousRatio = ratio;
  52297. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52298. returnValue = false;
  52299. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52300. }
  52301. else {
  52302. // Get max value if required
  52303. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52304. var keyOffset = to.toString() + from.toString();
  52305. if (!this._offsetsCache[keyOffset]) {
  52306. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52307. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52308. switch (this._animation.dataType) {
  52309. // Float
  52310. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52311. this._offsetsCache[keyOffset] = toValue - fromValue;
  52312. break;
  52313. // Quaternion
  52314. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52315. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52316. break;
  52317. // Vector3
  52318. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52319. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52320. // Vector2
  52321. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52322. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52323. // Size
  52324. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52325. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52326. // Color3
  52327. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52328. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52329. default:
  52330. break;
  52331. }
  52332. this._highLimitsCache[keyOffset] = toValue;
  52333. }
  52334. highLimitValue = this._highLimitsCache[keyOffset];
  52335. offsetValue = this._offsetsCache[keyOffset];
  52336. }
  52337. }
  52338. if (offsetValue === undefined) {
  52339. switch (this._animation.dataType) {
  52340. // Float
  52341. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52342. offsetValue = 0;
  52343. break;
  52344. // Quaternion
  52345. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52346. offsetValue = _staticOffsetValueQuaternion;
  52347. break;
  52348. // Vector3
  52349. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52350. offsetValue = _staticOffsetValueVector3;
  52351. break;
  52352. // Vector2
  52353. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52354. offsetValue = _staticOffsetValueVector2;
  52355. break;
  52356. // Size
  52357. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52358. offsetValue = _staticOffsetValueSize;
  52359. break;
  52360. // Color3
  52361. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52362. offsetValue = _staticOffsetValueColor3;
  52363. }
  52364. }
  52365. // Compute value
  52366. var repeatCount = (ratio / range) >> 0;
  52367. var currentFrame = returnValue ? from + ratio % range : to;
  52368. // Need to normalize?
  52369. if (this._host && this._host.syncRoot) {
  52370. var syncRoot = this._host.syncRoot;
  52371. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52372. currentFrame = from + (to - from) * hostNormalizedFrame;
  52373. }
  52374. // Reset events if looping
  52375. var events = this._events;
  52376. if (range > 0 && this.currentFrame > currentFrame ||
  52377. range < 0 && this.currentFrame < currentFrame) {
  52378. // Need to reset animation events
  52379. for (var index = 0; index < events.length; index++) {
  52380. if (!events[index].onlyOnce) {
  52381. // reset event, the animation is looping
  52382. events[index].isDone = false;
  52383. }
  52384. }
  52385. }
  52386. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52387. // Set value
  52388. this.setValue(currentValue, weight);
  52389. // Check events
  52390. for (var index = 0; index < events.length; index++) {
  52391. // Make sure current frame has passed event frame and that event frame is within the current range
  52392. // Also, handle both forward and reverse animations
  52393. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52394. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52395. var event = events[index];
  52396. if (!event.isDone) {
  52397. // If event should be done only once, remove it.
  52398. if (event.onlyOnce) {
  52399. events.splice(index, 1);
  52400. index--;
  52401. }
  52402. event.isDone = true;
  52403. event.action(currentFrame);
  52404. } // Don't do anything if the event has already be done.
  52405. }
  52406. }
  52407. if (!returnValue) {
  52408. this._stopped = true;
  52409. }
  52410. return returnValue;
  52411. };
  52412. return RuntimeAnimation;
  52413. }());
  52414. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52415. })(BABYLON || (BABYLON = {}));
  52416. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52417. var BABYLON;
  52418. (function (BABYLON) {
  52419. /**
  52420. * Class used to store an actual running animation
  52421. */
  52422. var Animatable = /** @class */ (function () {
  52423. /**
  52424. * Creates a new Animatable
  52425. * @param scene defines the hosting scene
  52426. * @param target defines the target object
  52427. * @param fromFrame defines the starting frame number (default is 0)
  52428. * @param toFrame defines the ending frame number (default is 100)
  52429. * @param loopAnimation defines if the animation must loop (default is false)
  52430. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52431. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52432. * @param animations defines a group of animation to add to the new Animatable
  52433. */
  52434. function Animatable(scene,
  52435. /** defines the target object */
  52436. target,
  52437. /** defines the starting frame number (default is 0) */
  52438. fromFrame,
  52439. /** defines the ending frame number (default is 100) */
  52440. toFrame,
  52441. /** defines if the animation must loop (default is false) */
  52442. loopAnimation, speedRatio,
  52443. /** defines a callback to call when animation ends if it is not looping */
  52444. onAnimationEnd, animations) {
  52445. if (fromFrame === void 0) { fromFrame = 0; }
  52446. if (toFrame === void 0) { toFrame = 100; }
  52447. if (loopAnimation === void 0) { loopAnimation = false; }
  52448. if (speedRatio === void 0) { speedRatio = 1.0; }
  52449. this.target = target;
  52450. this.fromFrame = fromFrame;
  52451. this.toFrame = toFrame;
  52452. this.loopAnimation = loopAnimation;
  52453. this.onAnimationEnd = onAnimationEnd;
  52454. this._localDelayOffset = null;
  52455. this._pausedDelay = null;
  52456. this._runtimeAnimations = new Array();
  52457. this._paused = false;
  52458. this._speedRatio = 1;
  52459. this._weight = -1.0;
  52460. /**
  52461. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52462. * This will only apply for non looping animation (default is true)
  52463. */
  52464. this.disposeOnEnd = true;
  52465. /**
  52466. * Gets a boolean indicating if the animation has started
  52467. */
  52468. this.animationStarted = false;
  52469. /**
  52470. * Observer raised when the animation ends
  52471. */
  52472. this.onAnimationEndObservable = new BABYLON.Observable();
  52473. this._scene = scene;
  52474. if (animations) {
  52475. this.appendAnimations(target, animations);
  52476. }
  52477. this._speedRatio = speedRatio;
  52478. scene._activeAnimatables.push(this);
  52479. }
  52480. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52481. /**
  52482. * Gets the root Animatable used to synchronize and normalize animations
  52483. */
  52484. get: function () {
  52485. return this._syncRoot;
  52486. },
  52487. enumerable: true,
  52488. configurable: true
  52489. });
  52490. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52491. /**
  52492. * Gets the current frame of the first RuntimeAnimation
  52493. * Used to synchronize Animatables
  52494. */
  52495. get: function () {
  52496. if (this._runtimeAnimations.length === 0) {
  52497. return 0;
  52498. }
  52499. return this._runtimeAnimations[0].currentFrame;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. Object.defineProperty(Animatable.prototype, "weight", {
  52505. /**
  52506. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52507. */
  52508. get: function () {
  52509. return this._weight;
  52510. },
  52511. set: function (value) {
  52512. if (value === -1) { // -1 is ok and means no weight
  52513. this._weight = -1;
  52514. return;
  52515. }
  52516. // Else weight must be in [0, 1] range
  52517. this._weight = Math.min(Math.max(value, 0), 1.0);
  52518. },
  52519. enumerable: true,
  52520. configurable: true
  52521. });
  52522. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52523. /**
  52524. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52525. */
  52526. get: function () {
  52527. return this._speedRatio;
  52528. },
  52529. set: function (value) {
  52530. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52531. var animation = this._runtimeAnimations[index];
  52532. animation._prepareForSpeedRatioChange(value);
  52533. }
  52534. this._speedRatio = value;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. // Methods
  52540. /**
  52541. * Synchronize and normalize current Animatable with a source Animatable
  52542. * This is useful when using animation weights and when animations are not of the same length
  52543. * @param root defines the root Animatable to synchronize with
  52544. * @returns the current Animatable
  52545. */
  52546. Animatable.prototype.syncWith = function (root) {
  52547. this._syncRoot = root;
  52548. if (root) {
  52549. // Make sure this animatable will animate after the root
  52550. var index = this._scene._activeAnimatables.indexOf(this);
  52551. if (index > -1) {
  52552. this._scene._activeAnimatables.splice(index, 1);
  52553. this._scene._activeAnimatables.push(this);
  52554. }
  52555. }
  52556. return this;
  52557. };
  52558. /**
  52559. * Gets the list of runtime animations
  52560. * @returns an array of RuntimeAnimation
  52561. */
  52562. Animatable.prototype.getAnimations = function () {
  52563. return this._runtimeAnimations;
  52564. };
  52565. /**
  52566. * Adds more animations to the current animatable
  52567. * @param target defines the target of the animations
  52568. * @param animations defines the new animations to add
  52569. */
  52570. Animatable.prototype.appendAnimations = function (target, animations) {
  52571. for (var index = 0; index < animations.length; index++) {
  52572. var animation = animations[index];
  52573. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52574. }
  52575. };
  52576. /**
  52577. * Gets the source animation for a specific property
  52578. * @param property defines the propertyu to look for
  52579. * @returns null or the source animation for the given property
  52580. */
  52581. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52582. var runtimeAnimations = this._runtimeAnimations;
  52583. for (var index = 0; index < runtimeAnimations.length; index++) {
  52584. if (runtimeAnimations[index].animation.targetProperty === property) {
  52585. return runtimeAnimations[index].animation;
  52586. }
  52587. }
  52588. return null;
  52589. };
  52590. /**
  52591. * Gets the runtime animation for a specific property
  52592. * @param property defines the propertyu to look for
  52593. * @returns null or the runtime animation for the given property
  52594. */
  52595. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52596. var runtimeAnimations = this._runtimeAnimations;
  52597. for (var index = 0; index < runtimeAnimations.length; index++) {
  52598. if (runtimeAnimations[index].animation.targetProperty === property) {
  52599. return runtimeAnimations[index];
  52600. }
  52601. }
  52602. return null;
  52603. };
  52604. /**
  52605. * Resets the animatable to its original state
  52606. */
  52607. Animatable.prototype.reset = function () {
  52608. var runtimeAnimations = this._runtimeAnimations;
  52609. for (var index = 0; index < runtimeAnimations.length; index++) {
  52610. runtimeAnimations[index].reset(true);
  52611. }
  52612. this._localDelayOffset = null;
  52613. this._pausedDelay = null;
  52614. };
  52615. /**
  52616. * Allows the animatable to blend with current running animations
  52617. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52618. * @param blendingSpeed defines the blending speed to use
  52619. */
  52620. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52621. var runtimeAnimations = this._runtimeAnimations;
  52622. for (var index = 0; index < runtimeAnimations.length; index++) {
  52623. runtimeAnimations[index].animation.enableBlending = true;
  52624. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52625. }
  52626. };
  52627. /**
  52628. * Disable animation blending
  52629. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52630. */
  52631. Animatable.prototype.disableBlending = function () {
  52632. var runtimeAnimations = this._runtimeAnimations;
  52633. for (var index = 0; index < runtimeAnimations.length; index++) {
  52634. runtimeAnimations[index].animation.enableBlending = false;
  52635. }
  52636. };
  52637. /**
  52638. * Jump directly to a given frame
  52639. * @param frame defines the frame to jump to
  52640. */
  52641. Animatable.prototype.goToFrame = function (frame) {
  52642. var runtimeAnimations = this._runtimeAnimations;
  52643. if (runtimeAnimations[0]) {
  52644. var fps = runtimeAnimations[0].animation.framePerSecond;
  52645. var currentFrame = runtimeAnimations[0].currentFrame;
  52646. var adjustTime = frame - currentFrame;
  52647. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52648. if (this._localDelayOffset === null) {
  52649. this._localDelayOffset = 0;
  52650. }
  52651. this._localDelayOffset -= delay;
  52652. }
  52653. for (var index = 0; index < runtimeAnimations.length; index++) {
  52654. runtimeAnimations[index].goToFrame(frame);
  52655. }
  52656. };
  52657. /**
  52658. * Pause the animation
  52659. */
  52660. Animatable.prototype.pause = function () {
  52661. if (this._paused) {
  52662. return;
  52663. }
  52664. this._paused = true;
  52665. };
  52666. /**
  52667. * Restart the animation
  52668. */
  52669. Animatable.prototype.restart = function () {
  52670. this._paused = false;
  52671. };
  52672. Animatable.prototype._raiseOnAnimationEnd = function () {
  52673. if (this.onAnimationEnd) {
  52674. this.onAnimationEnd();
  52675. }
  52676. this.onAnimationEndObservable.notifyObservers(this);
  52677. };
  52678. /**
  52679. * Stop and delete the current animation
  52680. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52681. * @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)
  52682. */
  52683. Animatable.prototype.stop = function (animationName, targetMask) {
  52684. if (animationName || targetMask) {
  52685. var idx = this._scene._activeAnimatables.indexOf(this);
  52686. if (idx > -1) {
  52687. var runtimeAnimations = this._runtimeAnimations;
  52688. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52689. var runtimeAnimation = runtimeAnimations[index];
  52690. if (animationName && runtimeAnimation.animation.name != animationName) {
  52691. continue;
  52692. }
  52693. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52694. continue;
  52695. }
  52696. runtimeAnimation.dispose();
  52697. runtimeAnimations.splice(index, 1);
  52698. }
  52699. if (runtimeAnimations.length == 0) {
  52700. this._scene._activeAnimatables.splice(idx, 1);
  52701. this._raiseOnAnimationEnd();
  52702. }
  52703. }
  52704. }
  52705. else {
  52706. var index = this._scene._activeAnimatables.indexOf(this);
  52707. if (index > -1) {
  52708. this._scene._activeAnimatables.splice(index, 1);
  52709. var runtimeAnimations = this._runtimeAnimations;
  52710. for (var index = 0; index < runtimeAnimations.length; index++) {
  52711. runtimeAnimations[index].dispose();
  52712. }
  52713. this._raiseOnAnimationEnd();
  52714. }
  52715. }
  52716. };
  52717. /**
  52718. * Wait asynchronously for the animation to end
  52719. * @returns a promise which will be fullfilled when the animation ends
  52720. */
  52721. Animatable.prototype.waitAsync = function () {
  52722. var _this = this;
  52723. return new Promise(function (resolve, reject) {
  52724. _this.onAnimationEndObservable.add(function () {
  52725. resolve(_this);
  52726. }, undefined, undefined, _this, true);
  52727. });
  52728. };
  52729. /** @hidden */
  52730. Animatable.prototype._animate = function (delay) {
  52731. if (this._paused) {
  52732. this.animationStarted = false;
  52733. if (this._pausedDelay === null) {
  52734. this._pausedDelay = delay;
  52735. }
  52736. return true;
  52737. }
  52738. if (this._localDelayOffset === null) {
  52739. this._localDelayOffset = delay;
  52740. this._pausedDelay = null;
  52741. }
  52742. else if (this._pausedDelay !== null) {
  52743. this._localDelayOffset += delay - this._pausedDelay;
  52744. this._pausedDelay = null;
  52745. }
  52746. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52747. return true;
  52748. }
  52749. // Animating
  52750. var running = false;
  52751. var runtimeAnimations = this._runtimeAnimations;
  52752. var index;
  52753. for (index = 0; index < runtimeAnimations.length; index++) {
  52754. var animation = runtimeAnimations[index];
  52755. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52756. running = running || isRunning;
  52757. }
  52758. this.animationStarted = running;
  52759. if (!running) {
  52760. if (this.disposeOnEnd) {
  52761. // Remove from active animatables
  52762. index = this._scene._activeAnimatables.indexOf(this);
  52763. this._scene._activeAnimatables.splice(index, 1);
  52764. // Dispose all runtime animations
  52765. for (index = 0; index < runtimeAnimations.length; index++) {
  52766. runtimeAnimations[index].dispose();
  52767. }
  52768. }
  52769. this._raiseOnAnimationEnd();
  52770. if (this.disposeOnEnd) {
  52771. this.onAnimationEnd = null;
  52772. this.onAnimationEndObservable.clear();
  52773. }
  52774. }
  52775. return running;
  52776. };
  52777. return Animatable;
  52778. }());
  52779. BABYLON.Animatable = Animatable;
  52780. })(BABYLON || (BABYLON = {}));
  52781. //# sourceMappingURL=babylon.animatable.js.map
  52782. var BABYLON;
  52783. (function (BABYLON) {
  52784. /**
  52785. * Base class used for every default easing function.
  52786. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52787. */
  52788. var EasingFunction = /** @class */ (function () {
  52789. function EasingFunction() {
  52790. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52791. }
  52792. /**
  52793. * Sets the easing mode of the current function.
  52794. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52795. */
  52796. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52797. var n = Math.min(Math.max(easingMode, 0), 2);
  52798. this._easingMode = n;
  52799. };
  52800. /**
  52801. * Gets the current easing mode.
  52802. * @returns the easing mode
  52803. */
  52804. EasingFunction.prototype.getEasingMode = function () {
  52805. return this._easingMode;
  52806. };
  52807. /**
  52808. * @hidden
  52809. */
  52810. EasingFunction.prototype.easeInCore = function (gradient) {
  52811. throw new Error('You must implement this method');
  52812. };
  52813. /**
  52814. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52815. * of the easing function.
  52816. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52817. * @returns the corresponding value on the curve defined by the easing function
  52818. */
  52819. EasingFunction.prototype.ease = function (gradient) {
  52820. switch (this._easingMode) {
  52821. case EasingFunction.EASINGMODE_EASEIN:
  52822. return this.easeInCore(gradient);
  52823. case EasingFunction.EASINGMODE_EASEOUT:
  52824. return (1 - this.easeInCore(1 - gradient));
  52825. }
  52826. if (gradient >= 0.5) {
  52827. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52828. }
  52829. return (this.easeInCore(gradient * 2) * 0.5);
  52830. };
  52831. /**
  52832. * Interpolation follows the mathematical formula associated with the easing function.
  52833. */
  52834. EasingFunction.EASINGMODE_EASEIN = 0;
  52835. /**
  52836. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52837. */
  52838. EasingFunction.EASINGMODE_EASEOUT = 1;
  52839. /**
  52840. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52841. */
  52842. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52843. return EasingFunction;
  52844. }());
  52845. BABYLON.EasingFunction = EasingFunction;
  52846. /**
  52847. * Easing function with a circle shape (see link below).
  52848. * @see https://easings.net/#easeInCirc
  52849. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52850. */
  52851. var CircleEase = /** @class */ (function (_super) {
  52852. __extends(CircleEase, _super);
  52853. function CircleEase() {
  52854. return _super !== null && _super.apply(this, arguments) || this;
  52855. }
  52856. /** @hidden */
  52857. CircleEase.prototype.easeInCore = function (gradient) {
  52858. gradient = Math.max(0, Math.min(1, gradient));
  52859. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52860. };
  52861. return CircleEase;
  52862. }(EasingFunction));
  52863. BABYLON.CircleEase = CircleEase;
  52864. /**
  52865. * Easing function with a ease back shape (see link below).
  52866. * @see https://easings.net/#easeInBack
  52867. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52868. */
  52869. var BackEase = /** @class */ (function (_super) {
  52870. __extends(BackEase, _super);
  52871. /**
  52872. * Instantiates a back ease easing
  52873. * @see https://easings.net/#easeInBack
  52874. * @param amplitude Defines the amplitude of the function
  52875. */
  52876. function BackEase(
  52877. /** Defines the amplitude of the function */
  52878. amplitude) {
  52879. if (amplitude === void 0) { amplitude = 1; }
  52880. var _this = _super.call(this) || this;
  52881. _this.amplitude = amplitude;
  52882. return _this;
  52883. }
  52884. /** @hidden */
  52885. BackEase.prototype.easeInCore = function (gradient) {
  52886. var num = Math.max(0, this.amplitude);
  52887. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52888. };
  52889. return BackEase;
  52890. }(EasingFunction));
  52891. BABYLON.BackEase = BackEase;
  52892. /**
  52893. * Easing function with a bouncing shape (see link below).
  52894. * @see https://easings.net/#easeInBounce
  52895. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52896. */
  52897. var BounceEase = /** @class */ (function (_super) {
  52898. __extends(BounceEase, _super);
  52899. /**
  52900. * Instantiates a bounce easing
  52901. * @see https://easings.net/#easeInBounce
  52902. * @param bounces Defines the number of bounces
  52903. * @param bounciness Defines the amplitude of the bounce
  52904. */
  52905. function BounceEase(
  52906. /** Defines the number of bounces */
  52907. bounces,
  52908. /** Defines the amplitude of the bounce */
  52909. bounciness) {
  52910. if (bounces === void 0) { bounces = 3; }
  52911. if (bounciness === void 0) { bounciness = 2; }
  52912. var _this = _super.call(this) || this;
  52913. _this.bounces = bounces;
  52914. _this.bounciness = bounciness;
  52915. return _this;
  52916. }
  52917. /** @hidden */
  52918. BounceEase.prototype.easeInCore = function (gradient) {
  52919. var y = Math.max(0.0, this.bounces);
  52920. var bounciness = this.bounciness;
  52921. if (bounciness <= 1.0) {
  52922. bounciness = 1.001;
  52923. }
  52924. var num9 = Math.pow(bounciness, y);
  52925. var num5 = 1.0 - bounciness;
  52926. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52927. var num15 = gradient * num4;
  52928. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52929. var num3 = Math.floor(num65);
  52930. var num13 = num3 + 1.0;
  52931. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52932. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52933. var num7 = (num8 + num12) * 0.5;
  52934. var num6 = gradient - num7;
  52935. var num2 = num7 - num8;
  52936. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52937. };
  52938. return BounceEase;
  52939. }(EasingFunction));
  52940. BABYLON.BounceEase = BounceEase;
  52941. /**
  52942. * Easing function with a power of 3 shape (see link below).
  52943. * @see https://easings.net/#easeInCubic
  52944. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52945. */
  52946. var CubicEase = /** @class */ (function (_super) {
  52947. __extends(CubicEase, _super);
  52948. function CubicEase() {
  52949. return _super !== null && _super.apply(this, arguments) || this;
  52950. }
  52951. /** @hidden */
  52952. CubicEase.prototype.easeInCore = function (gradient) {
  52953. return (gradient * gradient * gradient);
  52954. };
  52955. return CubicEase;
  52956. }(EasingFunction));
  52957. BABYLON.CubicEase = CubicEase;
  52958. /**
  52959. * Easing function with an elastic shape (see link below).
  52960. * @see https://easings.net/#easeInElastic
  52961. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52962. */
  52963. var ElasticEase = /** @class */ (function (_super) {
  52964. __extends(ElasticEase, _super);
  52965. /**
  52966. * Instantiates an elastic easing function
  52967. * @see https://easings.net/#easeInElastic
  52968. * @param oscillations Defines the number of oscillations
  52969. * @param springiness Defines the amplitude of the oscillations
  52970. */
  52971. function ElasticEase(
  52972. /** Defines the number of oscillations*/
  52973. oscillations,
  52974. /** Defines the amplitude of the oscillations*/
  52975. springiness) {
  52976. if (oscillations === void 0) { oscillations = 3; }
  52977. if (springiness === void 0) { springiness = 3; }
  52978. var _this = _super.call(this) || this;
  52979. _this.oscillations = oscillations;
  52980. _this.springiness = springiness;
  52981. return _this;
  52982. }
  52983. /** @hidden */
  52984. ElasticEase.prototype.easeInCore = function (gradient) {
  52985. var num2;
  52986. var num3 = Math.max(0.0, this.oscillations);
  52987. var num = Math.max(0.0, this.springiness);
  52988. if (num == 0) {
  52989. num2 = gradient;
  52990. }
  52991. else {
  52992. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52993. }
  52994. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52995. };
  52996. return ElasticEase;
  52997. }(EasingFunction));
  52998. BABYLON.ElasticEase = ElasticEase;
  52999. /**
  53000. * Easing function with an exponential shape (see link below).
  53001. * @see https://easings.net/#easeInExpo
  53002. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53003. */
  53004. var ExponentialEase = /** @class */ (function (_super) {
  53005. __extends(ExponentialEase, _super);
  53006. /**
  53007. * Instantiates an exponential easing function
  53008. * @see https://easings.net/#easeInExpo
  53009. * @param exponent Defines the exponent of the function
  53010. */
  53011. function ExponentialEase(
  53012. /** Defines the exponent of the function */
  53013. exponent) {
  53014. if (exponent === void 0) { exponent = 2; }
  53015. var _this = _super.call(this) || this;
  53016. _this.exponent = exponent;
  53017. return _this;
  53018. }
  53019. /** @hidden */
  53020. ExponentialEase.prototype.easeInCore = function (gradient) {
  53021. if (this.exponent <= 0) {
  53022. return gradient;
  53023. }
  53024. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53025. };
  53026. return ExponentialEase;
  53027. }(EasingFunction));
  53028. BABYLON.ExponentialEase = ExponentialEase;
  53029. /**
  53030. * Easing function with a power shape (see link below).
  53031. * @see https://easings.net/#easeInQuad
  53032. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53033. */
  53034. var PowerEase = /** @class */ (function (_super) {
  53035. __extends(PowerEase, _super);
  53036. /**
  53037. * Instantiates an power base easing function
  53038. * @see https://easings.net/#easeInQuad
  53039. * @param power Defines the power of the function
  53040. */
  53041. function PowerEase(
  53042. /** Defines the power of the function */
  53043. power) {
  53044. if (power === void 0) { power = 2; }
  53045. var _this = _super.call(this) || this;
  53046. _this.power = power;
  53047. return _this;
  53048. }
  53049. /** @hidden */
  53050. PowerEase.prototype.easeInCore = function (gradient) {
  53051. var y = Math.max(0.0, this.power);
  53052. return Math.pow(gradient, y);
  53053. };
  53054. return PowerEase;
  53055. }(EasingFunction));
  53056. BABYLON.PowerEase = PowerEase;
  53057. /**
  53058. * Easing function with a power of 2 shape (see link below).
  53059. * @see https://easings.net/#easeInQuad
  53060. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53061. */
  53062. var QuadraticEase = /** @class */ (function (_super) {
  53063. __extends(QuadraticEase, _super);
  53064. function QuadraticEase() {
  53065. return _super !== null && _super.apply(this, arguments) || this;
  53066. }
  53067. /** @hidden */
  53068. QuadraticEase.prototype.easeInCore = function (gradient) {
  53069. return (gradient * gradient);
  53070. };
  53071. return QuadraticEase;
  53072. }(EasingFunction));
  53073. BABYLON.QuadraticEase = QuadraticEase;
  53074. /**
  53075. * Easing function with a power of 4 shape (see link below).
  53076. * @see https://easings.net/#easeInQuart
  53077. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53078. */
  53079. var QuarticEase = /** @class */ (function (_super) {
  53080. __extends(QuarticEase, _super);
  53081. function QuarticEase() {
  53082. return _super !== null && _super.apply(this, arguments) || this;
  53083. }
  53084. /** @hidden */
  53085. QuarticEase.prototype.easeInCore = function (gradient) {
  53086. return (gradient * gradient * gradient * gradient);
  53087. };
  53088. return QuarticEase;
  53089. }(EasingFunction));
  53090. BABYLON.QuarticEase = QuarticEase;
  53091. /**
  53092. * Easing function with a power of 5 shape (see link below).
  53093. * @see https://easings.net/#easeInQuint
  53094. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53095. */
  53096. var QuinticEase = /** @class */ (function (_super) {
  53097. __extends(QuinticEase, _super);
  53098. function QuinticEase() {
  53099. return _super !== null && _super.apply(this, arguments) || this;
  53100. }
  53101. /** @hidden */
  53102. QuinticEase.prototype.easeInCore = function (gradient) {
  53103. return (gradient * gradient * gradient * gradient * gradient);
  53104. };
  53105. return QuinticEase;
  53106. }(EasingFunction));
  53107. BABYLON.QuinticEase = QuinticEase;
  53108. /**
  53109. * Easing function with a sin shape (see link below).
  53110. * @see https://easings.net/#easeInSine
  53111. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53112. */
  53113. var SineEase = /** @class */ (function (_super) {
  53114. __extends(SineEase, _super);
  53115. function SineEase() {
  53116. return _super !== null && _super.apply(this, arguments) || this;
  53117. }
  53118. /** @hidden */
  53119. SineEase.prototype.easeInCore = function (gradient) {
  53120. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53121. };
  53122. return SineEase;
  53123. }(EasingFunction));
  53124. BABYLON.SineEase = SineEase;
  53125. /**
  53126. * Easing function with a bezier shape (see link below).
  53127. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53128. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53129. */
  53130. var BezierCurveEase = /** @class */ (function (_super) {
  53131. __extends(BezierCurveEase, _super);
  53132. /**
  53133. * Instantiates a bezier function
  53134. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53135. * @param x1 Defines the x component of the start tangent in the bezier curve
  53136. * @param y1 Defines the y component of the start tangent in the bezier curve
  53137. * @param x2 Defines the x component of the end tangent in the bezier curve
  53138. * @param y2 Defines the y component of the end tangent in the bezier curve
  53139. */
  53140. function BezierCurveEase(
  53141. /** Defines the x component of the start tangent in the bezier curve */
  53142. x1,
  53143. /** Defines the y component of the start tangent in the bezier curve */
  53144. y1,
  53145. /** Defines the x component of the end tangent in the bezier curve */
  53146. x2,
  53147. /** Defines the y component of the end tangent in the bezier curve */
  53148. y2) {
  53149. if (x1 === void 0) { x1 = 0; }
  53150. if (y1 === void 0) { y1 = 0; }
  53151. if (x2 === void 0) { x2 = 1; }
  53152. if (y2 === void 0) { y2 = 1; }
  53153. var _this = _super.call(this) || this;
  53154. _this.x1 = x1;
  53155. _this.y1 = y1;
  53156. _this.x2 = x2;
  53157. _this.y2 = y2;
  53158. return _this;
  53159. }
  53160. /** @hidden */
  53161. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53162. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53163. };
  53164. return BezierCurveEase;
  53165. }(EasingFunction));
  53166. BABYLON.BezierCurveEase = BezierCurveEase;
  53167. })(BABYLON || (BABYLON = {}));
  53168. //# sourceMappingURL=babylon.easing.js.map
  53169. var BABYLON;
  53170. (function (BABYLON) {
  53171. /**
  53172. * A Condition applied to an Action
  53173. */
  53174. var Condition = /** @class */ (function () {
  53175. /**
  53176. * Creates a new Condition
  53177. * @param actionManager the manager of the action the condition is applied to
  53178. */
  53179. function Condition(actionManager) {
  53180. this._actionManager = actionManager;
  53181. }
  53182. /**
  53183. * Check if the current condition is valid
  53184. * @returns a boolean
  53185. */
  53186. Condition.prototype.isValid = function () {
  53187. return true;
  53188. };
  53189. /**
  53190. * Internal only
  53191. * @hidden
  53192. */
  53193. Condition.prototype._getProperty = function (propertyPath) {
  53194. return this._actionManager._getProperty(propertyPath);
  53195. };
  53196. /**
  53197. * Internal only
  53198. * @hidden
  53199. */
  53200. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53201. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53202. };
  53203. /**
  53204. * Serialize placeholder for child classes
  53205. * @returns the serialized object
  53206. */
  53207. Condition.prototype.serialize = function () {
  53208. };
  53209. /**
  53210. * Internal only
  53211. * @hidden
  53212. */
  53213. Condition.prototype._serialize = function (serializedCondition) {
  53214. return {
  53215. type: 2,
  53216. children: [],
  53217. name: serializedCondition.name,
  53218. properties: serializedCondition.properties
  53219. };
  53220. };
  53221. return Condition;
  53222. }());
  53223. BABYLON.Condition = Condition;
  53224. /**
  53225. * Defines specific conditional operators as extensions of Condition
  53226. */
  53227. var ValueCondition = /** @class */ (function (_super) {
  53228. __extends(ValueCondition, _super);
  53229. /**
  53230. * Creates a new ValueCondition
  53231. * @param actionManager manager for the action the condition applies to
  53232. * @param target for the action
  53233. * @param propertyPath path to specify the property of the target the conditional operator uses
  53234. * @param value the value compared by the conditional operator against the current value of the property
  53235. * @param operator the conditional operator, default ValueCondition.IsEqual
  53236. */
  53237. function ValueCondition(actionManager, target,
  53238. /** path to specify the property of the target the conditional operator uses */
  53239. propertyPath,
  53240. /** the value compared by the conditional operator against the current value of the property */
  53241. value,
  53242. /** the conditional operator, default ValueCondition.IsEqual */
  53243. operator) {
  53244. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53245. var _this = _super.call(this, actionManager) || this;
  53246. _this.propertyPath = propertyPath;
  53247. _this.value = value;
  53248. _this.operator = operator;
  53249. _this._target = target;
  53250. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53251. _this._property = _this._getProperty(_this.propertyPath);
  53252. return _this;
  53253. }
  53254. Object.defineProperty(ValueCondition, "IsEqual", {
  53255. /**
  53256. * returns the number for IsEqual
  53257. */
  53258. get: function () {
  53259. return ValueCondition._IsEqual;
  53260. },
  53261. enumerable: true,
  53262. configurable: true
  53263. });
  53264. Object.defineProperty(ValueCondition, "IsDifferent", {
  53265. /**
  53266. * Returns the number for IsDifferent
  53267. */
  53268. get: function () {
  53269. return ValueCondition._IsDifferent;
  53270. },
  53271. enumerable: true,
  53272. configurable: true
  53273. });
  53274. Object.defineProperty(ValueCondition, "IsGreater", {
  53275. /**
  53276. * Returns the number for IsGreater
  53277. */
  53278. get: function () {
  53279. return ValueCondition._IsGreater;
  53280. },
  53281. enumerable: true,
  53282. configurable: true
  53283. });
  53284. Object.defineProperty(ValueCondition, "IsLesser", {
  53285. /**
  53286. * Returns the number for IsLesser
  53287. */
  53288. get: function () {
  53289. return ValueCondition._IsLesser;
  53290. },
  53291. enumerable: true,
  53292. configurable: true
  53293. });
  53294. /**
  53295. * Compares the given value with the property value for the specified conditional operator
  53296. * @returns the result of the comparison
  53297. */
  53298. ValueCondition.prototype.isValid = function () {
  53299. switch (this.operator) {
  53300. case ValueCondition.IsGreater:
  53301. return this._effectiveTarget[this._property] > this.value;
  53302. case ValueCondition.IsLesser:
  53303. return this._effectiveTarget[this._property] < this.value;
  53304. case ValueCondition.IsEqual:
  53305. case ValueCondition.IsDifferent:
  53306. var check;
  53307. if (this.value.equals) {
  53308. check = this.value.equals(this._effectiveTarget[this._property]);
  53309. }
  53310. else {
  53311. check = this.value === this._effectiveTarget[this._property];
  53312. }
  53313. return this.operator === ValueCondition.IsEqual ? check : !check;
  53314. }
  53315. return false;
  53316. };
  53317. /**
  53318. * Serialize the ValueCondition into a JSON compatible object
  53319. * @returns serialization object
  53320. */
  53321. ValueCondition.prototype.serialize = function () {
  53322. return this._serialize({
  53323. name: "ValueCondition",
  53324. properties: [
  53325. BABYLON.Action._GetTargetProperty(this._target),
  53326. { name: "propertyPath", value: this.propertyPath },
  53327. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53328. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53329. ]
  53330. });
  53331. };
  53332. /**
  53333. * Gets the name of the conditional operator for the ValueCondition
  53334. * @param operator the conditional operator
  53335. * @returns the name
  53336. */
  53337. ValueCondition.GetOperatorName = function (operator) {
  53338. switch (operator) {
  53339. case ValueCondition._IsEqual: return "IsEqual";
  53340. case ValueCondition._IsDifferent: return "IsDifferent";
  53341. case ValueCondition._IsGreater: return "IsGreater";
  53342. case ValueCondition._IsLesser: return "IsLesser";
  53343. default: return "";
  53344. }
  53345. };
  53346. /**
  53347. * Internal only
  53348. * @hidden
  53349. */
  53350. ValueCondition._IsEqual = 0;
  53351. /**
  53352. * Internal only
  53353. * @hidden
  53354. */
  53355. ValueCondition._IsDifferent = 1;
  53356. /**
  53357. * Internal only
  53358. * @hidden
  53359. */
  53360. ValueCondition._IsGreater = 2;
  53361. /**
  53362. * Internal only
  53363. * @hidden
  53364. */
  53365. ValueCondition._IsLesser = 3;
  53366. return ValueCondition;
  53367. }(Condition));
  53368. BABYLON.ValueCondition = ValueCondition;
  53369. /**
  53370. * Defines a predicate condition as an extension of Condition
  53371. */
  53372. var PredicateCondition = /** @class */ (function (_super) {
  53373. __extends(PredicateCondition, _super);
  53374. /**
  53375. * Creates a new PredicateCondition
  53376. * @param actionManager manager for the action the condition applies to
  53377. * @param predicate defines the predicate function used to validate the condition
  53378. */
  53379. function PredicateCondition(actionManager,
  53380. /** defines the predicate function used to validate the condition */
  53381. predicate) {
  53382. var _this = _super.call(this, actionManager) || this;
  53383. _this.predicate = predicate;
  53384. return _this;
  53385. }
  53386. /**
  53387. * @returns the validity of the predicate condition
  53388. */
  53389. PredicateCondition.prototype.isValid = function () {
  53390. return this.predicate();
  53391. };
  53392. return PredicateCondition;
  53393. }(Condition));
  53394. BABYLON.PredicateCondition = PredicateCondition;
  53395. /**
  53396. * Defines a state condition as an extension of Condition
  53397. */
  53398. var StateCondition = /** @class */ (function (_super) {
  53399. __extends(StateCondition, _super);
  53400. /**
  53401. * Creates a new StateCondition
  53402. * @param actionManager manager for the action the condition applies to
  53403. * @param target of the condition
  53404. * @param value to compare with target state
  53405. */
  53406. function StateCondition(actionManager, target, value) {
  53407. var _this = _super.call(this, actionManager) || this;
  53408. _this.value = value;
  53409. _this._target = target;
  53410. return _this;
  53411. }
  53412. /**
  53413. * @returns the validity of the state
  53414. */
  53415. StateCondition.prototype.isValid = function () {
  53416. return this._target.state === this.value;
  53417. };
  53418. /**
  53419. * Serialize the StateCondition into a JSON compatible object
  53420. * @returns serialization object
  53421. */
  53422. StateCondition.prototype.serialize = function () {
  53423. return this._serialize({
  53424. name: "StateCondition",
  53425. properties: [
  53426. BABYLON.Action._GetTargetProperty(this._target),
  53427. { name: "value", value: this.value }
  53428. ]
  53429. });
  53430. };
  53431. return StateCondition;
  53432. }(Condition));
  53433. BABYLON.StateCondition = StateCondition;
  53434. })(BABYLON || (BABYLON = {}));
  53435. //# sourceMappingURL=babylon.condition.js.map
  53436. var BABYLON;
  53437. (function (BABYLON) {
  53438. /**
  53439. * The action to be carried out following a trigger
  53440. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53441. */
  53442. var Action = /** @class */ (function () {
  53443. /**
  53444. * Creates a new Action
  53445. * @param triggerOptions the trigger, with or without parameters, for the action
  53446. * @param condition an optional determinant of action
  53447. */
  53448. function Action(
  53449. /** the trigger, with or without parameters, for the action */
  53450. triggerOptions, condition) {
  53451. this.triggerOptions = triggerOptions;
  53452. /**
  53453. * An event triggered prior to action being executed.
  53454. */
  53455. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53456. if (triggerOptions.parameter) {
  53457. this.trigger = triggerOptions.trigger;
  53458. this._triggerParameter = triggerOptions.parameter;
  53459. }
  53460. else if (triggerOptions.trigger) {
  53461. this.trigger = triggerOptions.trigger;
  53462. }
  53463. else {
  53464. this.trigger = triggerOptions;
  53465. }
  53466. this._nextActiveAction = this;
  53467. this._condition = condition;
  53468. }
  53469. /**
  53470. * Internal only
  53471. * @hidden
  53472. */
  53473. Action.prototype._prepare = function () {
  53474. };
  53475. /**
  53476. * Gets the trigger parameters
  53477. * @returns the trigger parameters
  53478. */
  53479. Action.prototype.getTriggerParameter = function () {
  53480. return this._triggerParameter;
  53481. };
  53482. /**
  53483. * Internal only - executes current action event
  53484. * @hidden
  53485. */
  53486. Action.prototype._executeCurrent = function (evt) {
  53487. if (this._nextActiveAction._condition) {
  53488. var condition = this._nextActiveAction._condition;
  53489. var currentRenderId = this._actionManager.getScene().getRenderId();
  53490. // We cache the current evaluation for the current frame
  53491. if (condition._evaluationId === currentRenderId) {
  53492. if (!condition._currentResult) {
  53493. return;
  53494. }
  53495. }
  53496. else {
  53497. condition._evaluationId = currentRenderId;
  53498. if (!condition.isValid()) {
  53499. condition._currentResult = false;
  53500. return;
  53501. }
  53502. condition._currentResult = true;
  53503. }
  53504. }
  53505. this.onBeforeExecuteObservable.notifyObservers(this);
  53506. this._nextActiveAction.execute(evt);
  53507. this.skipToNextActiveAction();
  53508. };
  53509. /**
  53510. * Execute placeholder for child classes
  53511. * @param evt optional action event
  53512. */
  53513. Action.prototype.execute = function (evt) {
  53514. };
  53515. /**
  53516. * Skips to next active action
  53517. */
  53518. Action.prototype.skipToNextActiveAction = function () {
  53519. if (this._nextActiveAction._child) {
  53520. if (!this._nextActiveAction._child._actionManager) {
  53521. this._nextActiveAction._child._actionManager = this._actionManager;
  53522. }
  53523. this._nextActiveAction = this._nextActiveAction._child;
  53524. }
  53525. else {
  53526. this._nextActiveAction = this;
  53527. }
  53528. };
  53529. /**
  53530. * Adds action to chain of actions, may be a DoNothingAction
  53531. * @param action defines the next action to execute
  53532. * @returns The action passed in
  53533. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53534. */
  53535. Action.prototype.then = function (action) {
  53536. this._child = action;
  53537. action._actionManager = this._actionManager;
  53538. action._prepare();
  53539. return action;
  53540. };
  53541. /**
  53542. * Internal only
  53543. * @hidden
  53544. */
  53545. Action.prototype._getProperty = function (propertyPath) {
  53546. return this._actionManager._getProperty(propertyPath);
  53547. };
  53548. /**
  53549. * Internal only
  53550. * @hidden
  53551. */
  53552. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53553. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53554. };
  53555. /**
  53556. * Serialize placeholder for child classes
  53557. * @param parent of child
  53558. * @returns the serialized object
  53559. */
  53560. Action.prototype.serialize = function (parent) {
  53561. };
  53562. /**
  53563. * Internal only called by serialize
  53564. * @hidden
  53565. */
  53566. Action.prototype._serialize = function (serializedAction, parent) {
  53567. var serializationObject = {
  53568. type: 1,
  53569. children: [],
  53570. name: serializedAction.name,
  53571. properties: serializedAction.properties || []
  53572. };
  53573. // Serialize child
  53574. if (this._child) {
  53575. this._child.serialize(serializationObject);
  53576. }
  53577. // Check if "this" has a condition
  53578. if (this._condition) {
  53579. var serializedCondition = this._condition.serialize();
  53580. serializedCondition.children.push(serializationObject);
  53581. if (parent) {
  53582. parent.children.push(serializedCondition);
  53583. }
  53584. return serializedCondition;
  53585. }
  53586. if (parent) {
  53587. parent.children.push(serializationObject);
  53588. }
  53589. return serializationObject;
  53590. };
  53591. /**
  53592. * Internal only
  53593. * @hidden
  53594. */
  53595. Action._SerializeValueAsString = function (value) {
  53596. if (typeof value === "number") {
  53597. return value.toString();
  53598. }
  53599. if (typeof value === "boolean") {
  53600. return value ? "true" : "false";
  53601. }
  53602. if (value instanceof BABYLON.Vector2) {
  53603. return value.x + ", " + value.y;
  53604. }
  53605. if (value instanceof BABYLON.Vector3) {
  53606. return value.x + ", " + value.y + ", " + value.z;
  53607. }
  53608. if (value instanceof BABYLON.Color3) {
  53609. return value.r + ", " + value.g + ", " + value.b;
  53610. }
  53611. if (value instanceof BABYLON.Color4) {
  53612. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53613. }
  53614. return value; // string
  53615. };
  53616. /**
  53617. * Internal only
  53618. * @hidden
  53619. */
  53620. Action._GetTargetProperty = function (target) {
  53621. return {
  53622. name: "target",
  53623. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53624. : target instanceof BABYLON.Light ? "LightProperties"
  53625. : target instanceof BABYLON.Camera ? "CameraProperties"
  53626. : "SceneProperties",
  53627. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53628. };
  53629. };
  53630. return Action;
  53631. }());
  53632. BABYLON.Action = Action;
  53633. })(BABYLON || (BABYLON = {}));
  53634. //# sourceMappingURL=babylon.action.js.map
  53635. var BABYLON;
  53636. (function (BABYLON) {
  53637. /**
  53638. * ActionEvent is the event being sent when an action is triggered.
  53639. */
  53640. var ActionEvent = /** @class */ (function () {
  53641. /**
  53642. * Creates a new ActionEvent
  53643. * @param source The mesh or sprite that triggered the action
  53644. * @param pointerX The X mouse cursor position at the time of the event
  53645. * @param pointerY The Y mouse cursor position at the time of the event
  53646. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53647. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53648. * @param additionalData additional data for the event
  53649. */
  53650. function ActionEvent(
  53651. /** The mesh or sprite that triggered the action */
  53652. source,
  53653. /** The X mouse cursor position at the time of the event */
  53654. pointerX,
  53655. /** The Y mouse cursor position at the time of the event */
  53656. pointerY,
  53657. /** The mesh that is currently pointed at (can be null) */
  53658. meshUnderPointer,
  53659. /** the original (browser) event that triggered the ActionEvent */
  53660. sourceEvent,
  53661. /** additional data for the event */
  53662. additionalData) {
  53663. this.source = source;
  53664. this.pointerX = pointerX;
  53665. this.pointerY = pointerY;
  53666. this.meshUnderPointer = meshUnderPointer;
  53667. this.sourceEvent = sourceEvent;
  53668. this.additionalData = additionalData;
  53669. }
  53670. /**
  53671. * Helper function to auto-create an ActionEvent from a source mesh.
  53672. * @param source The source mesh that triggered the event
  53673. * @param evt The original (browser) event
  53674. * @param additionalData additional data for the event
  53675. * @returns the new ActionEvent
  53676. */
  53677. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53678. var scene = source.getScene();
  53679. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53680. };
  53681. /**
  53682. * Helper function to auto-create an ActionEvent from a source sprite
  53683. * @param source The source sprite that triggered the event
  53684. * @param scene Scene associated with the sprite
  53685. * @param evt The original (browser) event
  53686. * @param additionalData additional data for the event
  53687. * @returns the new ActionEvent
  53688. */
  53689. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53690. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53691. };
  53692. /**
  53693. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53694. * @param scene the scene where the event occurred
  53695. * @param evt The original (browser) event
  53696. * @returns the new ActionEvent
  53697. */
  53698. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53699. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53700. };
  53701. /**
  53702. * Helper function to auto-create an ActionEvent from a primitive
  53703. * @param prim defines the target primitive
  53704. * @param pointerPos defines the pointer position
  53705. * @param evt The original (browser) event
  53706. * @param additionalData additional data for the event
  53707. * @returns the new ActionEvent
  53708. */
  53709. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53710. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53711. };
  53712. return ActionEvent;
  53713. }());
  53714. BABYLON.ActionEvent = ActionEvent;
  53715. /**
  53716. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53717. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53718. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53719. */
  53720. var ActionManager = /** @class */ (function () {
  53721. /**
  53722. * Creates a new action manager
  53723. * @param scene defines the hosting scene
  53724. */
  53725. function ActionManager(scene) {
  53726. // Members
  53727. /** Gets the list of actions */
  53728. this.actions = new Array();
  53729. /** Gets the cursor to use when hovering items */
  53730. this.hoverCursor = '';
  53731. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53732. scene.actionManagers.push(this);
  53733. }
  53734. // Methods
  53735. /**
  53736. * Releases all associated resources
  53737. */
  53738. ActionManager.prototype.dispose = function () {
  53739. var index = this._scene.actionManagers.indexOf(this);
  53740. for (var i = 0; i < this.actions.length; i++) {
  53741. var action = this.actions[i];
  53742. ActionManager.Triggers[action.trigger]--;
  53743. if (ActionManager.Triggers[action.trigger] === 0) {
  53744. delete ActionManager.Triggers[action.trigger];
  53745. }
  53746. }
  53747. if (index > -1) {
  53748. this._scene.actionManagers.splice(index, 1);
  53749. }
  53750. };
  53751. /**
  53752. * Gets hosting scene
  53753. * @returns the hosting scene
  53754. */
  53755. ActionManager.prototype.getScene = function () {
  53756. return this._scene;
  53757. };
  53758. /**
  53759. * Does this action manager handles actions of any of the given triggers
  53760. * @param triggers defines the triggers to be tested
  53761. * @return a boolean indicating whether one (or more) of the triggers is handled
  53762. */
  53763. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53764. for (var index = 0; index < this.actions.length; index++) {
  53765. var action = this.actions[index];
  53766. if (triggers.indexOf(action.trigger) > -1) {
  53767. return true;
  53768. }
  53769. }
  53770. return false;
  53771. };
  53772. /**
  53773. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53774. * speed.
  53775. * @param triggerA defines the trigger to be tested
  53776. * @param triggerB defines the trigger to be tested
  53777. * @return a boolean indicating whether one (or more) of the triggers is handled
  53778. */
  53779. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53780. for (var index = 0; index < this.actions.length; index++) {
  53781. var action = this.actions[index];
  53782. if (triggerA == action.trigger || triggerB == action.trigger) {
  53783. return true;
  53784. }
  53785. }
  53786. return false;
  53787. };
  53788. /**
  53789. * Does this action manager handles actions of a given trigger
  53790. * @param trigger defines the trigger to be tested
  53791. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53792. * @return whether the trigger is handled
  53793. */
  53794. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53795. for (var index = 0; index < this.actions.length; index++) {
  53796. var action = this.actions[index];
  53797. if (action.trigger === trigger) {
  53798. if (parameterPredicate) {
  53799. if (parameterPredicate(action.getTriggerParameter())) {
  53800. return true;
  53801. }
  53802. }
  53803. else {
  53804. return true;
  53805. }
  53806. }
  53807. }
  53808. return false;
  53809. };
  53810. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53811. /**
  53812. * Does this action manager has pointer triggers
  53813. */
  53814. get: function () {
  53815. for (var index = 0; index < this.actions.length; index++) {
  53816. var action = this.actions[index];
  53817. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53818. return true;
  53819. }
  53820. }
  53821. return false;
  53822. },
  53823. enumerable: true,
  53824. configurable: true
  53825. });
  53826. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53827. /**
  53828. * Does this action manager has pick triggers
  53829. */
  53830. get: function () {
  53831. for (var index = 0; index < this.actions.length; index++) {
  53832. var action = this.actions[index];
  53833. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53834. return true;
  53835. }
  53836. }
  53837. return false;
  53838. },
  53839. enumerable: true,
  53840. configurable: true
  53841. });
  53842. Object.defineProperty(ActionManager, "HasTriggers", {
  53843. /**
  53844. * Does exist one action manager with at least one trigger
  53845. **/
  53846. get: function () {
  53847. for (var t in ActionManager.Triggers) {
  53848. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53849. return true;
  53850. }
  53851. }
  53852. return false;
  53853. },
  53854. enumerable: true,
  53855. configurable: true
  53856. });
  53857. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53858. /**
  53859. * Does exist one action manager with at least one pick trigger
  53860. **/
  53861. get: function () {
  53862. for (var t in ActionManager.Triggers) {
  53863. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53864. var t_int = parseInt(t);
  53865. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53866. return true;
  53867. }
  53868. }
  53869. }
  53870. return false;
  53871. },
  53872. enumerable: true,
  53873. configurable: true
  53874. });
  53875. /**
  53876. * Does exist one action manager that handles actions of a given trigger
  53877. * @param trigger defines the trigger to be tested
  53878. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53879. **/
  53880. ActionManager.HasSpecificTrigger = function (trigger) {
  53881. for (var t in ActionManager.Triggers) {
  53882. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53883. var t_int = parseInt(t);
  53884. if (t_int === trigger) {
  53885. return true;
  53886. }
  53887. }
  53888. }
  53889. return false;
  53890. };
  53891. /**
  53892. * Registers an action to this action manager
  53893. * @param action defines the action to be registered
  53894. * @return the action amended (prepared) after registration
  53895. */
  53896. ActionManager.prototype.registerAction = function (action) {
  53897. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53898. if (this.getScene().actionManager !== this) {
  53899. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53900. return null;
  53901. }
  53902. }
  53903. this.actions.push(action);
  53904. if (ActionManager.Triggers[action.trigger]) {
  53905. ActionManager.Triggers[action.trigger]++;
  53906. }
  53907. else {
  53908. ActionManager.Triggers[action.trigger] = 1;
  53909. }
  53910. action._actionManager = this;
  53911. action._prepare();
  53912. return action;
  53913. };
  53914. /**
  53915. * Unregisters an action to this action manager
  53916. * @param action defines the action to be unregistered
  53917. * @return a boolean indicating whether the action has been unregistered
  53918. */
  53919. ActionManager.prototype.unregisterAction = function (action) {
  53920. var index = this.actions.indexOf(action);
  53921. if (index !== -1) {
  53922. this.actions.splice(index, 1);
  53923. ActionManager.Triggers[action.trigger] -= 1;
  53924. if (ActionManager.Triggers[action.trigger] === 0) {
  53925. delete ActionManager.Triggers[action.trigger];
  53926. }
  53927. delete action._actionManager;
  53928. return true;
  53929. }
  53930. return false;
  53931. };
  53932. /**
  53933. * Process a specific trigger
  53934. * @param trigger defines the trigger to process
  53935. * @param evt defines the event details to be processed
  53936. */
  53937. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53938. for (var index = 0; index < this.actions.length; index++) {
  53939. var action = this.actions[index];
  53940. if (action.trigger === trigger) {
  53941. if (evt) {
  53942. if (trigger === ActionManager.OnKeyUpTrigger
  53943. || trigger === ActionManager.OnKeyDownTrigger) {
  53944. var parameter = action.getTriggerParameter();
  53945. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53946. if (!parameter.toLowerCase) {
  53947. continue;
  53948. }
  53949. var lowerCase = parameter.toLowerCase();
  53950. if (lowerCase !== evt.sourceEvent.key) {
  53951. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53952. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53953. if (actualkey !== lowerCase) {
  53954. continue;
  53955. }
  53956. }
  53957. }
  53958. }
  53959. }
  53960. action._executeCurrent(evt);
  53961. }
  53962. }
  53963. };
  53964. /** @hidden */
  53965. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53966. var properties = propertyPath.split(".");
  53967. for (var index = 0; index < properties.length - 1; index++) {
  53968. target = target[properties[index]];
  53969. }
  53970. return target;
  53971. };
  53972. /** @hidden */
  53973. ActionManager.prototype._getProperty = function (propertyPath) {
  53974. var properties = propertyPath.split(".");
  53975. return properties[properties.length - 1];
  53976. };
  53977. /**
  53978. * Serialize this manager to a JSON object
  53979. * @param name defines the property name to store this manager
  53980. * @returns a JSON representation of this manager
  53981. */
  53982. ActionManager.prototype.serialize = function (name) {
  53983. var root = {
  53984. children: new Array(),
  53985. name: name,
  53986. type: 3,
  53987. properties: new Array() // Empty for root but required
  53988. };
  53989. for (var i = 0; i < this.actions.length; i++) {
  53990. var triggerObject = {
  53991. type: 0,
  53992. children: new Array(),
  53993. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53994. properties: new Array()
  53995. };
  53996. var triggerOptions = this.actions[i].triggerOptions;
  53997. if (triggerOptions && typeof triggerOptions !== "number") {
  53998. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53999. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54000. }
  54001. else {
  54002. var parameter = {};
  54003. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54004. if (triggerOptions.parameter.mesh) {
  54005. parameter._meshId = triggerOptions.parameter.mesh.id;
  54006. }
  54007. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54008. }
  54009. }
  54010. // Serialize child action, recursively
  54011. this.actions[i].serialize(triggerObject);
  54012. // Add serialized trigger
  54013. root.children.push(triggerObject);
  54014. }
  54015. return root;
  54016. };
  54017. /**
  54018. * Creates a new ActionManager from a JSON data
  54019. * @param parsedActions defines the JSON data to read from
  54020. * @param object defines the hosting mesh
  54021. * @param scene defines the hosting scene
  54022. */
  54023. ActionManager.Parse = function (parsedActions, object, scene) {
  54024. var actionManager = new ActionManager(scene);
  54025. if (object === null)
  54026. scene.actionManager = actionManager;
  54027. else
  54028. object.actionManager = actionManager;
  54029. // instanciate a new object
  54030. var instanciate = function (name, params) {
  54031. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54032. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54033. newInstance.constructor.apply(newInstance, params);
  54034. return newInstance;
  54035. };
  54036. var parseParameter = function (name, value, target, propertyPath) {
  54037. if (propertyPath === null) {
  54038. // String, boolean or float
  54039. var floatValue = parseFloat(value);
  54040. if (value === "true" || value === "false")
  54041. return value === "true";
  54042. else
  54043. return isNaN(floatValue) ? value : floatValue;
  54044. }
  54045. var effectiveTarget = propertyPath.split(".");
  54046. var values = value.split(",");
  54047. // Get effective Target
  54048. for (var i = 0; i < effectiveTarget.length; i++) {
  54049. target = target[effectiveTarget[i]];
  54050. }
  54051. // Return appropriate value with its type
  54052. if (typeof (target) === "boolean")
  54053. return values[0] === "true";
  54054. if (typeof (target) === "string")
  54055. return values[0];
  54056. // Parameters with multiple values such as Vector3 etc.
  54057. var split = new Array();
  54058. for (var i = 0; i < values.length; i++)
  54059. split.push(parseFloat(values[i]));
  54060. if (target instanceof BABYLON.Vector3)
  54061. return BABYLON.Vector3.FromArray(split);
  54062. if (target instanceof BABYLON.Vector4)
  54063. return BABYLON.Vector4.FromArray(split);
  54064. if (target instanceof BABYLON.Color3)
  54065. return BABYLON.Color3.FromArray(split);
  54066. if (target instanceof BABYLON.Color4)
  54067. return BABYLON.Color4.FromArray(split);
  54068. return parseFloat(values[0]);
  54069. };
  54070. // traverse graph per trigger
  54071. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54072. if (combineArray === void 0) { combineArray = null; }
  54073. if (parsedAction.detached)
  54074. return;
  54075. var parameters = new Array();
  54076. var target = null;
  54077. var propertyPath = null;
  54078. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54079. // Parameters
  54080. if (parsedAction.type === 2)
  54081. parameters.push(actionManager);
  54082. else
  54083. parameters.push(trigger);
  54084. if (combine) {
  54085. var actions = new Array();
  54086. for (var j = 0; j < parsedAction.combine.length; j++) {
  54087. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54088. }
  54089. parameters.push(actions);
  54090. }
  54091. else {
  54092. for (var i = 0; i < parsedAction.properties.length; i++) {
  54093. var value = parsedAction.properties[i].value;
  54094. var name = parsedAction.properties[i].name;
  54095. var targetType = parsedAction.properties[i].targetType;
  54096. if (name === "target")
  54097. if (targetType !== null && targetType === "SceneProperties")
  54098. value = target = scene;
  54099. else
  54100. value = target = scene.getNodeByName(value);
  54101. else if (name === "parent")
  54102. value = scene.getNodeByName(value);
  54103. else if (name === "sound") {
  54104. // Can not externalize to component, so only checks for the presence off the API.
  54105. if (scene.getSoundByName) {
  54106. value = scene.getSoundByName(value);
  54107. }
  54108. }
  54109. else if (name !== "propertyPath") {
  54110. if (parsedAction.type === 2 && name === "operator")
  54111. value = BABYLON.ValueCondition[value];
  54112. else
  54113. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54114. }
  54115. else {
  54116. propertyPath = value;
  54117. }
  54118. parameters.push(value);
  54119. }
  54120. }
  54121. if (combineArray === null) {
  54122. parameters.push(condition);
  54123. }
  54124. else {
  54125. parameters.push(null);
  54126. }
  54127. // If interpolate value action
  54128. if (parsedAction.name === "InterpolateValueAction") {
  54129. var param = parameters[parameters.length - 2];
  54130. parameters[parameters.length - 1] = param;
  54131. parameters[parameters.length - 2] = condition;
  54132. }
  54133. // Action or condition(s) and not CombineAction
  54134. var newAction = instanciate(parsedAction.name, parameters);
  54135. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54136. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54137. if (action)
  54138. action.then(nothing);
  54139. else
  54140. actionManager.registerAction(nothing);
  54141. action = nothing;
  54142. }
  54143. if (combineArray === null) {
  54144. if (newAction instanceof BABYLON.Condition) {
  54145. condition = newAction;
  54146. newAction = action;
  54147. }
  54148. else {
  54149. condition = null;
  54150. if (action)
  54151. action.then(newAction);
  54152. else
  54153. actionManager.registerAction(newAction);
  54154. }
  54155. }
  54156. else {
  54157. combineArray.push(newAction);
  54158. }
  54159. for (var i = 0; i < parsedAction.children.length; i++)
  54160. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54161. };
  54162. // triggers
  54163. for (var i = 0; i < parsedActions.children.length; i++) {
  54164. var triggerParams;
  54165. var trigger = parsedActions.children[i];
  54166. if (trigger.properties.length > 0) {
  54167. var param = trigger.properties[0].value;
  54168. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54169. if (value._meshId) {
  54170. value.mesh = scene.getMeshByID(value._meshId);
  54171. }
  54172. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54173. }
  54174. else
  54175. triggerParams = ActionManager[trigger.name];
  54176. for (var j = 0; j < trigger.children.length; j++) {
  54177. if (!trigger.detached)
  54178. traverse(trigger.children[j], triggerParams, null, null);
  54179. }
  54180. }
  54181. };
  54182. /**
  54183. * Get a trigger name by index
  54184. * @param trigger defines the trigger index
  54185. * @returns a trigger name
  54186. */
  54187. ActionManager.GetTriggerName = function (trigger) {
  54188. switch (trigger) {
  54189. case 0: return "NothingTrigger";
  54190. case 1: return "OnPickTrigger";
  54191. case 2: return "OnLeftPickTrigger";
  54192. case 3: return "OnRightPickTrigger";
  54193. case 4: return "OnCenterPickTrigger";
  54194. case 5: return "OnPickDownTrigger";
  54195. case 6: return "OnPickUpTrigger";
  54196. case 7: return "OnLongPressTrigger";
  54197. case 8: return "OnPointerOverTrigger";
  54198. case 9: return "OnPointerOutTrigger";
  54199. case 10: return "OnEveryFrameTrigger";
  54200. case 11: return "OnIntersectionEnterTrigger";
  54201. case 12: return "OnIntersectionExitTrigger";
  54202. case 13: return "OnKeyDownTrigger";
  54203. case 14: return "OnKeyUpTrigger";
  54204. case 15: return "OnPickOutTrigger";
  54205. default: return "";
  54206. }
  54207. };
  54208. /**
  54209. * Nothing
  54210. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54211. */
  54212. ActionManager.NothingTrigger = 0;
  54213. /**
  54214. * On pick
  54215. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54216. */
  54217. ActionManager.OnPickTrigger = 1;
  54218. /**
  54219. * On left pick
  54220. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54221. */
  54222. ActionManager.OnLeftPickTrigger = 2;
  54223. /**
  54224. * On right pick
  54225. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54226. */
  54227. ActionManager.OnRightPickTrigger = 3;
  54228. /**
  54229. * On center pick
  54230. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54231. */
  54232. ActionManager.OnCenterPickTrigger = 4;
  54233. /**
  54234. * On pick down
  54235. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54236. */
  54237. ActionManager.OnPickDownTrigger = 5;
  54238. /**
  54239. * On double pick
  54240. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54241. */
  54242. ActionManager.OnDoublePickTrigger = 6;
  54243. /**
  54244. * On pick up
  54245. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54246. */
  54247. ActionManager.OnPickUpTrigger = 7;
  54248. /**
  54249. * On pick out.
  54250. * This trigger will only be raised if you also declared a OnPickDown
  54251. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54252. */
  54253. ActionManager.OnPickOutTrigger = 16;
  54254. /**
  54255. * On long press
  54256. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54257. */
  54258. ActionManager.OnLongPressTrigger = 8;
  54259. /**
  54260. * On pointer over
  54261. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54262. */
  54263. ActionManager.OnPointerOverTrigger = 9;
  54264. /**
  54265. * On pointer out
  54266. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54267. */
  54268. ActionManager.OnPointerOutTrigger = 10;
  54269. /**
  54270. * On every frame
  54271. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54272. */
  54273. ActionManager.OnEveryFrameTrigger = 11;
  54274. /**
  54275. * On intersection enter
  54276. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54277. */
  54278. ActionManager.OnIntersectionEnterTrigger = 12;
  54279. /**
  54280. * On intersection exit
  54281. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54282. */
  54283. ActionManager.OnIntersectionExitTrigger = 13;
  54284. /**
  54285. * On key down
  54286. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54287. */
  54288. ActionManager.OnKeyDownTrigger = 14;
  54289. /**
  54290. * On key up
  54291. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54292. */
  54293. ActionManager.OnKeyUpTrigger = 15;
  54294. /** Gets the list of active triggers */
  54295. ActionManager.Triggers = {};
  54296. return ActionManager;
  54297. }());
  54298. BABYLON.ActionManager = ActionManager;
  54299. })(BABYLON || (BABYLON = {}));
  54300. //# sourceMappingURL=babylon.actionManager.js.map
  54301. var BABYLON;
  54302. (function (BABYLON) {
  54303. /**
  54304. * This defines an action responsible to change the value of a property
  54305. * by interpolating between its current value and the newly set one once triggered.
  54306. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54307. */
  54308. var InterpolateValueAction = /** @class */ (function (_super) {
  54309. __extends(InterpolateValueAction, _super);
  54310. /**
  54311. * Instantiate the action
  54312. * @param triggerOptions defines the trigger options
  54313. * @param target defines the object containing the value to interpolate
  54314. * @param propertyPath defines the path to the property in the target object
  54315. * @param value defines the target value at the end of the interpolation
  54316. * @param duration deines the time it will take for the property to interpolate to the value.
  54317. * @param condition defines the trigger related conditions
  54318. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54319. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54320. */
  54321. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54322. if (duration === void 0) { duration = 1000; }
  54323. var _this = _super.call(this, triggerOptions, condition) || this;
  54324. /**
  54325. * Defines the time it will take for the property to interpolate to the value.
  54326. */
  54327. _this.duration = 1000;
  54328. /**
  54329. * Observable triggered once the interpolation animation has been done.
  54330. */
  54331. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54332. _this.propertyPath = propertyPath;
  54333. _this.value = value;
  54334. _this.duration = duration;
  54335. _this.stopOtherAnimations = stopOtherAnimations;
  54336. _this.onInterpolationDone = onInterpolationDone;
  54337. _this._target = _this._effectiveTarget = target;
  54338. return _this;
  54339. }
  54340. /** @hidden */
  54341. InterpolateValueAction.prototype._prepare = function () {
  54342. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54343. this._property = this._getProperty(this.propertyPath);
  54344. };
  54345. /**
  54346. * Execute the action starts the value interpolation.
  54347. */
  54348. InterpolateValueAction.prototype.execute = function () {
  54349. var _this = this;
  54350. var scene = this._actionManager.getScene();
  54351. var keys = [
  54352. {
  54353. frame: 0,
  54354. value: this._effectiveTarget[this._property]
  54355. }, {
  54356. frame: 100,
  54357. value: this.value
  54358. }
  54359. ];
  54360. var dataType;
  54361. if (typeof this.value === "number") {
  54362. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54363. }
  54364. else if (this.value instanceof BABYLON.Color3) {
  54365. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54366. }
  54367. else if (this.value instanceof BABYLON.Vector3) {
  54368. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54369. }
  54370. else if (this.value instanceof BABYLON.Matrix) {
  54371. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54372. }
  54373. else if (this.value instanceof BABYLON.Quaternion) {
  54374. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54375. }
  54376. else {
  54377. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54378. return;
  54379. }
  54380. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54381. animation.setKeys(keys);
  54382. if (this.stopOtherAnimations) {
  54383. scene.stopAnimation(this._effectiveTarget);
  54384. }
  54385. var wrapper = function () {
  54386. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54387. if (_this.onInterpolationDone) {
  54388. _this.onInterpolationDone();
  54389. }
  54390. };
  54391. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54392. };
  54393. /**
  54394. * Serializes the actions and its related information.
  54395. * @param parent defines the object to serialize in
  54396. * @returns the serialized object
  54397. */
  54398. InterpolateValueAction.prototype.serialize = function (parent) {
  54399. return _super.prototype._serialize.call(this, {
  54400. name: "InterpolateValueAction",
  54401. properties: [
  54402. BABYLON.Action._GetTargetProperty(this._target),
  54403. { name: "propertyPath", value: this.propertyPath },
  54404. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54405. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54406. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54407. ]
  54408. }, parent);
  54409. };
  54410. return InterpolateValueAction;
  54411. }(BABYLON.Action));
  54412. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54413. })(BABYLON || (BABYLON = {}));
  54414. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54415. var BABYLON;
  54416. (function (BABYLON) {
  54417. /**
  54418. * This defines an action responsible to toggle a boolean once triggered.
  54419. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54420. */
  54421. var SwitchBooleanAction = /** @class */ (function (_super) {
  54422. __extends(SwitchBooleanAction, _super);
  54423. /**
  54424. * Instantiate the action
  54425. * @param triggerOptions defines the trigger options
  54426. * @param target defines the object containing the boolean
  54427. * @param propertyPath defines the path to the boolean property in the target object
  54428. * @param condition defines the trigger related conditions
  54429. */
  54430. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54431. var _this = _super.call(this, triggerOptions, condition) || this;
  54432. _this.propertyPath = propertyPath;
  54433. _this._target = _this._effectiveTarget = target;
  54434. return _this;
  54435. }
  54436. /** @hidden */
  54437. SwitchBooleanAction.prototype._prepare = function () {
  54438. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54439. this._property = this._getProperty(this.propertyPath);
  54440. };
  54441. /**
  54442. * Execute the action toggle the boolean value.
  54443. */
  54444. SwitchBooleanAction.prototype.execute = function () {
  54445. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54446. };
  54447. /**
  54448. * Serializes the actions and its related information.
  54449. * @param parent defines the object to serialize in
  54450. * @returns the serialized object
  54451. */
  54452. SwitchBooleanAction.prototype.serialize = function (parent) {
  54453. return _super.prototype._serialize.call(this, {
  54454. name: "SwitchBooleanAction",
  54455. properties: [
  54456. BABYLON.Action._GetTargetProperty(this._target),
  54457. { name: "propertyPath", value: this.propertyPath }
  54458. ]
  54459. }, parent);
  54460. };
  54461. return SwitchBooleanAction;
  54462. }(BABYLON.Action));
  54463. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54464. /**
  54465. * This defines an action responsible to set a the state field of the target
  54466. * to a desired value once triggered.
  54467. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54468. */
  54469. var SetStateAction = /** @class */ (function (_super) {
  54470. __extends(SetStateAction, _super);
  54471. /**
  54472. * Instantiate the action
  54473. * @param triggerOptions defines the trigger options
  54474. * @param target defines the object containing the state property
  54475. * @param value defines the value to store in the state field
  54476. * @param condition defines the trigger related conditions
  54477. */
  54478. function SetStateAction(triggerOptions, target, value, condition) {
  54479. var _this = _super.call(this, triggerOptions, condition) || this;
  54480. _this.value = value;
  54481. _this._target = target;
  54482. return _this;
  54483. }
  54484. /**
  54485. * Execute the action and store the value on the target state property.
  54486. */
  54487. SetStateAction.prototype.execute = function () {
  54488. this._target.state = this.value;
  54489. };
  54490. /**
  54491. * Serializes the actions and its related information.
  54492. * @param parent defines the object to serialize in
  54493. * @returns the serialized object
  54494. */
  54495. SetStateAction.prototype.serialize = function (parent) {
  54496. return _super.prototype._serialize.call(this, {
  54497. name: "SetStateAction",
  54498. properties: [
  54499. BABYLON.Action._GetTargetProperty(this._target),
  54500. { name: "value", value: this.value }
  54501. ]
  54502. }, parent);
  54503. };
  54504. return SetStateAction;
  54505. }(BABYLON.Action));
  54506. BABYLON.SetStateAction = SetStateAction;
  54507. /**
  54508. * This defines an action responsible to set a property of the target
  54509. * to a desired value once triggered.
  54510. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54511. */
  54512. var SetValueAction = /** @class */ (function (_super) {
  54513. __extends(SetValueAction, _super);
  54514. /**
  54515. * Instantiate the action
  54516. * @param triggerOptions defines the trigger options
  54517. * @param target defines the object containing the property
  54518. * @param propertyPath defines the path of the property to set in the target
  54519. * @param value defines the value to set in the property
  54520. * @param condition defines the trigger related conditions
  54521. */
  54522. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54523. var _this = _super.call(this, triggerOptions, condition) || this;
  54524. _this.propertyPath = propertyPath;
  54525. _this.value = value;
  54526. _this._target = _this._effectiveTarget = target;
  54527. return _this;
  54528. }
  54529. /** @hidden */
  54530. SetValueAction.prototype._prepare = function () {
  54531. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54532. this._property = this._getProperty(this.propertyPath);
  54533. };
  54534. /**
  54535. * Execute the action and set the targetted property to the desired value.
  54536. */
  54537. SetValueAction.prototype.execute = function () {
  54538. this._effectiveTarget[this._property] = this.value;
  54539. if (this._target.markAsDirty) {
  54540. this._target.markAsDirty(this._property);
  54541. }
  54542. };
  54543. /**
  54544. * Serializes the actions and its related information.
  54545. * @param parent defines the object to serialize in
  54546. * @returns the serialized object
  54547. */
  54548. SetValueAction.prototype.serialize = function (parent) {
  54549. return _super.prototype._serialize.call(this, {
  54550. name: "SetValueAction",
  54551. properties: [
  54552. BABYLON.Action._GetTargetProperty(this._target),
  54553. { name: "propertyPath", value: this.propertyPath },
  54554. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54555. ]
  54556. }, parent);
  54557. };
  54558. return SetValueAction;
  54559. }(BABYLON.Action));
  54560. BABYLON.SetValueAction = SetValueAction;
  54561. /**
  54562. * This defines an action responsible to increment the target value
  54563. * to a desired value once triggered.
  54564. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54565. */
  54566. var IncrementValueAction = /** @class */ (function (_super) {
  54567. __extends(IncrementValueAction, _super);
  54568. /**
  54569. * Instantiate the action
  54570. * @param triggerOptions defines the trigger options
  54571. * @param target defines the object containing the property
  54572. * @param propertyPath defines the path of the property to increment in the target
  54573. * @param value defines the value value we should increment the property by
  54574. * @param condition defines the trigger related conditions
  54575. */
  54576. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54577. var _this = _super.call(this, triggerOptions, condition) || this;
  54578. _this.propertyPath = propertyPath;
  54579. _this.value = value;
  54580. _this._target = _this._effectiveTarget = target;
  54581. return _this;
  54582. }
  54583. /** @hidden */
  54584. IncrementValueAction.prototype._prepare = function () {
  54585. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54586. this._property = this._getProperty(this.propertyPath);
  54587. if (typeof this._effectiveTarget[this._property] !== "number") {
  54588. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54589. }
  54590. };
  54591. /**
  54592. * Execute the action and increment the target of the value amount.
  54593. */
  54594. IncrementValueAction.prototype.execute = function () {
  54595. this._effectiveTarget[this._property] += this.value;
  54596. if (this._target.markAsDirty) {
  54597. this._target.markAsDirty(this._property);
  54598. }
  54599. };
  54600. /**
  54601. * Serializes the actions and its related information.
  54602. * @param parent defines the object to serialize in
  54603. * @returns the serialized object
  54604. */
  54605. IncrementValueAction.prototype.serialize = function (parent) {
  54606. return _super.prototype._serialize.call(this, {
  54607. name: "IncrementValueAction",
  54608. properties: [
  54609. BABYLON.Action._GetTargetProperty(this._target),
  54610. { name: "propertyPath", value: this.propertyPath },
  54611. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54612. ]
  54613. }, parent);
  54614. };
  54615. return IncrementValueAction;
  54616. }(BABYLON.Action));
  54617. BABYLON.IncrementValueAction = IncrementValueAction;
  54618. /**
  54619. * This defines an action responsible to start an animation once triggered.
  54620. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54621. */
  54622. var PlayAnimationAction = /** @class */ (function (_super) {
  54623. __extends(PlayAnimationAction, _super);
  54624. /**
  54625. * Instantiate the action
  54626. * @param triggerOptions defines the trigger options
  54627. * @param target defines the target animation or animation name
  54628. * @param from defines from where the animation should start (animation frame)
  54629. * @param end defines where the animation should stop (animation frame)
  54630. * @param loop defines if the animation should loop or stop after the first play
  54631. * @param condition defines the trigger related conditions
  54632. */
  54633. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54634. var _this = _super.call(this, triggerOptions, condition) || this;
  54635. _this.from = from;
  54636. _this.to = to;
  54637. _this.loop = loop;
  54638. _this._target = target;
  54639. return _this;
  54640. }
  54641. /** @hidden */
  54642. PlayAnimationAction.prototype._prepare = function () {
  54643. };
  54644. /**
  54645. * Execute the action and play the animation.
  54646. */
  54647. PlayAnimationAction.prototype.execute = function () {
  54648. var scene = this._actionManager.getScene();
  54649. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54650. };
  54651. /**
  54652. * Serializes the actions and its related information.
  54653. * @param parent defines the object to serialize in
  54654. * @returns the serialized object
  54655. */
  54656. PlayAnimationAction.prototype.serialize = function (parent) {
  54657. return _super.prototype._serialize.call(this, {
  54658. name: "PlayAnimationAction",
  54659. properties: [
  54660. BABYLON.Action._GetTargetProperty(this._target),
  54661. { name: "from", value: String(this.from) },
  54662. { name: "to", value: String(this.to) },
  54663. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54664. ]
  54665. }, parent);
  54666. };
  54667. return PlayAnimationAction;
  54668. }(BABYLON.Action));
  54669. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54670. /**
  54671. * This defines an action responsible to stop an animation once triggered.
  54672. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54673. */
  54674. var StopAnimationAction = /** @class */ (function (_super) {
  54675. __extends(StopAnimationAction, _super);
  54676. /**
  54677. * Instantiate the action
  54678. * @param triggerOptions defines the trigger options
  54679. * @param target defines the target animation or animation name
  54680. * @param condition defines the trigger related conditions
  54681. */
  54682. function StopAnimationAction(triggerOptions, target, condition) {
  54683. var _this = _super.call(this, triggerOptions, condition) || this;
  54684. _this._target = target;
  54685. return _this;
  54686. }
  54687. /** @hidden */
  54688. StopAnimationAction.prototype._prepare = function () {
  54689. };
  54690. /**
  54691. * Execute the action and stop the animation.
  54692. */
  54693. StopAnimationAction.prototype.execute = function () {
  54694. var scene = this._actionManager.getScene();
  54695. scene.stopAnimation(this._target);
  54696. };
  54697. /**
  54698. * Serializes the actions and its related information.
  54699. * @param parent defines the object to serialize in
  54700. * @returns the serialized object
  54701. */
  54702. StopAnimationAction.prototype.serialize = function (parent) {
  54703. return _super.prototype._serialize.call(this, {
  54704. name: "StopAnimationAction",
  54705. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54706. }, parent);
  54707. };
  54708. return StopAnimationAction;
  54709. }(BABYLON.Action));
  54710. BABYLON.StopAnimationAction = StopAnimationAction;
  54711. /**
  54712. * This defines an action responsible that does nothing once triggered.
  54713. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54714. */
  54715. var DoNothingAction = /** @class */ (function (_super) {
  54716. __extends(DoNothingAction, _super);
  54717. /**
  54718. * Instantiate the action
  54719. * @param triggerOptions defines the trigger options
  54720. * @param condition defines the trigger related conditions
  54721. */
  54722. function DoNothingAction(triggerOptions, condition) {
  54723. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54724. return _super.call(this, triggerOptions, condition) || this;
  54725. }
  54726. /**
  54727. * Execute the action and do nothing.
  54728. */
  54729. DoNothingAction.prototype.execute = function () {
  54730. };
  54731. /**
  54732. * Serializes the actions and its related information.
  54733. * @param parent defines the object to serialize in
  54734. * @returns the serialized object
  54735. */
  54736. DoNothingAction.prototype.serialize = function (parent) {
  54737. return _super.prototype._serialize.call(this, {
  54738. name: "DoNothingAction",
  54739. properties: []
  54740. }, parent);
  54741. };
  54742. return DoNothingAction;
  54743. }(BABYLON.Action));
  54744. BABYLON.DoNothingAction = DoNothingAction;
  54745. /**
  54746. * This defines an action responsible to trigger several actions once triggered.
  54747. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54748. */
  54749. var CombineAction = /** @class */ (function (_super) {
  54750. __extends(CombineAction, _super);
  54751. /**
  54752. * Instantiate the action
  54753. * @param triggerOptions defines the trigger options
  54754. * @param children defines the list of aggregated animations to run
  54755. * @param condition defines the trigger related conditions
  54756. */
  54757. function CombineAction(triggerOptions, children, condition) {
  54758. var _this = _super.call(this, triggerOptions, condition) || this;
  54759. _this.children = children;
  54760. return _this;
  54761. }
  54762. /** @hidden */
  54763. CombineAction.prototype._prepare = function () {
  54764. for (var index = 0; index < this.children.length; index++) {
  54765. this.children[index]._actionManager = this._actionManager;
  54766. this.children[index]._prepare();
  54767. }
  54768. };
  54769. /**
  54770. * Execute the action and executes all the aggregated actions.
  54771. */
  54772. CombineAction.prototype.execute = function (evt) {
  54773. for (var index = 0; index < this.children.length; index++) {
  54774. this.children[index].execute(evt);
  54775. }
  54776. };
  54777. /**
  54778. * Serializes the actions and its related information.
  54779. * @param parent defines the object to serialize in
  54780. * @returns the serialized object
  54781. */
  54782. CombineAction.prototype.serialize = function (parent) {
  54783. var serializationObject = _super.prototype._serialize.call(this, {
  54784. name: "CombineAction",
  54785. properties: [],
  54786. combine: []
  54787. }, parent);
  54788. for (var i = 0; i < this.children.length; i++) {
  54789. serializationObject.combine.push(this.children[i].serialize(null));
  54790. }
  54791. return serializationObject;
  54792. };
  54793. return CombineAction;
  54794. }(BABYLON.Action));
  54795. BABYLON.CombineAction = CombineAction;
  54796. /**
  54797. * This defines an action responsible to run code (external event) once triggered.
  54798. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54799. */
  54800. var ExecuteCodeAction = /** @class */ (function (_super) {
  54801. __extends(ExecuteCodeAction, _super);
  54802. /**
  54803. * Instantiate the action
  54804. * @param triggerOptions defines the trigger options
  54805. * @param func defines the callback function to run
  54806. * @param condition defines the trigger related conditions
  54807. */
  54808. function ExecuteCodeAction(triggerOptions, func, condition) {
  54809. var _this = _super.call(this, triggerOptions, condition) || this;
  54810. _this.func = func;
  54811. return _this;
  54812. }
  54813. /**
  54814. * Execute the action and run the attached code.
  54815. */
  54816. ExecuteCodeAction.prototype.execute = function (evt) {
  54817. this.func(evt);
  54818. };
  54819. return ExecuteCodeAction;
  54820. }(BABYLON.Action));
  54821. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54822. /**
  54823. * This defines an action responsible to set the parent property of the target once triggered.
  54824. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54825. */
  54826. var SetParentAction = /** @class */ (function (_super) {
  54827. __extends(SetParentAction, _super);
  54828. /**
  54829. * Instantiate the action
  54830. * @param triggerOptions defines the trigger options
  54831. * @param target defines the target containing the parent property
  54832. * @param parent defines from where the animation should start (animation frame)
  54833. * @param condition defines the trigger related conditions
  54834. */
  54835. function SetParentAction(triggerOptions, target, parent, condition) {
  54836. var _this = _super.call(this, triggerOptions, condition) || this;
  54837. _this._target = target;
  54838. _this._parent = parent;
  54839. return _this;
  54840. }
  54841. /** @hidden */
  54842. SetParentAction.prototype._prepare = function () {
  54843. };
  54844. /**
  54845. * Execute the action and set the parent property.
  54846. */
  54847. SetParentAction.prototype.execute = function () {
  54848. if (this._target.parent === this._parent) {
  54849. return;
  54850. }
  54851. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54852. invertParentWorldMatrix.invert();
  54853. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54854. this._target.parent = this._parent;
  54855. };
  54856. /**
  54857. * Serializes the actions and its related information.
  54858. * @param parent defines the object to serialize in
  54859. * @returns the serialized object
  54860. */
  54861. SetParentAction.prototype.serialize = function (parent) {
  54862. return _super.prototype._serialize.call(this, {
  54863. name: "SetParentAction",
  54864. properties: [
  54865. BABYLON.Action._GetTargetProperty(this._target),
  54866. BABYLON.Action._GetTargetProperty(this._parent),
  54867. ]
  54868. }, parent);
  54869. };
  54870. return SetParentAction;
  54871. }(BABYLON.Action));
  54872. BABYLON.SetParentAction = SetParentAction;
  54873. })(BABYLON || (BABYLON = {}));
  54874. //# sourceMappingURL=babylon.directActions.js.map
  54875. var BABYLON;
  54876. (function (BABYLON) {
  54877. var SpriteManager = /** @class */ (function () {
  54878. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54879. if (epsilon === void 0) { epsilon = 0.01; }
  54880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54881. this.name = name;
  54882. this.sprites = new Array();
  54883. this.renderingGroupId = 0;
  54884. this.layerMask = 0x0FFFFFFF;
  54885. this.fogEnabled = true;
  54886. this.isPickable = false;
  54887. /**
  54888. * An event triggered when the manager is disposed.
  54889. */
  54890. this.onDisposeObservable = new BABYLON.Observable();
  54891. this._vertexBuffers = {};
  54892. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54893. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54894. }
  54895. this._capacity = capacity;
  54896. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54897. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54898. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54899. if (cellSize.width && cellSize.height) {
  54900. this.cellWidth = cellSize.width;
  54901. this.cellHeight = cellSize.height;
  54902. }
  54903. else if (cellSize !== undefined) {
  54904. this.cellWidth = cellSize;
  54905. this.cellHeight = cellSize;
  54906. }
  54907. else {
  54908. return;
  54909. }
  54910. this._epsilon = epsilon;
  54911. this._scene = scene;
  54912. this._scene.spriteManagers.push(this);
  54913. var indices = [];
  54914. var index = 0;
  54915. for (var count = 0; count < capacity; count++) {
  54916. indices.push(index);
  54917. indices.push(index + 1);
  54918. indices.push(index + 2);
  54919. indices.push(index);
  54920. indices.push(index + 2);
  54921. indices.push(index + 3);
  54922. index += 4;
  54923. }
  54924. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54925. // VBO
  54926. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54927. this._vertexData = new Float32Array(capacity * 16 * 4);
  54928. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54929. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54930. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54931. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54932. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54934. this._vertexBuffers["options"] = options;
  54935. this._vertexBuffers["cellInfo"] = cellInfo;
  54936. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54937. // Effects
  54938. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54939. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54940. }
  54941. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54942. set: function (callback) {
  54943. if (this._onDisposeObserver) {
  54944. this.onDisposeObservable.remove(this._onDisposeObserver);
  54945. }
  54946. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54947. },
  54948. enumerable: true,
  54949. configurable: true
  54950. });
  54951. Object.defineProperty(SpriteManager.prototype, "texture", {
  54952. get: function () {
  54953. return this._spriteTexture;
  54954. },
  54955. set: function (value) {
  54956. this._spriteTexture = value;
  54957. },
  54958. enumerable: true,
  54959. configurable: true
  54960. });
  54961. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54962. var arrayOffset = index * 16;
  54963. if (offsetX === 0)
  54964. offsetX = this._epsilon;
  54965. else if (offsetX === 1)
  54966. offsetX = 1 - this._epsilon;
  54967. if (offsetY === 0)
  54968. offsetY = this._epsilon;
  54969. else if (offsetY === 1)
  54970. offsetY = 1 - this._epsilon;
  54971. this._vertexData[arrayOffset] = sprite.position.x;
  54972. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54973. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54974. this._vertexData[arrayOffset + 3] = sprite.angle;
  54975. this._vertexData[arrayOffset + 4] = sprite.width;
  54976. this._vertexData[arrayOffset + 5] = sprite.height;
  54977. this._vertexData[arrayOffset + 6] = offsetX;
  54978. this._vertexData[arrayOffset + 7] = offsetY;
  54979. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54980. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54981. var offset = (sprite.cellIndex / rowSize) >> 0;
  54982. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54983. this._vertexData[arrayOffset + 11] = offset;
  54984. // Color
  54985. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54986. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54987. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54988. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54989. };
  54990. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54991. var count = Math.min(this._capacity, this.sprites.length);
  54992. var min = BABYLON.Vector3.Zero();
  54993. var max = BABYLON.Vector3.Zero();
  54994. var distance = Number.MAX_VALUE;
  54995. var currentSprite = null;
  54996. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54997. var cameraView = camera.getViewMatrix();
  54998. for (var index = 0; index < count; index++) {
  54999. var sprite = this.sprites[index];
  55000. if (!sprite) {
  55001. continue;
  55002. }
  55003. if (predicate) {
  55004. if (!predicate(sprite)) {
  55005. continue;
  55006. }
  55007. }
  55008. else if (!sprite.isPickable) {
  55009. continue;
  55010. }
  55011. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55012. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55013. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55014. if (ray.intersectsBoxMinMax(min, max)) {
  55015. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55016. if (distance > currentDistance) {
  55017. distance = currentDistance;
  55018. currentSprite = sprite;
  55019. if (fastCheck) {
  55020. break;
  55021. }
  55022. }
  55023. }
  55024. }
  55025. if (currentSprite) {
  55026. var result = new BABYLON.PickingInfo();
  55027. result.hit = true;
  55028. result.pickedSprite = currentSprite;
  55029. result.distance = distance;
  55030. return result;
  55031. }
  55032. return null;
  55033. };
  55034. SpriteManager.prototype.render = function () {
  55035. // Check
  55036. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55037. return;
  55038. var engine = this._scene.getEngine();
  55039. var baseSize = this._spriteTexture.getBaseSize();
  55040. // Sprites
  55041. var deltaTime = engine.getDeltaTime();
  55042. var max = Math.min(this._capacity, this.sprites.length);
  55043. var rowSize = baseSize.width / this.cellWidth;
  55044. var offset = 0;
  55045. for (var index = 0; index < max; index++) {
  55046. var sprite = this.sprites[index];
  55047. if (!sprite || !sprite.isVisible) {
  55048. continue;
  55049. }
  55050. sprite._animate(deltaTime);
  55051. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55052. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55053. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55054. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55055. }
  55056. this._buffer.update(this._vertexData);
  55057. // Render
  55058. var effect = this._effectBase;
  55059. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55060. effect = this._effectFog;
  55061. }
  55062. engine.enableEffect(effect);
  55063. var viewMatrix = this._scene.getViewMatrix();
  55064. effect.setTexture("diffuseSampler", this._spriteTexture);
  55065. effect.setMatrix("view", viewMatrix);
  55066. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55067. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55068. // Fog
  55069. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55070. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55071. effect.setColor3("vFogColor", this._scene.fogColor);
  55072. }
  55073. // VBOs
  55074. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55075. // Draw order
  55076. engine.setDepthFunctionToLessOrEqual();
  55077. effect.setBool("alphaTest", true);
  55078. engine.setColorWrite(false);
  55079. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55080. engine.setColorWrite(true);
  55081. effect.setBool("alphaTest", false);
  55082. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55083. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55084. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55085. };
  55086. SpriteManager.prototype.dispose = function () {
  55087. if (this._buffer) {
  55088. this._buffer.dispose();
  55089. this._buffer = null;
  55090. }
  55091. if (this._indexBuffer) {
  55092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55093. this._indexBuffer = null;
  55094. }
  55095. if (this._spriteTexture) {
  55096. this._spriteTexture.dispose();
  55097. this._spriteTexture = null;
  55098. }
  55099. // Remove from scene
  55100. var index = this._scene.spriteManagers.indexOf(this);
  55101. this._scene.spriteManagers.splice(index, 1);
  55102. // Callback
  55103. this.onDisposeObservable.notifyObservers(this);
  55104. this.onDisposeObservable.clear();
  55105. };
  55106. return SpriteManager;
  55107. }());
  55108. BABYLON.SpriteManager = SpriteManager;
  55109. })(BABYLON || (BABYLON = {}));
  55110. //# sourceMappingURL=babylon.spriteManager.js.map
  55111. var BABYLON;
  55112. (function (BABYLON) {
  55113. var Sprite = /** @class */ (function () {
  55114. function Sprite(name, manager) {
  55115. this.name = name;
  55116. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55117. this.width = 1.0;
  55118. this.height = 1.0;
  55119. this.angle = 0;
  55120. this.cellIndex = 0;
  55121. this.invertU = 0;
  55122. this.invertV = 0;
  55123. this.animations = new Array();
  55124. this.isPickable = false;
  55125. this._animationStarted = false;
  55126. this._loopAnimation = false;
  55127. this._fromIndex = 0;
  55128. this._toIndex = 0;
  55129. this._delay = 0;
  55130. this._direction = 1;
  55131. this._time = 0;
  55132. /**
  55133. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55134. */
  55135. this.isVisible = true;
  55136. this._manager = manager;
  55137. this._manager.sprites.push(this);
  55138. this.position = BABYLON.Vector3.Zero();
  55139. }
  55140. Object.defineProperty(Sprite.prototype, "size", {
  55141. get: function () {
  55142. return this.width;
  55143. },
  55144. set: function (value) {
  55145. this.width = value;
  55146. this.height = value;
  55147. },
  55148. enumerable: true,
  55149. configurable: true
  55150. });
  55151. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55152. this._fromIndex = from;
  55153. this._toIndex = to;
  55154. this._loopAnimation = loop;
  55155. this._delay = delay;
  55156. this._animationStarted = true;
  55157. this._direction = from < to ? 1 : -1;
  55158. this.cellIndex = from;
  55159. this._time = 0;
  55160. this._onAnimationEnd = onAnimationEnd;
  55161. };
  55162. Sprite.prototype.stopAnimation = function () {
  55163. this._animationStarted = false;
  55164. };
  55165. /** @hidden */
  55166. Sprite.prototype._animate = function (deltaTime) {
  55167. if (!this._animationStarted)
  55168. return;
  55169. this._time += deltaTime;
  55170. if (this._time > this._delay) {
  55171. this._time = this._time % this._delay;
  55172. this.cellIndex += this._direction;
  55173. if (this.cellIndex > this._toIndex) {
  55174. if (this._loopAnimation) {
  55175. this.cellIndex = this._fromIndex;
  55176. }
  55177. else {
  55178. this.cellIndex = this._toIndex;
  55179. this._animationStarted = false;
  55180. if (this._onAnimationEnd) {
  55181. this._onAnimationEnd();
  55182. }
  55183. if (this.disposeWhenFinishedAnimating) {
  55184. this.dispose();
  55185. }
  55186. }
  55187. }
  55188. }
  55189. };
  55190. Sprite.prototype.dispose = function () {
  55191. for (var i = 0; i < this._manager.sprites.length; i++) {
  55192. if (this._manager.sprites[i] == this) {
  55193. this._manager.sprites.splice(i, 1);
  55194. }
  55195. }
  55196. };
  55197. return Sprite;
  55198. }());
  55199. BABYLON.Sprite = Sprite;
  55200. })(BABYLON || (BABYLON = {}));
  55201. //# sourceMappingURL=babylon.sprite.js.map
  55202. var BABYLON;
  55203. (function (BABYLON) {
  55204. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55205. if (!BABYLON.PickingInfo) {
  55206. return null;
  55207. }
  55208. var pickingInfo = null;
  55209. if (!camera) {
  55210. if (!this.activeCamera) {
  55211. return null;
  55212. }
  55213. camera = this.activeCamera;
  55214. }
  55215. if (this.spriteManagers.length > 0) {
  55216. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55217. var spriteManager = this.spriteManagers[spriteIndex];
  55218. if (!spriteManager.isPickable) {
  55219. continue;
  55220. }
  55221. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55222. if (!result || !result.hit)
  55223. continue;
  55224. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55225. continue;
  55226. pickingInfo = result;
  55227. if (fastCheck) {
  55228. break;
  55229. }
  55230. }
  55231. }
  55232. return pickingInfo || new BABYLON.PickingInfo();
  55233. };
  55234. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55235. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55236. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55237. };
  55238. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55239. if (!this._tempSpritePickingRay) {
  55240. return null;
  55241. }
  55242. if (!camera) {
  55243. if (!this.activeCamera) {
  55244. return null;
  55245. }
  55246. camera = this.activeCamera;
  55247. }
  55248. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55249. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55250. };
  55251. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55252. if (this._pointerOverSprite === sprite) {
  55253. return;
  55254. }
  55255. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55256. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55257. }
  55258. this._pointerOverSprite = sprite;
  55259. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55260. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55261. }
  55262. };
  55263. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55264. return this._pointerOverSprite;
  55265. };
  55266. /**
  55267. * Defines the sprite scene component responsible to manage sprites
  55268. * in a given scene.
  55269. */
  55270. var SpriteSceneComponent = /** @class */ (function () {
  55271. /**
  55272. * Creates a new instance of the component for the given scene
  55273. * @param scene Defines the scene to register the component in
  55274. */
  55275. function SpriteSceneComponent(scene) {
  55276. /**
  55277. * The component name helpfull to identify the component in the list of scene components.
  55278. */
  55279. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55280. this.scene = scene;
  55281. this.scene.spriteManagers = new Array();
  55282. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55283. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55284. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55285. this._spritePredicate = function (sprite) {
  55286. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55287. };
  55288. }
  55289. /**
  55290. * Registers the component in a given scene
  55291. */
  55292. SpriteSceneComponent.prototype.register = function () {
  55293. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55294. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55295. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55296. };
  55297. /**
  55298. * Rebuilds the elements related to this component in case of
  55299. * context lost for instance.
  55300. */
  55301. SpriteSceneComponent.prototype.rebuild = function () {
  55302. /** Nothing to do for sprites */
  55303. };
  55304. /**
  55305. * Disposes the component and the associated ressources.
  55306. */
  55307. SpriteSceneComponent.prototype.dispose = function () {
  55308. this.scene.onBeforeSpritesRenderingObservable.clear();
  55309. this.scene.onAfterSpritesRenderingObservable.clear();
  55310. var spriteManagers = this.scene.spriteManagers;
  55311. while (spriteManagers.length) {
  55312. spriteManagers[0].dispose();
  55313. }
  55314. };
  55315. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55316. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55317. if (result) {
  55318. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55319. }
  55320. return result;
  55321. };
  55322. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55323. var scene = this.scene;
  55324. if (isMeshPicked) {
  55325. scene.setPointerOverSprite(null);
  55326. }
  55327. else {
  55328. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55329. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55330. scene.setPointerOverSprite(pickResult.pickedSprite);
  55331. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55332. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55333. }
  55334. else {
  55335. canvas.style.cursor = scene.hoverCursor;
  55336. }
  55337. }
  55338. else {
  55339. scene.setPointerOverSprite(null);
  55340. }
  55341. }
  55342. return pickResult;
  55343. };
  55344. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55345. var scene = this.scene;
  55346. scene._pickedDownSprite = null;
  55347. if (scene.spriteManagers.length > 0) {
  55348. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55349. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55350. if (pickResult.pickedSprite.actionManager) {
  55351. scene._pickedDownSprite = pickResult.pickedSprite;
  55352. switch (evt.button) {
  55353. case 0:
  55354. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55355. break;
  55356. case 1:
  55357. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55358. break;
  55359. case 2:
  55360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55361. break;
  55362. }
  55363. if (pickResult.pickedSprite.actionManager) {
  55364. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55365. }
  55366. }
  55367. }
  55368. }
  55369. return pickResult;
  55370. };
  55371. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55372. var scene = this.scene;
  55373. if (scene.spriteManagers.length > 0) {
  55374. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55375. if (spritePickResult) {
  55376. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55377. if (spritePickResult.pickedSprite.actionManager) {
  55378. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55379. if (spritePickResult.pickedSprite.actionManager) {
  55380. if (!this.scene._isPointerSwiping()) {
  55381. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55382. }
  55383. }
  55384. }
  55385. }
  55386. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55387. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55388. }
  55389. }
  55390. }
  55391. return pickResult;
  55392. };
  55393. return SpriteSceneComponent;
  55394. }());
  55395. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55396. })(BABYLON || (BABYLON = {}));
  55397. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55398. var BABYLON;
  55399. (function (BABYLON) {
  55400. /**
  55401. * @hidden
  55402. */
  55403. var IntersectionInfo = /** @class */ (function () {
  55404. function IntersectionInfo(bu, bv, distance) {
  55405. this.bu = bu;
  55406. this.bv = bv;
  55407. this.distance = distance;
  55408. this.faceId = 0;
  55409. this.subMeshId = 0;
  55410. }
  55411. return IntersectionInfo;
  55412. }());
  55413. BABYLON.IntersectionInfo = IntersectionInfo;
  55414. /**
  55415. * Information about the result of picking within a scene
  55416. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55417. */
  55418. var PickingInfo = /** @class */ (function () {
  55419. function PickingInfo() {
  55420. /**
  55421. * If the pick collided with an object
  55422. */
  55423. this.hit = false;
  55424. /**
  55425. * Distance away where the pick collided
  55426. */
  55427. this.distance = 0;
  55428. /**
  55429. * The location of pick collision
  55430. */
  55431. this.pickedPoint = null;
  55432. /**
  55433. * The mesh corresponding the the pick collision
  55434. */
  55435. this.pickedMesh = null;
  55436. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55437. this.bu = 0;
  55438. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55439. this.bv = 0;
  55440. /** The id of the face on the mesh that was picked */
  55441. this.faceId = -1;
  55442. /** Id of the the submesh that was picked */
  55443. this.subMeshId = 0;
  55444. /** If a sprite was picked, this will be the sprite the pick collided with */
  55445. this.pickedSprite = null;
  55446. /**
  55447. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55448. */
  55449. this.originMesh = null;
  55450. /**
  55451. * The ray that was used to perform the picking.
  55452. */
  55453. this.ray = null;
  55454. }
  55455. /**
  55456. * Gets the normal correspodning to the face the pick collided with
  55457. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55458. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55459. * @returns The normal correspodning to the face the pick collided with
  55460. */
  55461. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55462. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55463. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55464. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55465. return null;
  55466. }
  55467. var indices = this.pickedMesh.getIndices();
  55468. if (!indices) {
  55469. return null;
  55470. }
  55471. var result;
  55472. if (useVerticesNormals) {
  55473. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55474. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55475. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55476. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55477. normal0 = normal0.scale(this.bu);
  55478. normal1 = normal1.scale(this.bv);
  55479. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55480. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55481. }
  55482. else {
  55483. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55484. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55485. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55486. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55487. var p1p2 = vertex1.subtract(vertex2);
  55488. var p3p2 = vertex3.subtract(vertex2);
  55489. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55490. }
  55491. if (useWorldCoordinates) {
  55492. var wm = this.pickedMesh.getWorldMatrix();
  55493. if (this.pickedMesh.nonUniformScaling) {
  55494. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55495. wm = BABYLON.Tmp.Matrix[0];
  55496. wm.setTranslationFromFloats(0, 0, 0);
  55497. wm.invert();
  55498. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55499. wm = BABYLON.Tmp.Matrix[1];
  55500. }
  55501. result = BABYLON.Vector3.TransformNormal(result, wm);
  55502. }
  55503. result.normalize();
  55504. return result;
  55505. };
  55506. /**
  55507. * Gets the texture coordinates of where the pick occured
  55508. * @returns the vector containing the coordnates of the texture
  55509. */
  55510. PickingInfo.prototype.getTextureCoordinates = function () {
  55511. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55512. return null;
  55513. }
  55514. var indices = this.pickedMesh.getIndices();
  55515. if (!indices) {
  55516. return null;
  55517. }
  55518. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55519. if (!uvs) {
  55520. return null;
  55521. }
  55522. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55523. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55524. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55525. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55526. uv1 = uv1.scale(this.bu);
  55527. uv2 = uv2.scale(this.bv);
  55528. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55529. };
  55530. return PickingInfo;
  55531. }());
  55532. BABYLON.PickingInfo = PickingInfo;
  55533. })(BABYLON || (BABYLON = {}));
  55534. //# sourceMappingURL=babylon.pickingInfo.js.map
  55535. var BABYLON;
  55536. (function (BABYLON) {
  55537. var Ray = /** @class */ (function () {
  55538. function Ray(origin, direction, length) {
  55539. if (length === void 0) { length = Number.MAX_VALUE; }
  55540. this.origin = origin;
  55541. this.direction = direction;
  55542. this.length = length;
  55543. }
  55544. // Methods
  55545. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55546. var d = 0.0;
  55547. var maxValue = Number.MAX_VALUE;
  55548. var inv;
  55549. var min;
  55550. var max;
  55551. var temp;
  55552. if (Math.abs(this.direction.x) < 0.0000001) {
  55553. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55554. return false;
  55555. }
  55556. }
  55557. else {
  55558. inv = 1.0 / this.direction.x;
  55559. min = (minimum.x - this.origin.x) * inv;
  55560. max = (maximum.x - this.origin.x) * inv;
  55561. if (max === -Infinity) {
  55562. max = Infinity;
  55563. }
  55564. if (min > max) {
  55565. temp = min;
  55566. min = max;
  55567. max = temp;
  55568. }
  55569. d = Math.max(min, d);
  55570. maxValue = Math.min(max, maxValue);
  55571. if (d > maxValue) {
  55572. return false;
  55573. }
  55574. }
  55575. if (Math.abs(this.direction.y) < 0.0000001) {
  55576. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55577. return false;
  55578. }
  55579. }
  55580. else {
  55581. inv = 1.0 / this.direction.y;
  55582. min = (minimum.y - this.origin.y) * inv;
  55583. max = (maximum.y - this.origin.y) * inv;
  55584. if (max === -Infinity) {
  55585. max = Infinity;
  55586. }
  55587. if (min > max) {
  55588. temp = min;
  55589. min = max;
  55590. max = temp;
  55591. }
  55592. d = Math.max(min, d);
  55593. maxValue = Math.min(max, maxValue);
  55594. if (d > maxValue) {
  55595. return false;
  55596. }
  55597. }
  55598. if (Math.abs(this.direction.z) < 0.0000001) {
  55599. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55600. return false;
  55601. }
  55602. }
  55603. else {
  55604. inv = 1.0 / this.direction.z;
  55605. min = (minimum.z - this.origin.z) * inv;
  55606. max = (maximum.z - this.origin.z) * inv;
  55607. if (max === -Infinity) {
  55608. max = Infinity;
  55609. }
  55610. if (min > max) {
  55611. temp = min;
  55612. min = max;
  55613. max = temp;
  55614. }
  55615. d = Math.max(min, d);
  55616. maxValue = Math.min(max, maxValue);
  55617. if (d > maxValue) {
  55618. return false;
  55619. }
  55620. }
  55621. return true;
  55622. };
  55623. Ray.prototype.intersectsBox = function (box) {
  55624. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55625. };
  55626. Ray.prototype.intersectsSphere = function (sphere) {
  55627. var x = sphere.center.x - this.origin.x;
  55628. var y = sphere.center.y - this.origin.y;
  55629. var z = sphere.center.z - this.origin.z;
  55630. var pyth = (x * x) + (y * y) + (z * z);
  55631. var rr = sphere.radius * sphere.radius;
  55632. if (pyth <= rr) {
  55633. return true;
  55634. }
  55635. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55636. if (dot < 0.0) {
  55637. return false;
  55638. }
  55639. var temp = pyth - (dot * dot);
  55640. return temp <= rr;
  55641. };
  55642. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55643. if (!this._edge1) {
  55644. this._edge1 = BABYLON.Vector3.Zero();
  55645. this._edge2 = BABYLON.Vector3.Zero();
  55646. this._pvec = BABYLON.Vector3.Zero();
  55647. this._tvec = BABYLON.Vector3.Zero();
  55648. this._qvec = BABYLON.Vector3.Zero();
  55649. }
  55650. vertex1.subtractToRef(vertex0, this._edge1);
  55651. vertex2.subtractToRef(vertex0, this._edge2);
  55652. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55653. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55654. if (det === 0) {
  55655. return null;
  55656. }
  55657. var invdet = 1 / det;
  55658. this.origin.subtractToRef(vertex0, this._tvec);
  55659. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55660. if (bu < 0 || bu > 1.0) {
  55661. return null;
  55662. }
  55663. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55664. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55665. if (bv < 0 || bu + bv > 1.0) {
  55666. return null;
  55667. }
  55668. //check if the distance is longer than the predefined length.
  55669. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55670. if (distance > this.length) {
  55671. return null;
  55672. }
  55673. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55674. };
  55675. Ray.prototype.intersectsPlane = function (plane) {
  55676. var distance;
  55677. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55678. if (Math.abs(result1) < 9.99999997475243E-07) {
  55679. return null;
  55680. }
  55681. else {
  55682. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55683. distance = (-plane.d - result2) / result1;
  55684. if (distance < 0.0) {
  55685. if (distance < -9.99999997475243E-07) {
  55686. return null;
  55687. }
  55688. else {
  55689. return 0;
  55690. }
  55691. }
  55692. return distance;
  55693. }
  55694. };
  55695. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55696. var tm = BABYLON.Tmp.Matrix[0];
  55697. mesh.getWorldMatrix().invertToRef(tm);
  55698. if (this._tmpRay) {
  55699. Ray.TransformToRef(this, tm, this._tmpRay);
  55700. }
  55701. else {
  55702. this._tmpRay = Ray.Transform(this, tm);
  55703. }
  55704. return mesh.intersects(this._tmpRay, fastCheck);
  55705. };
  55706. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55707. if (results) {
  55708. results.length = 0;
  55709. }
  55710. else {
  55711. results = [];
  55712. }
  55713. for (var i = 0; i < meshes.length; i++) {
  55714. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55715. if (pickInfo.hit) {
  55716. results.push(pickInfo);
  55717. }
  55718. }
  55719. results.sort(this._comparePickingInfo);
  55720. return results;
  55721. };
  55722. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55723. if (pickingInfoA.distance < pickingInfoB.distance) {
  55724. return -1;
  55725. }
  55726. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55727. return 1;
  55728. }
  55729. else {
  55730. return 0;
  55731. }
  55732. };
  55733. /**
  55734. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55735. * @param sega the first point of the segment to test the intersection against
  55736. * @param segb the second point of the segment to test the intersection against
  55737. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55738. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55739. */
  55740. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55741. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55742. var u = segb.subtract(sega);
  55743. var v = rsegb.subtract(this.origin);
  55744. var w = sega.subtract(this.origin);
  55745. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55746. var b = BABYLON.Vector3.Dot(u, v);
  55747. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55748. var d = BABYLON.Vector3.Dot(u, w);
  55749. var e = BABYLON.Vector3.Dot(v, w);
  55750. var D = a * c - b * b; // always >= 0
  55751. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55752. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55753. // compute the line parameters of the two closest points
  55754. if (D < Ray.smallnum) { // the lines are almost parallel
  55755. sN = 0.0; // force using point P0 on segment S1
  55756. sD = 1.0; // to prevent possible division by 0.0 later
  55757. tN = e;
  55758. tD = c;
  55759. }
  55760. else { // get the closest points on the infinite lines
  55761. sN = (b * e - c * d);
  55762. tN = (a * e - b * d);
  55763. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55764. sN = 0.0;
  55765. tN = e;
  55766. tD = c;
  55767. }
  55768. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55769. sN = sD;
  55770. tN = e + b;
  55771. tD = c;
  55772. }
  55773. }
  55774. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55775. tN = 0.0;
  55776. // recompute sc for this edge
  55777. if (-d < 0.0) {
  55778. sN = 0.0;
  55779. }
  55780. else if (-d > a)
  55781. sN = sD;
  55782. else {
  55783. sN = -d;
  55784. sD = a;
  55785. }
  55786. }
  55787. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55788. tN = tD;
  55789. // recompute sc for this edge
  55790. if ((-d + b) < 0.0) {
  55791. sN = 0;
  55792. }
  55793. else if ((-d + b) > a) {
  55794. sN = sD;
  55795. }
  55796. else {
  55797. sN = (-d + b);
  55798. sD = a;
  55799. }
  55800. }
  55801. // finally do the division to get sc and tc
  55802. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55803. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55804. // get the difference of the two closest points
  55805. var qtc = v.multiplyByFloats(tc, tc, tc);
  55806. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55807. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55808. if (isIntersected) {
  55809. return qtc.length();
  55810. }
  55811. return -1;
  55812. };
  55813. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55814. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55815. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55816. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55817. this.direction.normalize();
  55818. return this;
  55819. };
  55820. // Statics
  55821. Ray.Zero = function () {
  55822. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55823. };
  55824. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55825. var result = Ray.Zero();
  55826. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55827. };
  55828. /**
  55829. * 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
  55830. * transformed to the given world matrix.
  55831. * @param origin The origin point
  55832. * @param end The end point
  55833. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55834. */
  55835. Ray.CreateNewFromTo = function (origin, end, world) {
  55836. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55837. var direction = end.subtract(origin);
  55838. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55839. direction.normalize();
  55840. return Ray.Transform(new Ray(origin, direction, length), world);
  55841. };
  55842. Ray.Transform = function (ray, matrix) {
  55843. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55844. Ray.TransformToRef(ray, matrix, result);
  55845. return result;
  55846. };
  55847. Ray.TransformToRef = function (ray, matrix, result) {
  55848. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55849. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55850. result.length = ray.length;
  55851. var dir = result.direction;
  55852. var len = dir.length();
  55853. if (!(len === 0 || len === 1)) {
  55854. var num = 1.0 / len;
  55855. dir.x *= num;
  55856. dir.y *= num;
  55857. dir.z *= num;
  55858. result.length *= len;
  55859. }
  55860. };
  55861. Ray.smallnum = 0.00000001;
  55862. Ray.rayl = 10e8;
  55863. return Ray;
  55864. }());
  55865. BABYLON.Ray = Ray;
  55866. })(BABYLON || (BABYLON = {}));
  55867. //# sourceMappingURL=babylon.ray.js.map
  55868. var BABYLON;
  55869. (function (BABYLON) {
  55870. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55871. if (boxMin.x > sphereCenter.x + sphereRadius)
  55872. return false;
  55873. if (sphereCenter.x - sphereRadius > boxMax.x)
  55874. return false;
  55875. if (boxMin.y > sphereCenter.y + sphereRadius)
  55876. return false;
  55877. if (sphereCenter.y - sphereRadius > boxMax.y)
  55878. return false;
  55879. if (boxMin.z > sphereCenter.z + sphereRadius)
  55880. return false;
  55881. if (sphereCenter.z - sphereRadius > boxMax.z)
  55882. return false;
  55883. return true;
  55884. };
  55885. var getLowestRoot = (function () {
  55886. var result = { root: 0, found: false };
  55887. return function (a, b, c, maxR) {
  55888. result.root = 0;
  55889. result.found = false;
  55890. var determinant = b * b - 4.0 * a * c;
  55891. if (determinant < 0)
  55892. return result;
  55893. var sqrtD = Math.sqrt(determinant);
  55894. var r1 = (-b - sqrtD) / (2.0 * a);
  55895. var r2 = (-b + sqrtD) / (2.0 * a);
  55896. if (r1 > r2) {
  55897. var temp = r2;
  55898. r2 = r1;
  55899. r1 = temp;
  55900. }
  55901. if (r1 > 0 && r1 < maxR) {
  55902. result.root = r1;
  55903. result.found = true;
  55904. return result;
  55905. }
  55906. if (r2 > 0 && r2 < maxR) {
  55907. result.root = r2;
  55908. result.found = true;
  55909. return result;
  55910. }
  55911. return result;
  55912. };
  55913. })();
  55914. /** @hidden */
  55915. var Collider = /** @class */ (function () {
  55916. function Collider() {
  55917. this._collisionPoint = BABYLON.Vector3.Zero();
  55918. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55919. this._tempVector = BABYLON.Vector3.Zero();
  55920. this._tempVector2 = BABYLON.Vector3.Zero();
  55921. this._tempVector3 = BABYLON.Vector3.Zero();
  55922. this._tempVector4 = BABYLON.Vector3.Zero();
  55923. this._edge = BABYLON.Vector3.Zero();
  55924. this._baseToVertex = BABYLON.Vector3.Zero();
  55925. this._destinationPoint = BABYLON.Vector3.Zero();
  55926. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55927. this._displacementVector = BABYLON.Vector3.Zero();
  55928. /** @hidden */
  55929. this._radius = BABYLON.Vector3.One();
  55930. /** @hidden */
  55931. this._retry = 0;
  55932. /** @hidden */
  55933. this._basePointWorld = BABYLON.Vector3.Zero();
  55934. this._velocityWorld = BABYLON.Vector3.Zero();
  55935. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55936. this._collisionMask = -1;
  55937. }
  55938. Object.defineProperty(Collider.prototype, "collisionMask", {
  55939. get: function () {
  55940. return this._collisionMask;
  55941. },
  55942. set: function (mask) {
  55943. this._collisionMask = !isNaN(mask) ? mask : -1;
  55944. },
  55945. enumerable: true,
  55946. configurable: true
  55947. });
  55948. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55949. /**
  55950. * Gets the plane normal used to compute the sliding response (in local space)
  55951. */
  55952. get: function () {
  55953. return this._slidePlaneNormal;
  55954. },
  55955. enumerable: true,
  55956. configurable: true
  55957. });
  55958. // Methods
  55959. /** @hidden */
  55960. Collider.prototype._initialize = function (source, dir, e) {
  55961. this._velocity = dir;
  55962. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55963. this._basePoint = source;
  55964. source.multiplyToRef(this._radius, this._basePointWorld);
  55965. dir.multiplyToRef(this._radius, this._velocityWorld);
  55966. this._velocityWorldLength = this._velocityWorld.length();
  55967. this._epsilon = e;
  55968. this.collisionFound = false;
  55969. };
  55970. /** @hidden */
  55971. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55972. pa.subtractToRef(point, this._tempVector);
  55973. pb.subtractToRef(point, this._tempVector2);
  55974. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55975. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55976. if (d < 0)
  55977. return false;
  55978. pc.subtractToRef(point, this._tempVector3);
  55979. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55980. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55981. if (d < 0)
  55982. return false;
  55983. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55984. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55985. return d >= 0;
  55986. };
  55987. /** @hidden */
  55988. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55989. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55990. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55991. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55992. return false;
  55993. }
  55994. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55995. return false;
  55996. return true;
  55997. };
  55998. /** @hidden */
  55999. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56000. var t0;
  56001. var embeddedInPlane = false;
  56002. //defensive programming, actually not needed.
  56003. if (!trianglePlaneArray) {
  56004. trianglePlaneArray = [];
  56005. }
  56006. if (!trianglePlaneArray[faceIndex]) {
  56007. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56008. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56009. }
  56010. var trianglePlane = trianglePlaneArray[faceIndex];
  56011. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56012. return;
  56013. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56014. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56015. if (normalDotVelocity == 0) {
  56016. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56017. return;
  56018. embeddedInPlane = true;
  56019. t0 = 0;
  56020. }
  56021. else {
  56022. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56023. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56024. if (t0 > t1) {
  56025. var temp = t1;
  56026. t1 = t0;
  56027. t0 = temp;
  56028. }
  56029. if (t0 > 1.0 || t1 < 0.0)
  56030. return;
  56031. if (t0 < 0)
  56032. t0 = 0;
  56033. if (t0 > 1.0)
  56034. t0 = 1.0;
  56035. }
  56036. this._collisionPoint.copyFromFloats(0, 0, 0);
  56037. var found = false;
  56038. var t = 1.0;
  56039. if (!embeddedInPlane) {
  56040. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56041. this._velocity.scaleToRef(t0, this._tempVector);
  56042. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56043. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56044. found = true;
  56045. t = t0;
  56046. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56047. }
  56048. }
  56049. if (!found) {
  56050. var velocitySquaredLength = this._velocity.lengthSquared();
  56051. var a = velocitySquaredLength;
  56052. this._basePoint.subtractToRef(p1, this._tempVector);
  56053. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56054. var c = this._tempVector.lengthSquared() - 1.0;
  56055. var lowestRoot = getLowestRoot(a, b, c, t);
  56056. if (lowestRoot.found) {
  56057. t = lowestRoot.root;
  56058. found = true;
  56059. this._collisionPoint.copyFrom(p1);
  56060. }
  56061. this._basePoint.subtractToRef(p2, this._tempVector);
  56062. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56063. c = this._tempVector.lengthSquared() - 1.0;
  56064. lowestRoot = getLowestRoot(a, b, c, t);
  56065. if (lowestRoot.found) {
  56066. t = lowestRoot.root;
  56067. found = true;
  56068. this._collisionPoint.copyFrom(p2);
  56069. }
  56070. this._basePoint.subtractToRef(p3, this._tempVector);
  56071. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56072. c = this._tempVector.lengthSquared() - 1.0;
  56073. lowestRoot = getLowestRoot(a, b, c, t);
  56074. if (lowestRoot.found) {
  56075. t = lowestRoot.root;
  56076. found = true;
  56077. this._collisionPoint.copyFrom(p3);
  56078. }
  56079. p2.subtractToRef(p1, this._edge);
  56080. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56081. var edgeSquaredLength = this._edge.lengthSquared();
  56082. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56083. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56084. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56085. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56086. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56087. lowestRoot = getLowestRoot(a, b, c, t);
  56088. if (lowestRoot.found) {
  56089. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56090. if (f >= 0.0 && f <= 1.0) {
  56091. t = lowestRoot.root;
  56092. found = true;
  56093. this._edge.scaleInPlace(f);
  56094. p1.addToRef(this._edge, this._collisionPoint);
  56095. }
  56096. }
  56097. p3.subtractToRef(p2, this._edge);
  56098. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56099. edgeSquaredLength = this._edge.lengthSquared();
  56100. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56101. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56102. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56103. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56104. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56105. lowestRoot = getLowestRoot(a, b, c, t);
  56106. if (lowestRoot.found) {
  56107. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56108. if (f >= 0.0 && f <= 1.0) {
  56109. t = lowestRoot.root;
  56110. found = true;
  56111. this._edge.scaleInPlace(f);
  56112. p2.addToRef(this._edge, this._collisionPoint);
  56113. }
  56114. }
  56115. p1.subtractToRef(p3, this._edge);
  56116. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56117. edgeSquaredLength = this._edge.lengthSquared();
  56118. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56119. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56120. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56121. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56122. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56123. lowestRoot = getLowestRoot(a, b, c, t);
  56124. if (lowestRoot.found) {
  56125. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56126. if (f >= 0.0 && f <= 1.0) {
  56127. t = lowestRoot.root;
  56128. found = true;
  56129. this._edge.scaleInPlace(f);
  56130. p3.addToRef(this._edge, this._collisionPoint);
  56131. }
  56132. }
  56133. }
  56134. if (found) {
  56135. var distToCollision = t * this._velocity.length();
  56136. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56137. if (!this.intersectionPoint) {
  56138. this.intersectionPoint = this._collisionPoint.clone();
  56139. }
  56140. else {
  56141. this.intersectionPoint.copyFrom(this._collisionPoint);
  56142. }
  56143. this._nearestDistance = distToCollision;
  56144. this.collisionFound = true;
  56145. }
  56146. }
  56147. };
  56148. /** @hidden */
  56149. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56150. for (var i = indexStart; i < indexEnd; i += 3) {
  56151. var p1 = pts[indices[i] - decal];
  56152. var p2 = pts[indices[i + 1] - decal];
  56153. var p3 = pts[indices[i + 2] - decal];
  56154. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56155. }
  56156. };
  56157. /** @hidden */
  56158. Collider.prototype._getResponse = function (pos, vel) {
  56159. pos.addToRef(vel, this._destinationPoint);
  56160. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56161. this._basePoint.addToRef(vel, pos);
  56162. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56163. this._slidePlaneNormal.normalize();
  56164. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56165. pos.addInPlace(this._displacementVector);
  56166. this.intersectionPoint.addInPlace(this._displacementVector);
  56167. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56168. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56169. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56170. };
  56171. return Collider;
  56172. }());
  56173. BABYLON.Collider = Collider;
  56174. })(BABYLON || (BABYLON = {}));
  56175. //# sourceMappingURL=babylon.collider.js.map
  56176. var BABYLON;
  56177. (function (BABYLON) {
  56178. //WebWorker code will be inserted to this variable.
  56179. /** @hidden */
  56180. BABYLON.CollisionWorker = "";
  56181. /** Defines supported task for worker process */
  56182. var WorkerTaskType;
  56183. (function (WorkerTaskType) {
  56184. /** Initialization */
  56185. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56186. /** Update of geometry */
  56187. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56188. /** Evaluate collision */
  56189. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56190. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56191. /** Defines kind of replies returned by worker */
  56192. var WorkerReplyType;
  56193. (function (WorkerReplyType) {
  56194. /** Success */
  56195. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56196. /** Unkown error */
  56197. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56198. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56199. /** @hidden */
  56200. var CollisionCoordinatorWorker = /** @class */ (function () {
  56201. function CollisionCoordinatorWorker() {
  56202. var _this = this;
  56203. this._scaledPosition = BABYLON.Vector3.Zero();
  56204. this._scaledVelocity = BABYLON.Vector3.Zero();
  56205. this.onMeshUpdated = function (transformNode) {
  56206. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56207. };
  56208. this.onGeometryUpdated = function (geometry) {
  56209. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56210. };
  56211. this._afterRender = function () {
  56212. if (!_this._init)
  56213. return;
  56214. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56215. return;
  56216. }
  56217. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56218. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56219. if (_this._runningUpdated > 4) {
  56220. return;
  56221. }
  56222. ++_this._runningUpdated;
  56223. var payload = {
  56224. updatedMeshes: _this._addUpdateMeshesList,
  56225. updatedGeometries: _this._addUpdateGeometriesList,
  56226. removedGeometries: _this._toRemoveGeometryArray,
  56227. removedMeshes: _this._toRemoveMeshesArray
  56228. };
  56229. var message = {
  56230. payload: payload,
  56231. taskType: WorkerTaskType.UPDATE
  56232. };
  56233. var serializable = [];
  56234. for (var id in payload.updatedGeometries) {
  56235. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56236. //prepare transferables
  56237. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56238. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56239. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56240. }
  56241. }
  56242. _this._worker.postMessage(message, serializable);
  56243. _this._addUpdateMeshesList = {};
  56244. _this._addUpdateGeometriesList = {};
  56245. _this._toRemoveGeometryArray = [];
  56246. _this._toRemoveMeshesArray = [];
  56247. };
  56248. this._onMessageFromWorker = function (e) {
  56249. var returnData = e.data;
  56250. if (returnData.error != WorkerReplyType.SUCCESS) {
  56251. //TODO what errors can be returned from the worker?
  56252. BABYLON.Tools.Warn("error returned from worker!");
  56253. return;
  56254. }
  56255. switch (returnData.taskType) {
  56256. case WorkerTaskType.INIT:
  56257. _this._init = true;
  56258. //Update the worked with ALL of the scene's current state
  56259. _this._scene.meshes.forEach(function (mesh) {
  56260. _this.onMeshAdded(mesh);
  56261. });
  56262. _this._scene.getGeometries().forEach(function (geometry) {
  56263. _this.onGeometryAdded(geometry);
  56264. });
  56265. break;
  56266. case WorkerTaskType.UPDATE:
  56267. _this._runningUpdated--;
  56268. break;
  56269. case WorkerTaskType.COLLIDE:
  56270. var returnPayload = returnData.payload;
  56271. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56272. return;
  56273. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56274. if (callback) {
  56275. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56276. if (mesh) {
  56277. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56278. }
  56279. }
  56280. //cleanup
  56281. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56282. break;
  56283. }
  56284. };
  56285. this._collisionsCallbackArray = [];
  56286. this._init = false;
  56287. this._runningUpdated = 0;
  56288. this._addUpdateMeshesList = {};
  56289. this._addUpdateGeometriesList = {};
  56290. this._toRemoveGeometryArray = [];
  56291. this._toRemoveMeshesArray = [];
  56292. }
  56293. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56294. if (!this._init)
  56295. return;
  56296. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56297. return;
  56298. position.divideToRef(collider._radius, this._scaledPosition);
  56299. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56300. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56301. var payload = {
  56302. collider: {
  56303. position: this._scaledPosition.asArray(),
  56304. velocity: this._scaledVelocity.asArray(),
  56305. radius: collider._radius.asArray()
  56306. },
  56307. collisionId: collisionIndex,
  56308. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56309. maximumRetry: maximumRetry
  56310. };
  56311. var message = {
  56312. payload: payload,
  56313. taskType: WorkerTaskType.COLLIDE
  56314. };
  56315. this._worker.postMessage(message);
  56316. };
  56317. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56318. this._scene = scene;
  56319. this._scene.registerAfterRender(this._afterRender);
  56320. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56321. this._worker = new Worker(workerUrl);
  56322. this._worker.onmessage = this._onMessageFromWorker;
  56323. var message = {
  56324. payload: {},
  56325. taskType: WorkerTaskType.INIT
  56326. };
  56327. this._worker.postMessage(message);
  56328. };
  56329. CollisionCoordinatorWorker.prototype.destroy = function () {
  56330. this._scene.unregisterAfterRender(this._afterRender);
  56331. this._worker.terminate();
  56332. };
  56333. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56334. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56335. this.onMeshUpdated(mesh);
  56336. };
  56337. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56338. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56339. };
  56340. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56341. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56342. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56343. this.onGeometryUpdated(geometry);
  56344. };
  56345. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56346. this._toRemoveGeometryArray.push(geometry.id);
  56347. };
  56348. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56349. var submeshes = [];
  56350. if (mesh.subMeshes) {
  56351. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56352. var boundingInfo = sm.getBoundingInfo();
  56353. return {
  56354. position: idx,
  56355. verticesStart: sm.verticesStart,
  56356. verticesCount: sm.verticesCount,
  56357. indexStart: sm.indexStart,
  56358. indexCount: sm.indexCount,
  56359. hasMaterial: !!sm.getMaterial(),
  56360. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56361. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56362. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56363. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56364. };
  56365. });
  56366. }
  56367. var geometryId = null;
  56368. if (mesh instanceof BABYLON.Mesh) {
  56369. var geometry = mesh.geometry;
  56370. geometryId = geometry ? geometry.id : null;
  56371. }
  56372. else if (mesh instanceof BABYLON.InstancedMesh) {
  56373. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56374. geometryId = geometry ? geometry.id : null;
  56375. }
  56376. var boundingInfo = mesh.getBoundingInfo();
  56377. return {
  56378. uniqueId: mesh.uniqueId,
  56379. id: mesh.id,
  56380. name: mesh.name,
  56381. geometryId: geometryId,
  56382. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56383. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56384. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56385. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56386. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56387. subMeshes: submeshes,
  56388. checkCollisions: mesh.checkCollisions
  56389. };
  56390. };
  56391. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56392. return {
  56393. id: geometry.id,
  56394. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56395. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56396. indices: new Uint32Array(geometry.getIndices() || []),
  56397. };
  56398. };
  56399. return CollisionCoordinatorWorker;
  56400. }());
  56401. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56402. /** @hidden */
  56403. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56404. function CollisionCoordinatorLegacy() {
  56405. this._scaledPosition = BABYLON.Vector3.Zero();
  56406. this._scaledVelocity = BABYLON.Vector3.Zero();
  56407. this._finalPosition = BABYLON.Vector3.Zero();
  56408. }
  56409. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56410. position.divideToRef(collider._radius, this._scaledPosition);
  56411. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56412. collider.collidedMesh = null;
  56413. collider._retry = 0;
  56414. collider._initialVelocity = this._scaledVelocity;
  56415. collider._initialPosition = this._scaledPosition;
  56416. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56417. this._finalPosition.multiplyInPlace(collider._radius);
  56418. //run the callback
  56419. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56420. };
  56421. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56422. this._scene = scene;
  56423. };
  56424. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56425. //Legacy need no destruction method.
  56426. };
  56427. //No update in legacy mode
  56428. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56429. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56430. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56431. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56432. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56433. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56434. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56435. if (excludedMesh === void 0) { excludedMesh = null; }
  56436. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56437. if (collider._retry >= maximumRetry) {
  56438. finalPosition.copyFrom(position);
  56439. return;
  56440. }
  56441. // Check if this is a mesh else camera or -1
  56442. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56443. collider._initialize(position, velocity, closeDistance);
  56444. // Check all meshes
  56445. for (var index = 0; index < this._scene.meshes.length; index++) {
  56446. var mesh = this._scene.meshes[index];
  56447. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56448. mesh._checkCollision(collider);
  56449. }
  56450. }
  56451. if (!collider.collisionFound) {
  56452. position.addToRef(velocity, finalPosition);
  56453. return;
  56454. }
  56455. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56456. collider._getResponse(position, velocity);
  56457. }
  56458. if (velocity.length() <= closeDistance) {
  56459. finalPosition.copyFrom(position);
  56460. return;
  56461. }
  56462. collider._retry++;
  56463. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56464. };
  56465. return CollisionCoordinatorLegacy;
  56466. }());
  56467. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56468. })(BABYLON || (BABYLON = {}));
  56469. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56470. var BABYLON;
  56471. (function (BABYLON) {
  56472. /**
  56473. * A particle represents one of the element emitted by a particle system.
  56474. * This is mainly define by its coordinates, direction, velocity and age.
  56475. */
  56476. var Particle = /** @class */ (function () {
  56477. /**
  56478. * Creates a new instance Particle
  56479. * @param particleSystem the particle system the particle belongs to
  56480. */
  56481. function Particle(
  56482. /**
  56483. * The particle system the particle belongs to.
  56484. */
  56485. particleSystem) {
  56486. this.particleSystem = particleSystem;
  56487. /**
  56488. * The world position of the particle in the scene.
  56489. */
  56490. this.position = BABYLON.Vector3.Zero();
  56491. /**
  56492. * The world direction of the particle in the scene.
  56493. */
  56494. this.direction = BABYLON.Vector3.Zero();
  56495. /**
  56496. * The color of the particle.
  56497. */
  56498. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56499. /**
  56500. * The color change of the particle per step.
  56501. */
  56502. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56503. /**
  56504. * Defines how long will the life of the particle be.
  56505. */
  56506. this.lifeTime = 1.0;
  56507. /**
  56508. * The current age of the particle.
  56509. */
  56510. this.age = 0;
  56511. /**
  56512. * The current size of the particle.
  56513. */
  56514. this.size = 0;
  56515. /**
  56516. * The current scale of the particle.
  56517. */
  56518. this.scale = new BABYLON.Vector2(1, 1);
  56519. /**
  56520. * The current angle of the particle.
  56521. */
  56522. this.angle = 0;
  56523. /**
  56524. * Defines how fast is the angle changing.
  56525. */
  56526. this.angularSpeed = 0;
  56527. /**
  56528. * Defines the cell index used by the particle to be rendered from a sprite.
  56529. */
  56530. this.cellIndex = 0;
  56531. /** @hidden */
  56532. this._attachedSubEmitters = null;
  56533. /** @hidden */
  56534. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56535. /** @hidden */
  56536. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56537. /** @hidden */
  56538. this._currentSize1 = 0;
  56539. /** @hidden */
  56540. this._currentSize2 = 0;
  56541. /** @hidden */
  56542. this._currentAngularSpeed1 = 0;
  56543. /** @hidden */
  56544. this._currentAngularSpeed2 = 0;
  56545. /** @hidden */
  56546. this._currentVelocity1 = 0;
  56547. /** @hidden */
  56548. this._currentVelocity2 = 0;
  56549. /** @hidden */
  56550. this._currentLimitVelocity1 = 0;
  56551. /** @hidden */
  56552. this._currentLimitVelocity2 = 0;
  56553. /** @hidden */
  56554. this._currentDrag1 = 0;
  56555. /** @hidden */
  56556. this._currentDrag2 = 0;
  56557. this.id = Particle._Count++;
  56558. if (!this.particleSystem.isAnimationSheetEnabled) {
  56559. return;
  56560. }
  56561. this.updateCellInfoFromSystem();
  56562. }
  56563. Particle.prototype.updateCellInfoFromSystem = function () {
  56564. this.cellIndex = this.particleSystem.startSpriteCellID;
  56565. };
  56566. /**
  56567. * Defines how the sprite cell index is updated for the particle
  56568. */
  56569. Particle.prototype.updateCellIndex = function () {
  56570. var offsetAge = this.age;
  56571. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56572. if (this.particleSystem.spriteRandomStartCell) {
  56573. if (this._randomCellOffset === undefined) {
  56574. this._randomCellOffset = Math.random() * this.lifeTime;
  56575. }
  56576. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56577. changeSpeed = 1;
  56578. offsetAge = this._randomCellOffset;
  56579. }
  56580. else {
  56581. offsetAge += this._randomCellOffset;
  56582. }
  56583. }
  56584. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56585. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56586. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56587. };
  56588. /** @hidden */
  56589. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56590. if (subEmitter.particleSystem.emitter.position) {
  56591. var emitterMesh = subEmitter.particleSystem.emitter;
  56592. emitterMesh.position.copyFrom(this.position);
  56593. if (subEmitter.inheritDirection) {
  56594. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56595. // Look at using Y as forward
  56596. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56597. }
  56598. }
  56599. else {
  56600. var emitterPosition = subEmitter.particleSystem.emitter;
  56601. emitterPosition.copyFrom(this.position);
  56602. }
  56603. // Set inheritedVelocityOffset to be used when new particles are created
  56604. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56605. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56606. };
  56607. /** @hidden */
  56608. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56609. var _this = this;
  56610. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56611. this._attachedSubEmitters.forEach(function (subEmitter) {
  56612. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56613. });
  56614. }
  56615. };
  56616. /** @hidden */
  56617. Particle.prototype._reset = function () {
  56618. this.age = 0;
  56619. this._currentColorGradient = null;
  56620. this._currentSizeGradient = null;
  56621. this._currentAngularSpeedGradient = null;
  56622. this._currentVelocityGradient = null;
  56623. this._currentLimitVelocityGradient = null;
  56624. this._currentDragGradient = null;
  56625. this.cellIndex = this.particleSystem.startSpriteCellID;
  56626. this._randomCellOffset = undefined;
  56627. };
  56628. /**
  56629. * Copy the properties of particle to another one.
  56630. * @param other the particle to copy the information to.
  56631. */
  56632. Particle.prototype.copyTo = function (other) {
  56633. other.position.copyFrom(this.position);
  56634. if (this._initialDirection) {
  56635. if (other._initialDirection) {
  56636. other._initialDirection.copyFrom(this._initialDirection);
  56637. }
  56638. else {
  56639. other._initialDirection = this._initialDirection.clone();
  56640. }
  56641. }
  56642. else {
  56643. other._initialDirection = null;
  56644. }
  56645. other.direction.copyFrom(this.direction);
  56646. other.color.copyFrom(this.color);
  56647. other.colorStep.copyFrom(this.colorStep);
  56648. other.lifeTime = this.lifeTime;
  56649. other.age = this.age;
  56650. other._randomCellOffset = this._randomCellOffset;
  56651. other.size = this.size;
  56652. other.scale.copyFrom(this.scale);
  56653. other.angle = this.angle;
  56654. other.angularSpeed = this.angularSpeed;
  56655. other.particleSystem = this.particleSystem;
  56656. other.cellIndex = this.cellIndex;
  56657. other.id = this.id;
  56658. other._attachedSubEmitters = this._attachedSubEmitters;
  56659. if (this._currentColorGradient) {
  56660. other._currentColorGradient = this._currentColorGradient;
  56661. other._currentColor1.copyFrom(this._currentColor1);
  56662. other._currentColor2.copyFrom(this._currentColor2);
  56663. }
  56664. if (this._currentSizeGradient) {
  56665. other._currentSizeGradient = this._currentSizeGradient;
  56666. other._currentSize1 = this._currentSize1;
  56667. other._currentSize2 = this._currentSize2;
  56668. }
  56669. if (this._currentAngularSpeedGradient) {
  56670. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56671. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56672. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56673. }
  56674. if (this._currentVelocityGradient) {
  56675. other._currentVelocityGradient = this._currentVelocityGradient;
  56676. other._currentVelocity1 = this._currentVelocity1;
  56677. other._currentVelocity2 = this._currentVelocity2;
  56678. }
  56679. if (this._currentLimitVelocityGradient) {
  56680. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56681. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56682. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56683. }
  56684. if (this._currentDragGradient) {
  56685. other._currentDragGradient = this._currentDragGradient;
  56686. other._currentDrag1 = this._currentDrag1;
  56687. other._currentDrag2 = this._currentDrag2;
  56688. }
  56689. if (this.particleSystem.isAnimationSheetEnabled) {
  56690. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56691. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56692. }
  56693. if (this.particleSystem.useRampGradients) {
  56694. other.remapData.copyFrom(this.remapData);
  56695. }
  56696. if (this._randomNoiseCoordinates1) {
  56697. if (other._randomNoiseCoordinates1) {
  56698. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56699. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56700. }
  56701. else {
  56702. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56703. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56704. }
  56705. }
  56706. };
  56707. Particle._Count = 0;
  56708. return Particle;
  56709. }());
  56710. BABYLON.Particle = Particle;
  56711. })(BABYLON || (BABYLON = {}));
  56712. //# sourceMappingURL=babylon.particle.js.map
  56713. var BABYLON;
  56714. (function (BABYLON) {
  56715. /**
  56716. * This represents the base class for particle system in Babylon.
  56717. * 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.
  56718. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56719. * @example https://doc.babylonjs.com/babylon101/particles
  56720. */
  56721. var BaseParticleSystem = /** @class */ (function () {
  56722. /**
  56723. * Instantiates a particle system.
  56724. * 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.
  56725. * @param name The name of the particle system
  56726. */
  56727. function BaseParticleSystem(name) {
  56728. /**
  56729. * List of animations used by the particle system.
  56730. */
  56731. this.animations = [];
  56732. /**
  56733. * The rendering group used by the Particle system to chose when to render.
  56734. */
  56735. this.renderingGroupId = 0;
  56736. /**
  56737. * The emitter represents the Mesh or position we are attaching the particle system to.
  56738. */
  56739. this.emitter = null;
  56740. /**
  56741. * The maximum number of particles to emit per frame
  56742. */
  56743. this.emitRate = 10;
  56744. /**
  56745. * If you want to launch only a few particles at once, that can be done, as well.
  56746. */
  56747. this.manualEmitCount = -1;
  56748. /**
  56749. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56750. */
  56751. this.updateSpeed = 0.01;
  56752. /**
  56753. * The amount of time the particle system is running (depends of the overall update speed).
  56754. */
  56755. this.targetStopDuration = 0;
  56756. /**
  56757. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56758. */
  56759. this.disposeOnStop = false;
  56760. /**
  56761. * Minimum power of emitting particles.
  56762. */
  56763. this.minEmitPower = 1;
  56764. /**
  56765. * Maximum power of emitting particles.
  56766. */
  56767. this.maxEmitPower = 1;
  56768. /**
  56769. * Minimum life time of emitting particles.
  56770. */
  56771. this.minLifeTime = 1;
  56772. /**
  56773. * Maximum life time of emitting particles.
  56774. */
  56775. this.maxLifeTime = 1;
  56776. /**
  56777. * Minimum Size of emitting particles.
  56778. */
  56779. this.minSize = 1;
  56780. /**
  56781. * Maximum Size of emitting particles.
  56782. */
  56783. this.maxSize = 1;
  56784. /**
  56785. * Minimum scale of emitting particles on X axis.
  56786. */
  56787. this.minScaleX = 1;
  56788. /**
  56789. * Maximum scale of emitting particles on X axis.
  56790. */
  56791. this.maxScaleX = 1;
  56792. /**
  56793. * Minimum scale of emitting particles on Y axis.
  56794. */
  56795. this.minScaleY = 1;
  56796. /**
  56797. * Maximum scale of emitting particles on Y axis.
  56798. */
  56799. this.maxScaleY = 1;
  56800. /**
  56801. * Gets or sets the minimal initial rotation in radians.
  56802. */
  56803. this.minInitialRotation = 0;
  56804. /**
  56805. * Gets or sets the maximal initial rotation in radians.
  56806. */
  56807. this.maxInitialRotation = 0;
  56808. /**
  56809. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56810. */
  56811. this.minAngularSpeed = 0;
  56812. /**
  56813. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56814. */
  56815. this.maxAngularSpeed = 0;
  56816. /**
  56817. * The layer mask we are rendering the particles through.
  56818. */
  56819. this.layerMask = 0x0FFFFFFF;
  56820. /**
  56821. * This can help using your own shader to render the particle system.
  56822. * The according effect will be created
  56823. */
  56824. this.customShader = null;
  56825. /**
  56826. * By default particle system starts as soon as they are created. This prevents the
  56827. * automatic start to happen and let you decide when to start emitting particles.
  56828. */
  56829. this.preventAutoStart = false;
  56830. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56831. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56832. /**
  56833. * Callback triggered when the particle animation is ending.
  56834. */
  56835. this.onAnimationEnd = null;
  56836. /**
  56837. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56838. */
  56839. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56840. /**
  56841. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56842. * to override the particles.
  56843. */
  56844. this.forceDepthWrite = false;
  56845. /** 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 */
  56846. this.preWarmCycles = 0;
  56847. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56848. this.preWarmStepOffset = 1;
  56849. /**
  56850. * 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)
  56851. */
  56852. this.spriteCellChangeSpeed = 1;
  56853. /**
  56854. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56855. */
  56856. this.startSpriteCellID = 0;
  56857. /**
  56858. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56859. */
  56860. this.endSpriteCellID = 0;
  56861. /**
  56862. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56863. */
  56864. this.spriteCellWidth = 0;
  56865. /**
  56866. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56867. */
  56868. this.spriteCellHeight = 0;
  56869. /**
  56870. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56871. */
  56872. this.spriteRandomStartCell = false;
  56873. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56874. this.translationPivot = new BABYLON.Vector2(0, 0);
  56875. /**
  56876. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  56877. */
  56878. this.beginAnimationOnStart = false;
  56879. /**
  56880. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  56881. */
  56882. this.beginAnimationFrom = 0;
  56883. /**
  56884. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  56885. */
  56886. this.beginAnimationTo = 60;
  56887. /**
  56888. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  56889. */
  56890. this.beginAnimationLoop = false;
  56891. /**
  56892. * You can use gravity if you want to give an orientation to your particles.
  56893. */
  56894. this.gravity = BABYLON.Vector3.Zero();
  56895. this._colorGradients = null;
  56896. this._sizeGradients = null;
  56897. this._lifeTimeGradients = null;
  56898. this._angularSpeedGradients = null;
  56899. this._velocityGradients = null;
  56900. this._limitVelocityGradients = null;
  56901. this._dragGradients = null;
  56902. this._emitRateGradients = null;
  56903. this._startSizeGradients = null;
  56904. this._rampGradients = null;
  56905. this._colorRemapGradients = null;
  56906. this._alphaRemapGradients = null;
  56907. /**
  56908. * Defines the delay in milliseconds before starting the system (0 by default)
  56909. */
  56910. this.startDelay = 0;
  56911. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56912. this.limitVelocityDamping = 0.4;
  56913. /**
  56914. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56915. */
  56916. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56917. /**
  56918. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56919. */
  56920. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56921. /**
  56922. * Color the particle will have at the end of its lifetime
  56923. */
  56924. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56925. /**
  56926. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56927. */
  56928. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56929. /** @hidden */
  56930. this._isSubEmitter = false;
  56931. /**
  56932. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56933. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  56934. */
  56935. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  56936. this._isBillboardBased = true;
  56937. /**
  56938. * Local cache of defines for image processing.
  56939. */
  56940. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56941. this.id = name;
  56942. this.name = name;
  56943. }
  56944. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56945. /**
  56946. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56947. */
  56948. get: function () {
  56949. return this._isAnimationSheetEnabled;
  56950. },
  56951. set: function (value) {
  56952. if (this._isAnimationSheetEnabled == value) {
  56953. return;
  56954. }
  56955. this._isAnimationSheetEnabled = value;
  56956. this._reset();
  56957. },
  56958. enumerable: true,
  56959. configurable: true
  56960. });
  56961. /**
  56962. * Get hosting scene
  56963. * @returns the scene
  56964. */
  56965. BaseParticleSystem.prototype.getScene = function () {
  56966. return this._scene;
  56967. };
  56968. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56969. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56970. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56971. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56972. };
  56973. /**
  56974. * Gets the current list of drag gradients.
  56975. * You must use addDragGradient and removeDragGradient to udpate this list
  56976. * @returns the list of drag gradients
  56977. */
  56978. BaseParticleSystem.prototype.getDragGradients = function () {
  56979. return this._dragGradients;
  56980. };
  56981. /**
  56982. * Gets the current list of limit velocity gradients.
  56983. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56984. * @returns the list of limit velocity gradients
  56985. */
  56986. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56987. return this._limitVelocityGradients;
  56988. };
  56989. /**
  56990. * Gets the current list of color gradients.
  56991. * You must use addColorGradient and removeColorGradient to udpate this list
  56992. * @returns the list of color gradients
  56993. */
  56994. BaseParticleSystem.prototype.getColorGradients = function () {
  56995. return this._colorGradients;
  56996. };
  56997. /**
  56998. * Gets the current list of size gradients.
  56999. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57000. * @returns the list of size gradients
  57001. */
  57002. BaseParticleSystem.prototype.getSizeGradients = function () {
  57003. return this._sizeGradients;
  57004. };
  57005. /**
  57006. * Gets the current list of color remap gradients.
  57007. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57008. * @returns the list of color remap gradients
  57009. */
  57010. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57011. return this._colorRemapGradients;
  57012. };
  57013. /**
  57014. * Gets the current list of alpha remap gradients.
  57015. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57016. * @returns the list of alpha remap gradients
  57017. */
  57018. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57019. return this._alphaRemapGradients;
  57020. };
  57021. /**
  57022. * Gets the current list of life time gradients.
  57023. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57024. * @returns the list of life time gradients
  57025. */
  57026. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57027. return this._lifeTimeGradients;
  57028. };
  57029. /**
  57030. * Gets the current list of angular speed gradients.
  57031. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57032. * @returns the list of angular speed gradients
  57033. */
  57034. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57035. return this._angularSpeedGradients;
  57036. };
  57037. /**
  57038. * Gets the current list of velocity gradients.
  57039. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57040. * @returns the list of velocity gradients
  57041. */
  57042. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57043. return this._velocityGradients;
  57044. };
  57045. /**
  57046. * Gets the current list of start size gradients.
  57047. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57048. * @returns the list of start size gradients
  57049. */
  57050. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57051. return this._startSizeGradients;
  57052. };
  57053. /**
  57054. * Gets the current list of emit rate gradients.
  57055. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57056. * @returns the list of emit rate gradients
  57057. */
  57058. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57059. return this._emitRateGradients;
  57060. };
  57061. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57062. /**
  57063. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57064. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57065. */
  57066. get: function () {
  57067. if (this.particleEmitterType.direction1) {
  57068. return this.particleEmitterType.direction1;
  57069. }
  57070. return BABYLON.Vector3.Zero();
  57071. },
  57072. set: function (value) {
  57073. if (this.particleEmitterType.direction1) {
  57074. this.particleEmitterType.direction1 = value;
  57075. }
  57076. },
  57077. enumerable: true,
  57078. configurable: true
  57079. });
  57080. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57081. /**
  57082. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57083. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57084. */
  57085. get: function () {
  57086. if (this.particleEmitterType.direction2) {
  57087. return this.particleEmitterType.direction2;
  57088. }
  57089. return BABYLON.Vector3.Zero();
  57090. },
  57091. set: function (value) {
  57092. if (this.particleEmitterType.direction2) {
  57093. this.particleEmitterType.direction2 = value;
  57094. }
  57095. },
  57096. enumerable: true,
  57097. configurable: true
  57098. });
  57099. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57100. /**
  57101. * 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.
  57102. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57103. */
  57104. get: function () {
  57105. if (this.particleEmitterType.minEmitBox) {
  57106. return this.particleEmitterType.minEmitBox;
  57107. }
  57108. return BABYLON.Vector3.Zero();
  57109. },
  57110. set: function (value) {
  57111. if (this.particleEmitterType.minEmitBox) {
  57112. this.particleEmitterType.minEmitBox = value;
  57113. }
  57114. },
  57115. enumerable: true,
  57116. configurable: true
  57117. });
  57118. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57119. /**
  57120. * 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.
  57121. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57122. */
  57123. get: function () {
  57124. if (this.particleEmitterType.maxEmitBox) {
  57125. return this.particleEmitterType.maxEmitBox;
  57126. }
  57127. return BABYLON.Vector3.Zero();
  57128. },
  57129. set: function (value) {
  57130. if (this.particleEmitterType.maxEmitBox) {
  57131. this.particleEmitterType.maxEmitBox = value;
  57132. }
  57133. },
  57134. enumerable: true,
  57135. configurable: true
  57136. });
  57137. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57138. /**
  57139. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57140. */
  57141. get: function () {
  57142. return this._isBillboardBased;
  57143. },
  57144. set: function (value) {
  57145. if (this._isBillboardBased === value) {
  57146. return;
  57147. }
  57148. this._isBillboardBased = value;
  57149. this._reset();
  57150. },
  57151. enumerable: true,
  57152. configurable: true
  57153. });
  57154. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57155. /**
  57156. * Gets the image processing configuration used either in this material.
  57157. */
  57158. get: function () {
  57159. return this._imageProcessingConfiguration;
  57160. },
  57161. /**
  57162. * Sets the Default image processing configuration used either in the this material.
  57163. *
  57164. * If sets to null, the scene one is in use.
  57165. */
  57166. set: function (value) {
  57167. this._attachImageProcessingConfiguration(value);
  57168. },
  57169. enumerable: true,
  57170. configurable: true
  57171. });
  57172. /**
  57173. * Attaches a new image processing configuration to the Standard Material.
  57174. * @param configuration
  57175. */
  57176. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57177. if (configuration === this._imageProcessingConfiguration) {
  57178. return;
  57179. }
  57180. // Pick the scene configuration if needed.
  57181. if (!configuration) {
  57182. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57183. }
  57184. else {
  57185. this._imageProcessingConfiguration = configuration;
  57186. }
  57187. };
  57188. /** @hidden */
  57189. BaseParticleSystem.prototype._reset = function () {
  57190. };
  57191. /** @hidden */
  57192. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57193. if (!gradients) {
  57194. return this;
  57195. }
  57196. var index = 0;
  57197. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57198. var valueGradient = gradients_1[_i];
  57199. if (valueGradient.gradient === gradient) {
  57200. gradients.splice(index, 1);
  57201. break;
  57202. }
  57203. index++;
  57204. }
  57205. if (texture) {
  57206. texture.dispose();
  57207. }
  57208. return this;
  57209. };
  57210. /**
  57211. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57212. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57213. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57214. * @returns the emitter
  57215. */
  57216. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57217. var particleEmitter = new BABYLON.PointParticleEmitter();
  57218. particleEmitter.direction1 = direction1;
  57219. particleEmitter.direction2 = direction2;
  57220. this.particleEmitterType = particleEmitter;
  57221. return particleEmitter;
  57222. };
  57223. /**
  57224. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57225. * @param radius The radius of the hemisphere to emit from
  57226. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57227. * @returns the emitter
  57228. */
  57229. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57230. if (radius === void 0) { radius = 1; }
  57231. if (radiusRange === void 0) { radiusRange = 1; }
  57232. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57233. this.particleEmitterType = particleEmitter;
  57234. return particleEmitter;
  57235. };
  57236. /**
  57237. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57238. * @param radius The radius of the sphere to emit from
  57239. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57240. * @returns the emitter
  57241. */
  57242. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57243. if (radius === void 0) { radius = 1; }
  57244. if (radiusRange === void 0) { radiusRange = 1; }
  57245. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57246. this.particleEmitterType = particleEmitter;
  57247. return particleEmitter;
  57248. };
  57249. /**
  57250. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57251. * @param radius The radius of the sphere to emit from
  57252. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57253. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57254. * @returns the emitter
  57255. */
  57256. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57257. if (radius === void 0) { radius = 1; }
  57258. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57259. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57260. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57261. this.particleEmitterType = particleEmitter;
  57262. return particleEmitter;
  57263. };
  57264. /**
  57265. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57266. * @param radius The radius of the emission cylinder
  57267. * @param height The height of the emission cylinder
  57268. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57269. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57270. * @returns the emitter
  57271. */
  57272. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57273. if (radius === void 0) { radius = 1; }
  57274. if (height === void 0) { height = 1; }
  57275. if (radiusRange === void 0) { radiusRange = 1; }
  57276. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57277. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57278. this.particleEmitterType = particleEmitter;
  57279. return particleEmitter;
  57280. };
  57281. /**
  57282. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57283. * @param radius The radius of the cylinder to emit from
  57284. * @param height The height of the emission cylinder
  57285. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57286. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57287. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57288. * @returns the emitter
  57289. */
  57290. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57291. if (radius === void 0) { radius = 1; }
  57292. if (height === void 0) { height = 1; }
  57293. if (radiusRange === void 0) { radiusRange = 1; }
  57294. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57295. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57296. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57297. this.particleEmitterType = particleEmitter;
  57298. return particleEmitter;
  57299. };
  57300. /**
  57301. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57302. * @param radius The radius of the cone to emit from
  57303. * @param angle The base angle of the cone
  57304. * @returns the emitter
  57305. */
  57306. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57307. if (radius === void 0) { radius = 1; }
  57308. if (angle === void 0) { angle = Math.PI / 4; }
  57309. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57310. this.particleEmitterType = particleEmitter;
  57311. return particleEmitter;
  57312. };
  57313. /**
  57314. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57315. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57316. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57317. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57318. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57319. * @returns the emitter
  57320. */
  57321. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57322. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57323. this.particleEmitterType = particleEmitter;
  57324. this.direction1 = direction1;
  57325. this.direction2 = direction2;
  57326. this.minEmitBox = minEmitBox;
  57327. this.maxEmitBox = maxEmitBox;
  57328. return particleEmitter;
  57329. };
  57330. /**
  57331. * Source color is added to the destination color without alpha affecting the result
  57332. */
  57333. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57334. /**
  57335. * Blend current color and particle color using particle’s alpha
  57336. */
  57337. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57338. /**
  57339. * Add current color and particle color multiplied by particle’s alpha
  57340. */
  57341. BaseParticleSystem.BLENDMODE_ADD = 2;
  57342. /**
  57343. * Multiply current color with particle color
  57344. */
  57345. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57346. /**
  57347. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57348. */
  57349. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57350. return BaseParticleSystem;
  57351. }());
  57352. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57353. })(BABYLON || (BABYLON = {}));
  57354. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57355. var BABYLON;
  57356. (function (BABYLON) {
  57357. /**
  57358. * This represents a particle system in Babylon.
  57359. * 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.
  57360. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57361. * @example https://doc.babylonjs.com/babylon101/particles
  57362. */
  57363. var ParticleSystem = /** @class */ (function (_super) {
  57364. __extends(ParticleSystem, _super);
  57365. /**
  57366. * Instantiates a particle system.
  57367. * 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.
  57368. * @param name The name of the particle system
  57369. * @param capacity The max number of particles alive at the same time
  57370. * @param scene The scene the particle system belongs to
  57371. * @param customEffect a custom effect used to change the way particles are rendered by default
  57372. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57373. * @param epsilon Offset used to render the particles
  57374. */
  57375. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57376. if (customEffect === void 0) { customEffect = null; }
  57377. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57378. if (epsilon === void 0) { epsilon = 0.01; }
  57379. var _this = _super.call(this, name) || this;
  57380. /**
  57381. * @hidden
  57382. */
  57383. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57384. /**
  57385. * An event triggered when the system is disposed
  57386. */
  57387. _this.onDisposeObservable = new BABYLON.Observable();
  57388. _this._particles = new Array();
  57389. _this._stockParticles = new Array();
  57390. _this._newPartsExcess = 0;
  57391. _this._vertexBuffers = {};
  57392. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57393. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57394. _this._scaledDirection = BABYLON.Vector3.Zero();
  57395. _this._scaledGravity = BABYLON.Vector3.Zero();
  57396. _this._currentRenderId = -1;
  57397. _this._useInstancing = false;
  57398. _this._started = false;
  57399. _this._stopped = false;
  57400. _this._actualFrame = 0;
  57401. /** @hidden */
  57402. _this._currentEmitRate1 = 0;
  57403. /** @hidden */
  57404. _this._currentEmitRate2 = 0;
  57405. /** @hidden */
  57406. _this._currentStartSize1 = 0;
  57407. /** @hidden */
  57408. _this._currentStartSize2 = 0;
  57409. _this._rawTextureWidth = 256;
  57410. _this._useRampGradients = false;
  57411. /**
  57412. * @hidden
  57413. * If the particle systems emitter should be disposed when the particle system is disposed
  57414. */
  57415. _this._disposeEmitterOnDispose = false;
  57416. // start of sub system methods
  57417. /**
  57418. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57419. * Its lifetime will start back at 0.
  57420. */
  57421. _this.recycleParticle = function (particle) {
  57422. // move particle from activeParticle list to stock particles
  57423. var lastParticle = _this._particles.pop();
  57424. if (lastParticle !== particle) {
  57425. lastParticle.copyTo(particle);
  57426. }
  57427. _this._stockParticles.push(lastParticle);
  57428. };
  57429. _this._createParticle = function () {
  57430. var particle;
  57431. if (_this._stockParticles.length !== 0) {
  57432. particle = _this._stockParticles.pop();
  57433. particle._reset();
  57434. }
  57435. else {
  57436. particle = new BABYLON.Particle(_this);
  57437. }
  57438. // Attach emitters
  57439. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57440. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57441. particle._attachedSubEmitters = [];
  57442. subEmitters.forEach(function (subEmitter) {
  57443. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57444. var newEmitter = subEmitter.clone();
  57445. particle._attachedSubEmitters.push(newEmitter);
  57446. newEmitter.particleSystem.start();
  57447. }
  57448. });
  57449. }
  57450. return particle;
  57451. };
  57452. _this._emitFromParticle = function (particle) {
  57453. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57454. return;
  57455. }
  57456. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57457. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57458. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57459. var subSystem = subEmitter.clone();
  57460. particle._inheritParticleInfoToSubEmitter(subSystem);
  57461. subSystem.particleSystem._rootParticleSystem = _this;
  57462. _this.activeSubSystems.push(subSystem.particleSystem);
  57463. subSystem.particleSystem.start();
  57464. }
  57465. });
  57466. };
  57467. _this._capacity = capacity;
  57468. _this._epsilon = epsilon;
  57469. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57470. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57471. // Setup the default processing configuration to the scene.
  57472. _this._attachImageProcessingConfiguration(null);
  57473. _this._customEffect = customEffect;
  57474. _this._scene.particleSystems.push(_this);
  57475. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57476. _this._createIndexBuffer();
  57477. _this._createVertexBuffers();
  57478. // Default emitter type
  57479. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57480. // Update
  57481. _this.updateFunction = function (particles) {
  57482. var noiseTextureSize = null;
  57483. var noiseTextureData = null;
  57484. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57485. noiseTextureSize = _this.noiseTexture.getSize();
  57486. noiseTextureData = (_this.noiseTexture.getContent());
  57487. }
  57488. var _loop_1 = function () {
  57489. particle = particles[index];
  57490. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57491. var previousAge = particle.age;
  57492. particle.age += scaledUpdateSpeed;
  57493. // Evaluate step to death
  57494. if (particle.age > particle.lifeTime) {
  57495. var diff = particle.age - previousAge;
  57496. var oldDiff = particle.lifeTime - previousAge;
  57497. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57498. particle.age = particle.lifeTime;
  57499. }
  57500. var ratio = particle.age / particle.lifeTime;
  57501. // Color
  57502. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57503. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57504. if (currentGradient !== particle._currentColorGradient) {
  57505. particle._currentColor1.copyFrom(particle._currentColor2);
  57506. nextGradient.getColorToRef(particle._currentColor2);
  57507. particle._currentColorGradient = currentGradient;
  57508. }
  57509. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57510. });
  57511. }
  57512. else {
  57513. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57514. particle.color.addInPlace(_this._scaledColorStep);
  57515. if (particle.color.a < 0) {
  57516. particle.color.a = 0;
  57517. }
  57518. }
  57519. // Angular speed
  57520. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57521. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57522. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57523. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57524. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57525. particle._currentAngularSpeedGradient = currentGradient;
  57526. }
  57527. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57528. });
  57529. }
  57530. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57531. // Direction
  57532. var directionScale = scaledUpdateSpeed;
  57533. /// Velocity
  57534. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57535. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57536. if (currentGradient !== particle._currentVelocityGradient) {
  57537. particle._currentVelocity1 = particle._currentVelocity2;
  57538. particle._currentVelocity2 = nextGradient.getFactor();
  57539. particle._currentVelocityGradient = currentGradient;
  57540. }
  57541. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57542. });
  57543. }
  57544. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57545. /// Limit velocity
  57546. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57547. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57548. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57549. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57550. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57551. particle._currentLimitVelocityGradient = currentGradient;
  57552. }
  57553. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57554. var currentVelocity = particle.direction.length();
  57555. if (currentVelocity > limitVelocity) {
  57556. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57557. }
  57558. });
  57559. }
  57560. /// Drag
  57561. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57562. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57563. if (currentGradient !== particle._currentDragGradient) {
  57564. particle._currentDrag1 = particle._currentDrag2;
  57565. particle._currentDrag2 = nextGradient.getFactor();
  57566. particle._currentDragGradient = currentGradient;
  57567. }
  57568. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57569. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57570. });
  57571. }
  57572. particle.position.addInPlace(_this._scaledDirection);
  57573. // Noise
  57574. if (noiseTextureData && noiseTextureSize) {
  57575. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57576. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57577. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57578. var force = BABYLON.Tmp.Vector3[0];
  57579. var scaledForce = BABYLON.Tmp.Vector3[1];
  57580. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57581. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57582. particle.direction.addInPlace(scaledForce);
  57583. }
  57584. // Gravity
  57585. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57586. particle.direction.addInPlace(_this._scaledGravity);
  57587. // Size
  57588. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57589. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57590. if (currentGradient !== particle._currentSizeGradient) {
  57591. particle._currentSize1 = particle._currentSize2;
  57592. particle._currentSize2 = nextGradient.getFactor();
  57593. particle._currentSizeGradient = currentGradient;
  57594. }
  57595. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57596. });
  57597. }
  57598. // Remap data
  57599. if (_this._useRampGradients) {
  57600. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57601. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57602. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57603. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57604. particle.remapData.x = min;
  57605. particle.remapData.y = max - min;
  57606. });
  57607. }
  57608. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57609. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57610. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57611. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57612. particle.remapData.z = min;
  57613. particle.remapData.w = max - min;
  57614. });
  57615. }
  57616. }
  57617. if (_this._isAnimationSheetEnabled) {
  57618. particle.updateCellIndex();
  57619. }
  57620. // Update the position of the attached sub-emitters to match their attached particle
  57621. particle._inheritParticleInfoToSubEmitters();
  57622. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57623. _this._emitFromParticle(particle);
  57624. if (particle._attachedSubEmitters) {
  57625. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57626. subEmitter.particleSystem.disposeOnStop = true;
  57627. subEmitter.particleSystem.stop();
  57628. });
  57629. particle._attachedSubEmitters = null;
  57630. }
  57631. _this.recycleParticle(particle);
  57632. index--;
  57633. return "continue";
  57634. }
  57635. };
  57636. var particle;
  57637. for (var index = 0; index < particles.length; index++) {
  57638. _loop_1();
  57639. }
  57640. };
  57641. return _this;
  57642. }
  57643. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57644. /**
  57645. * Sets a callback that will be triggered when the system is disposed
  57646. */
  57647. set: function (callback) {
  57648. if (this._onDisposeObserver) {
  57649. this.onDisposeObservable.remove(this._onDisposeObserver);
  57650. }
  57651. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57652. },
  57653. enumerable: true,
  57654. configurable: true
  57655. });
  57656. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57657. /** Gets or sets a boolean indicating that ramp gradients must be used
  57658. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57659. */
  57660. get: function () {
  57661. return this._useRampGradients;
  57662. },
  57663. set: function (value) {
  57664. if (this._useRampGradients === value) {
  57665. return;
  57666. }
  57667. this._useRampGradients = value;
  57668. this._resetEffect();
  57669. },
  57670. enumerable: true,
  57671. configurable: true
  57672. });
  57673. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57674. //end of Sub-emitter
  57675. /**
  57676. * Gets the current list of active particles
  57677. */
  57678. get: function () {
  57679. return this._particles;
  57680. },
  57681. enumerable: true,
  57682. configurable: true
  57683. });
  57684. /**
  57685. * Returns the string "ParticleSystem"
  57686. * @returns a string containing the class name
  57687. */
  57688. ParticleSystem.prototype.getClassName = function () {
  57689. return "ParticleSystem";
  57690. };
  57691. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57692. var newGradient = new BABYLON.FactorGradient();
  57693. newGradient.gradient = gradient;
  57694. newGradient.factor1 = factor;
  57695. newGradient.factor2 = factor2;
  57696. factorGradients.push(newGradient);
  57697. factorGradients.sort(function (a, b) {
  57698. if (a.gradient < b.gradient) {
  57699. return -1;
  57700. }
  57701. else if (a.gradient > b.gradient) {
  57702. return 1;
  57703. }
  57704. return 0;
  57705. });
  57706. };
  57707. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57708. if (!factorGradients) {
  57709. return;
  57710. }
  57711. var index = 0;
  57712. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57713. var factorGradient = factorGradients_1[_i];
  57714. if (factorGradient.gradient === gradient) {
  57715. factorGradients.splice(index, 1);
  57716. break;
  57717. }
  57718. index++;
  57719. }
  57720. };
  57721. /**
  57722. * Adds a new life time gradient
  57723. * @param gradient defines the gradient to use (between 0 and 1)
  57724. * @param factor defines the life time factor to affect to the specified gradient
  57725. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57726. * @returns the current particle system
  57727. */
  57728. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57729. if (!this._lifeTimeGradients) {
  57730. this._lifeTimeGradients = [];
  57731. }
  57732. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57733. return this;
  57734. };
  57735. /**
  57736. * Remove a specific life time gradient
  57737. * @param gradient defines the gradient to remove
  57738. * @returns the current particle system
  57739. */
  57740. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57741. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57742. return this;
  57743. };
  57744. /**
  57745. * Adds a new size gradient
  57746. * @param gradient defines the gradient to use (between 0 and 1)
  57747. * @param factor defines the size factor to affect to the specified gradient
  57748. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57749. * @returns the current particle system
  57750. */
  57751. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57752. if (!this._sizeGradients) {
  57753. this._sizeGradients = [];
  57754. }
  57755. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57756. return this;
  57757. };
  57758. /**
  57759. * Remove a specific size gradient
  57760. * @param gradient defines the gradient to remove
  57761. * @returns the current particle system
  57762. */
  57763. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57764. this._removeFactorGradient(this._sizeGradients, gradient);
  57765. return this;
  57766. };
  57767. /**
  57768. * Adds a new color remap gradient
  57769. * @param gradient defines the gradient to use (between 0 and 1)
  57770. * @param min defines the color remap minimal range
  57771. * @param max defines the color remap maximal range
  57772. * @returns the current particle system
  57773. */
  57774. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57775. if (!this._colorRemapGradients) {
  57776. this._colorRemapGradients = [];
  57777. }
  57778. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57779. return this;
  57780. };
  57781. /**
  57782. * Remove a specific color remap gradient
  57783. * @param gradient defines the gradient to remove
  57784. * @returns the current particle system
  57785. */
  57786. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57787. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57788. return this;
  57789. };
  57790. /**
  57791. * Adds a new alpha remap gradient
  57792. * @param gradient defines the gradient to use (between 0 and 1)
  57793. * @param min defines the alpha remap minimal range
  57794. * @param max defines the alpha remap maximal range
  57795. * @returns the current particle system
  57796. */
  57797. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57798. if (!this._alphaRemapGradients) {
  57799. this._alphaRemapGradients = [];
  57800. }
  57801. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57802. return this;
  57803. };
  57804. /**
  57805. * Remove a specific alpha remap gradient
  57806. * @param gradient defines the gradient to remove
  57807. * @returns the current particle system
  57808. */
  57809. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57810. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57811. return this;
  57812. };
  57813. /**
  57814. * Adds a new angular speed gradient
  57815. * @param gradient defines the gradient to use (between 0 and 1)
  57816. * @param factor defines the angular speed to affect to the specified gradient
  57817. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57818. * @returns the current particle system
  57819. */
  57820. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57821. if (!this._angularSpeedGradients) {
  57822. this._angularSpeedGradients = [];
  57823. }
  57824. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57825. return this;
  57826. };
  57827. /**
  57828. * Remove a specific angular speed gradient
  57829. * @param gradient defines the gradient to remove
  57830. * @returns the current particle system
  57831. */
  57832. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57833. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57834. return this;
  57835. };
  57836. /**
  57837. * Adds a new velocity gradient
  57838. * @param gradient defines the gradient to use (between 0 and 1)
  57839. * @param factor defines the velocity to affect to the specified gradient
  57840. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57841. * @returns the current particle system
  57842. */
  57843. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57844. if (!this._velocityGradients) {
  57845. this._velocityGradients = [];
  57846. }
  57847. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57848. return this;
  57849. };
  57850. /**
  57851. * Remove a specific velocity gradient
  57852. * @param gradient defines the gradient to remove
  57853. * @returns the current particle system
  57854. */
  57855. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57856. this._removeFactorGradient(this._velocityGradients, gradient);
  57857. return this;
  57858. };
  57859. /**
  57860. * Adds a new limit velocity gradient
  57861. * @param gradient defines the gradient to use (between 0 and 1)
  57862. * @param factor defines the limit velocity value to affect to the specified gradient
  57863. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57864. * @returns the current particle system
  57865. */
  57866. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57867. if (!this._limitVelocityGradients) {
  57868. this._limitVelocityGradients = [];
  57869. }
  57870. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57871. return this;
  57872. };
  57873. /**
  57874. * Remove a specific limit velocity gradient
  57875. * @param gradient defines the gradient to remove
  57876. * @returns the current particle system
  57877. */
  57878. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57879. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57880. return this;
  57881. };
  57882. /**
  57883. * Adds a new drag gradient
  57884. * @param gradient defines the gradient to use (between 0 and 1)
  57885. * @param factor defines the drag value to affect to the specified gradient
  57886. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57887. * @returns the current particle system
  57888. */
  57889. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57890. if (!this._dragGradients) {
  57891. this._dragGradients = [];
  57892. }
  57893. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57894. return this;
  57895. };
  57896. /**
  57897. * Remove a specific drag gradient
  57898. * @param gradient defines the gradient to remove
  57899. * @returns the current particle system
  57900. */
  57901. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57902. this._removeFactorGradient(this._dragGradients, gradient);
  57903. return this;
  57904. };
  57905. /**
  57906. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57907. * @param gradient defines the gradient to use (between 0 and 1)
  57908. * @param factor defines the emit rate value to affect to the specified gradient
  57909. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57910. * @returns the current particle system
  57911. */
  57912. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57913. if (!this._emitRateGradients) {
  57914. this._emitRateGradients = [];
  57915. }
  57916. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57917. if (!this._currentEmitRateGradient) {
  57918. this._currentEmitRateGradient = this._emitRateGradients[0];
  57919. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57920. this._currentEmitRate2 = this._currentEmitRate1;
  57921. }
  57922. if (this._emitRateGradients.length === 2) {
  57923. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57924. }
  57925. return this;
  57926. };
  57927. /**
  57928. * Remove a specific emit rate gradient
  57929. * @param gradient defines the gradient to remove
  57930. * @returns the current particle system
  57931. */
  57932. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57933. this._removeFactorGradient(this._emitRateGradients, gradient);
  57934. return this;
  57935. };
  57936. /**
  57937. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57938. * @param gradient defines the gradient to use (between 0 and 1)
  57939. * @param factor defines the start size value to affect to the specified gradient
  57940. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57941. * @returns the current particle system
  57942. */
  57943. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57944. if (!this._startSizeGradients) {
  57945. this._startSizeGradients = [];
  57946. }
  57947. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57948. if (!this._currentStartSizeGradient) {
  57949. this._currentStartSizeGradient = this._startSizeGradients[0];
  57950. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57951. this._currentStartSize2 = this._currentStartSize1;
  57952. }
  57953. if (this._startSizeGradients.length === 2) {
  57954. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57955. }
  57956. return this;
  57957. };
  57958. /**
  57959. * Remove a specific start size gradient
  57960. * @param gradient defines the gradient to remove
  57961. * @returns the current particle system
  57962. */
  57963. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57964. this._removeFactorGradient(this._emitRateGradients, gradient);
  57965. return this;
  57966. };
  57967. ParticleSystem.prototype._createRampGradientTexture = function () {
  57968. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57969. return;
  57970. }
  57971. var data = new Uint8Array(this._rawTextureWidth * 4);
  57972. var tmpColor = BABYLON.Tmp.Color3[0];
  57973. for (var x = 0; x < this._rawTextureWidth; x++) {
  57974. var ratio = x / this._rawTextureWidth;
  57975. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57976. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57977. data[x * 4] = tmpColor.r * 255;
  57978. data[x * 4 + 1] = tmpColor.g * 255;
  57979. data[x * 4 + 2] = tmpColor.b * 255;
  57980. data[x * 4 + 3] = 255;
  57981. });
  57982. }
  57983. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57984. };
  57985. /**
  57986. * Gets the current list of ramp gradients.
  57987. * You must use addRampGradient and removeRampGradient to udpate this list
  57988. * @returns the list of ramp gradients
  57989. */
  57990. ParticleSystem.prototype.getRampGradients = function () {
  57991. return this._rampGradients;
  57992. };
  57993. /**
  57994. * Adds a new ramp gradient used to remap particle colors
  57995. * @param gradient defines the gradient to use (between 0 and 1)
  57996. * @param color defines the color to affect to the specified gradient
  57997. * @returns the current particle system
  57998. */
  57999. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58000. if (!this._rampGradients) {
  58001. this._rampGradients = [];
  58002. }
  58003. var rampGradient = new BABYLON.Color3Gradient();
  58004. rampGradient.gradient = gradient;
  58005. rampGradient.color = color;
  58006. this._rampGradients.push(rampGradient);
  58007. this._rampGradients.sort(function (a, b) {
  58008. if (a.gradient < b.gradient) {
  58009. return -1;
  58010. }
  58011. else if (a.gradient > b.gradient) {
  58012. return 1;
  58013. }
  58014. return 0;
  58015. });
  58016. if (this._rampGradientsTexture) {
  58017. this._rampGradientsTexture.dispose();
  58018. this._rampGradientsTexture = null;
  58019. }
  58020. this._createRampGradientTexture();
  58021. return this;
  58022. };
  58023. /**
  58024. * Remove a specific ramp gradient
  58025. * @param gradient defines the gradient to remove
  58026. * @returns the current particle system
  58027. */
  58028. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58029. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58030. this._rampGradientsTexture = null;
  58031. if (this._rampGradients && this._rampGradients.length > 0) {
  58032. this._createRampGradientTexture();
  58033. }
  58034. return this;
  58035. };
  58036. /**
  58037. * Adds a new color gradient
  58038. * @param gradient defines the gradient to use (between 0 and 1)
  58039. * @param color1 defines the color to affect to the specified gradient
  58040. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58041. */
  58042. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58043. if (!this._colorGradients) {
  58044. this._colorGradients = [];
  58045. }
  58046. var colorGradient = new BABYLON.ColorGradient();
  58047. colorGradient.gradient = gradient;
  58048. colorGradient.color1 = color1;
  58049. colorGradient.color2 = color2;
  58050. this._colorGradients.push(colorGradient);
  58051. this._colorGradients.sort(function (a, b) {
  58052. if (a.gradient < b.gradient) {
  58053. return -1;
  58054. }
  58055. else if (a.gradient > b.gradient) {
  58056. return 1;
  58057. }
  58058. return 0;
  58059. });
  58060. return this;
  58061. };
  58062. /**
  58063. * Remove a specific color gradient
  58064. * @param gradient defines the gradient to remove
  58065. */
  58066. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58067. if (!this._colorGradients) {
  58068. return this;
  58069. }
  58070. var index = 0;
  58071. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58072. var colorGradient = _a[_i];
  58073. if (colorGradient.gradient === gradient) {
  58074. this._colorGradients.splice(index, 1);
  58075. break;
  58076. }
  58077. index++;
  58078. }
  58079. return this;
  58080. };
  58081. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58082. u = Math.abs(u) * 0.5 + 0.5;
  58083. v = Math.abs(v) * 0.5 + 0.5;
  58084. var wrappedU = ((u * width) % width) | 0;
  58085. var wrappedV = ((v * height) % height) | 0;
  58086. var position = (wrappedU + wrappedV * width) * 4;
  58087. return pixels[position] / 255;
  58088. };
  58089. ParticleSystem.prototype._reset = function () {
  58090. this._resetEffect();
  58091. };
  58092. ParticleSystem.prototype._resetEffect = function () {
  58093. if (this._vertexBuffer) {
  58094. this._vertexBuffer.dispose();
  58095. this._vertexBuffer = null;
  58096. }
  58097. if (this._spriteBuffer) {
  58098. this._spriteBuffer.dispose();
  58099. this._spriteBuffer = null;
  58100. }
  58101. this._createVertexBuffers();
  58102. };
  58103. ParticleSystem.prototype._createVertexBuffers = function () {
  58104. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58105. if (this._isAnimationSheetEnabled) {
  58106. this._vertexBufferSize += 1;
  58107. }
  58108. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58109. this._vertexBufferSize += 3;
  58110. }
  58111. if (this._useRampGradients) {
  58112. this._vertexBufferSize += 4;
  58113. }
  58114. var engine = this._scene.getEngine();
  58115. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58116. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58117. var dataOffset = 0;
  58118. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58119. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58120. dataOffset += 3;
  58121. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58122. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58123. dataOffset += 4;
  58124. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58125. this._vertexBuffers["angle"] = options;
  58126. dataOffset += 1;
  58127. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58128. this._vertexBuffers["size"] = size;
  58129. dataOffset += 2;
  58130. if (this._isAnimationSheetEnabled) {
  58131. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58132. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58133. dataOffset += 1;
  58134. }
  58135. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58136. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58137. this._vertexBuffers["direction"] = directionBuffer;
  58138. dataOffset += 3;
  58139. }
  58140. if (this._useRampGradients) {
  58141. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58142. this._vertexBuffers["remapData"] = rampDataBuffer;
  58143. dataOffset += 4;
  58144. }
  58145. var offsets;
  58146. if (this._useInstancing) {
  58147. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58148. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58149. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58150. }
  58151. else {
  58152. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58153. dataOffset += 2;
  58154. }
  58155. this._vertexBuffers["offset"] = offsets;
  58156. };
  58157. ParticleSystem.prototype._createIndexBuffer = function () {
  58158. if (this._useInstancing) {
  58159. return;
  58160. }
  58161. var indices = [];
  58162. var index = 0;
  58163. for (var count = 0; count < this._capacity; count++) {
  58164. indices.push(index);
  58165. indices.push(index + 1);
  58166. indices.push(index + 2);
  58167. indices.push(index);
  58168. indices.push(index + 2);
  58169. indices.push(index + 3);
  58170. index += 4;
  58171. }
  58172. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58173. };
  58174. /**
  58175. * Gets the maximum number of particles active at the same time.
  58176. * @returns The max number of active particles.
  58177. */
  58178. ParticleSystem.prototype.getCapacity = function () {
  58179. return this._capacity;
  58180. };
  58181. /**
  58182. * Gets whether there are still active particles in the system.
  58183. * @returns True if it is alive, otherwise false.
  58184. */
  58185. ParticleSystem.prototype.isAlive = function () {
  58186. return this._alive;
  58187. };
  58188. /**
  58189. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58190. * @returns True if it has been started, otherwise false.
  58191. */
  58192. ParticleSystem.prototype.isStarted = function () {
  58193. return this._started;
  58194. };
  58195. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58196. var _this = this;
  58197. this._subEmitters = new Array();
  58198. if (this.subEmitters) {
  58199. this.subEmitters.forEach(function (subEmitter) {
  58200. if (subEmitter instanceof ParticleSystem) {
  58201. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58202. }
  58203. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58204. _this._subEmitters.push([subEmitter]);
  58205. }
  58206. else if (subEmitter instanceof Array) {
  58207. _this._subEmitters.push(subEmitter);
  58208. }
  58209. });
  58210. }
  58211. };
  58212. /**
  58213. * Starts the particle system and begins to emit
  58214. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58215. */
  58216. ParticleSystem.prototype.start = function (delay) {
  58217. var _this = this;
  58218. if (delay === void 0) { delay = this.startDelay; }
  58219. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58220. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58221. }
  58222. if (delay) {
  58223. setTimeout(function () {
  58224. _this.start(0);
  58225. }, delay);
  58226. return;
  58227. }
  58228. // Convert the subEmitters field to the constant type field _subEmitters
  58229. this._prepareSubEmitterInternalArray();
  58230. this._started = true;
  58231. this._stopped = false;
  58232. this._actualFrame = 0;
  58233. if (this._subEmitters && this._subEmitters.length != 0) {
  58234. this.activeSubSystems = new Array();
  58235. }
  58236. if (this.preWarmCycles) {
  58237. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58238. this.emitter.computeWorldMatrix(true);
  58239. }
  58240. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58241. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58242. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58243. setTimeout(function () {
  58244. for (var index = 0; index < _this.preWarmCycles; index++) {
  58245. _this.animate(true);
  58246. noiseTextureAsProcedural_1.render();
  58247. }
  58248. });
  58249. });
  58250. }
  58251. else {
  58252. for (var index = 0; index < this.preWarmCycles; index++) {
  58253. this.animate(true);
  58254. }
  58255. }
  58256. }
  58257. // Animations
  58258. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58259. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58260. }
  58261. };
  58262. /**
  58263. * Stops the particle system.
  58264. * @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.
  58265. */
  58266. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58267. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58268. this._stopped = true;
  58269. if (stopSubEmitters) {
  58270. this._stopSubEmitters();
  58271. }
  58272. };
  58273. // animation sheet
  58274. /**
  58275. * Remove all active particles
  58276. */
  58277. ParticleSystem.prototype.reset = function () {
  58278. this._stockParticles = [];
  58279. this._particles = [];
  58280. };
  58281. /**
  58282. * @hidden (for internal use only)
  58283. */
  58284. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58285. var offset = index * this._vertexBufferSize;
  58286. this._vertexData[offset++] = particle.position.x;
  58287. this._vertexData[offset++] = particle.position.y;
  58288. this._vertexData[offset++] = particle.position.z;
  58289. this._vertexData[offset++] = particle.color.r;
  58290. this._vertexData[offset++] = particle.color.g;
  58291. this._vertexData[offset++] = particle.color.b;
  58292. this._vertexData[offset++] = particle.color.a;
  58293. this._vertexData[offset++] = particle.angle;
  58294. this._vertexData[offset++] = particle.scale.x * particle.size;
  58295. this._vertexData[offset++] = particle.scale.y * particle.size;
  58296. if (this._isAnimationSheetEnabled) {
  58297. this._vertexData[offset++] = particle.cellIndex;
  58298. }
  58299. if (!this._isBillboardBased) {
  58300. if (particle._initialDirection) {
  58301. this._vertexData[offset++] = particle._initialDirection.x;
  58302. this._vertexData[offset++] = particle._initialDirection.y;
  58303. this._vertexData[offset++] = particle._initialDirection.z;
  58304. }
  58305. else {
  58306. this._vertexData[offset++] = particle.direction.x;
  58307. this._vertexData[offset++] = particle.direction.y;
  58308. this._vertexData[offset++] = particle.direction.z;
  58309. }
  58310. }
  58311. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58312. this._vertexData[offset++] = particle.direction.x;
  58313. this._vertexData[offset++] = particle.direction.y;
  58314. this._vertexData[offset++] = particle.direction.z;
  58315. }
  58316. if (this._useRampGradients) {
  58317. this._vertexData[offset++] = particle.remapData.x;
  58318. this._vertexData[offset++] = particle.remapData.y;
  58319. this._vertexData[offset++] = particle.remapData.z;
  58320. this._vertexData[offset++] = particle.remapData.w;
  58321. }
  58322. if (!this._useInstancing) {
  58323. if (this._isAnimationSheetEnabled) {
  58324. if (offsetX === 0)
  58325. offsetX = this._epsilon;
  58326. else if (offsetX === 1)
  58327. offsetX = 1 - this._epsilon;
  58328. if (offsetY === 0)
  58329. offsetY = this._epsilon;
  58330. else if (offsetY === 1)
  58331. offsetY = 1 - this._epsilon;
  58332. }
  58333. this._vertexData[offset++] = offsetX;
  58334. this._vertexData[offset++] = offsetY;
  58335. }
  58336. };
  58337. ParticleSystem.prototype._stopSubEmitters = function () {
  58338. if (!this.activeSubSystems) {
  58339. return;
  58340. }
  58341. this.activeSubSystems.forEach(function (subSystem) {
  58342. subSystem.stop(true);
  58343. });
  58344. this.activeSubSystems = new Array();
  58345. };
  58346. ParticleSystem.prototype._removeFromRoot = function () {
  58347. if (!this._rootParticleSystem) {
  58348. return;
  58349. }
  58350. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58351. if (index !== -1) {
  58352. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58353. }
  58354. this._rootParticleSystem = null;
  58355. };
  58356. // End of sub system methods
  58357. ParticleSystem.prototype._update = function (newParticles) {
  58358. var _this = this;
  58359. // Update current
  58360. this._alive = this._particles.length > 0;
  58361. if (this.emitter.position) {
  58362. var emitterMesh = this.emitter;
  58363. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58364. }
  58365. else {
  58366. var emitterPosition = this.emitter;
  58367. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58368. }
  58369. this.updateFunction(this._particles);
  58370. // Add new ones
  58371. var particle;
  58372. var _loop_2 = function () {
  58373. if (this_1._particles.length === this_1._capacity) {
  58374. return "break";
  58375. }
  58376. particle = this_1._createParticle();
  58377. this_1._particles.push(particle);
  58378. // Emitter
  58379. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58380. if (this_1.startPositionFunction) {
  58381. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58382. }
  58383. else {
  58384. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58385. }
  58386. if (this_1.startDirectionFunction) {
  58387. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58388. }
  58389. else {
  58390. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58391. }
  58392. if (emitPower === 0) {
  58393. if (!particle._initialDirection) {
  58394. particle._initialDirection = particle.direction.clone();
  58395. }
  58396. else {
  58397. particle._initialDirection.copyFrom(particle.direction);
  58398. }
  58399. }
  58400. else {
  58401. particle._initialDirection = null;
  58402. }
  58403. particle.direction.scaleInPlace(emitPower);
  58404. // Life time
  58405. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58406. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58407. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58408. var factorGradient1 = currentGradient;
  58409. var factorGradient2 = nextGradient;
  58410. var lifeTime1 = factorGradient1.getFactor();
  58411. var lifeTime2 = factorGradient2.getFactor();
  58412. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58413. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58414. });
  58415. }
  58416. else {
  58417. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58418. }
  58419. // Size
  58420. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58421. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58422. }
  58423. else {
  58424. particle._currentSizeGradient = this_1._sizeGradients[0];
  58425. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58426. particle.size = particle._currentSize1;
  58427. if (this_1._sizeGradients.length > 1) {
  58428. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58429. }
  58430. else {
  58431. particle._currentSize2 = particle._currentSize1;
  58432. }
  58433. }
  58434. // Size and scale
  58435. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58436. // Adjust scale by start size
  58437. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58438. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58439. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58440. if (currentGradient !== _this._currentStartSizeGradient) {
  58441. _this._currentStartSize1 = _this._currentStartSize2;
  58442. _this._currentStartSize2 = nextGradient.getFactor();
  58443. _this._currentStartSizeGradient = currentGradient;
  58444. }
  58445. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58446. particle.scale.scaleInPlace(value);
  58447. });
  58448. }
  58449. // Angle
  58450. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58451. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58452. }
  58453. else {
  58454. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58455. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58456. particle._currentAngularSpeed1 = particle.angularSpeed;
  58457. if (this_1._angularSpeedGradients.length > 1) {
  58458. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58459. }
  58460. else {
  58461. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58462. }
  58463. }
  58464. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58465. // Velocity
  58466. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58467. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58468. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58469. if (this_1._velocityGradients.length > 1) {
  58470. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58471. }
  58472. else {
  58473. particle._currentVelocity2 = particle._currentVelocity1;
  58474. }
  58475. }
  58476. // Limit velocity
  58477. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58478. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58479. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58480. if (this_1._limitVelocityGradients.length > 1) {
  58481. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58482. }
  58483. else {
  58484. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58485. }
  58486. }
  58487. // Drag
  58488. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58489. particle._currentDragGradient = this_1._dragGradients[0];
  58490. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58491. if (this_1._dragGradients.length > 1) {
  58492. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58493. }
  58494. else {
  58495. particle._currentDrag2 = particle._currentDrag1;
  58496. }
  58497. }
  58498. // Color
  58499. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58500. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58501. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58502. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58503. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58504. }
  58505. else {
  58506. particle._currentColorGradient = this_1._colorGradients[0];
  58507. particle._currentColorGradient.getColorToRef(particle.color);
  58508. particle._currentColor1.copyFrom(particle.color);
  58509. if (this_1._colorGradients.length > 1) {
  58510. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58511. }
  58512. else {
  58513. particle._currentColor2.copyFrom(particle.color);
  58514. }
  58515. }
  58516. // Sheet
  58517. if (this_1._isAnimationSheetEnabled) {
  58518. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58519. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58520. }
  58521. // Inherited Velocity
  58522. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58523. // Ramp
  58524. if (this_1._useRampGradients) {
  58525. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58526. }
  58527. // Noise texture coordinates
  58528. if (this_1.noiseTexture) {
  58529. if (particle._randomNoiseCoordinates1) {
  58530. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58531. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58532. }
  58533. else {
  58534. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58535. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58536. }
  58537. }
  58538. // Update the position of the attached sub-emitters to match their attached particle
  58539. particle._inheritParticleInfoToSubEmitters();
  58540. };
  58541. var this_1 = this, step;
  58542. for (var index = 0; index < newParticles; index++) {
  58543. var state_1 = _loop_2();
  58544. if (state_1 === "break")
  58545. break;
  58546. }
  58547. };
  58548. /** @hidden */
  58549. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58550. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58551. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58552. if (useRampGradients === void 0) { useRampGradients = false; }
  58553. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58554. if (isAnimationSheetEnabled) {
  58555. attributeNamesOrOptions.push("cellIndex");
  58556. }
  58557. if (!isBillboardBased) {
  58558. attributeNamesOrOptions.push("direction");
  58559. }
  58560. if (useRampGradients) {
  58561. attributeNamesOrOptions.push("remapData");
  58562. }
  58563. return attributeNamesOrOptions;
  58564. };
  58565. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58566. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58567. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58568. if (isAnimationSheetEnabled) {
  58569. effectCreationOption.push("particlesInfos");
  58570. }
  58571. return effectCreationOption;
  58572. };
  58573. ParticleSystem.prototype._getEffect = function (blendMode) {
  58574. if (this._customEffect) {
  58575. return this._customEffect;
  58576. }
  58577. ;
  58578. var defines = [];
  58579. if (this._scene.clipPlane) {
  58580. defines.push("#define CLIPPLANE");
  58581. }
  58582. if (this._scene.clipPlane2) {
  58583. defines.push("#define CLIPPLANE2");
  58584. }
  58585. if (this._scene.clipPlane3) {
  58586. defines.push("#define CLIPPLANE3");
  58587. }
  58588. if (this._scene.clipPlane4) {
  58589. defines.push("#define CLIPPLANE4");
  58590. }
  58591. if (this._isAnimationSheetEnabled) {
  58592. defines.push("#define ANIMATESHEET");
  58593. }
  58594. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58595. defines.push("#define BLENDMULTIPLYMODE");
  58596. }
  58597. if (this._useRampGradients) {
  58598. defines.push("#define RAMPGRADIENT");
  58599. }
  58600. if (this._isBillboardBased) {
  58601. defines.push("#define BILLBOARD");
  58602. switch (this.billboardMode) {
  58603. case ParticleSystem.BILLBOARDMODE_Y:
  58604. defines.push("#define BILLBOARDY");
  58605. break;
  58606. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58607. defines.push("#define BILLBOARDSTRETCHED");
  58608. break;
  58609. case ParticleSystem.BILLBOARDMODE_ALL:
  58610. default:
  58611. break;
  58612. }
  58613. }
  58614. if (this._imageProcessingConfiguration) {
  58615. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58616. defines.push(this._imageProcessingConfigurationDefines.toString());
  58617. }
  58618. // Effect
  58619. var join = defines.join("\n");
  58620. if (this._cachedDefines !== join) {
  58621. this._cachedDefines = join;
  58622. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58623. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58624. var samplers = ["diffuseSampler", "rampSampler"];
  58625. if (BABYLON.ImageProcessingConfiguration) {
  58626. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58627. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58628. }
  58629. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58630. }
  58631. return this._effect;
  58632. };
  58633. /**
  58634. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58635. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58636. */
  58637. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58638. var _this = this;
  58639. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58640. if (!this._started)
  58641. return;
  58642. if (!preWarmOnly) {
  58643. // Check
  58644. if (!this.isReady())
  58645. return;
  58646. if (this._currentRenderId === this._scene.getRenderId()) {
  58647. return;
  58648. }
  58649. this._currentRenderId = this._scene.getRenderId();
  58650. }
  58651. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58652. // Determine the number of particles we need to create
  58653. var newParticles;
  58654. if (this.manualEmitCount > -1) {
  58655. newParticles = this.manualEmitCount;
  58656. this._newPartsExcess = 0;
  58657. this.manualEmitCount = 0;
  58658. }
  58659. else {
  58660. var rate_1 = this.emitRate;
  58661. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58662. var ratio = this._actualFrame / this.targetStopDuration;
  58663. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58664. if (currentGradient !== _this._currentEmitRateGradient) {
  58665. _this._currentEmitRate1 = _this._currentEmitRate2;
  58666. _this._currentEmitRate2 = nextGradient.getFactor();
  58667. _this._currentEmitRateGradient = currentGradient;
  58668. }
  58669. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58670. });
  58671. }
  58672. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58673. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58674. }
  58675. if (this._newPartsExcess > 1.0) {
  58676. newParticles += this._newPartsExcess >> 0;
  58677. this._newPartsExcess -= this._newPartsExcess >> 0;
  58678. }
  58679. this._alive = false;
  58680. if (!this._stopped) {
  58681. this._actualFrame += this._scaledUpdateSpeed;
  58682. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58683. this.stop();
  58684. }
  58685. else {
  58686. newParticles = 0;
  58687. }
  58688. this._update(newParticles);
  58689. // Stopped?
  58690. if (this._stopped) {
  58691. if (!this._alive) {
  58692. this._started = false;
  58693. if (this.onAnimationEnd) {
  58694. this.onAnimationEnd();
  58695. }
  58696. if (this.disposeOnStop) {
  58697. this._scene._toBeDisposed.push(this);
  58698. }
  58699. }
  58700. }
  58701. if (!preWarmOnly) {
  58702. // Update VBO
  58703. var offset = 0;
  58704. for (var index = 0; index < this._particles.length; index++) {
  58705. var particle = this._particles[index];
  58706. this._appendParticleVertices(offset, particle);
  58707. offset += this._useInstancing ? 1 : 4;
  58708. }
  58709. if (this._vertexBuffer) {
  58710. this._vertexBuffer.update(this._vertexData);
  58711. }
  58712. }
  58713. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58714. this.stop();
  58715. }
  58716. };
  58717. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58718. this._appendParticleVertex(offset++, particle, 0, 0);
  58719. if (!this._useInstancing) {
  58720. this._appendParticleVertex(offset++, particle, 1, 0);
  58721. this._appendParticleVertex(offset++, particle, 1, 1);
  58722. this._appendParticleVertex(offset++, particle, 0, 1);
  58723. }
  58724. };
  58725. /**
  58726. * Rebuilds the particle system.
  58727. */
  58728. ParticleSystem.prototype.rebuild = function () {
  58729. this._createIndexBuffer();
  58730. if (this._vertexBuffer) {
  58731. this._vertexBuffer._rebuild();
  58732. }
  58733. };
  58734. /**
  58735. * Is this system ready to be used/rendered
  58736. * @return true if the system is ready
  58737. */
  58738. ParticleSystem.prototype.isReady = function () {
  58739. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58740. return false;
  58741. }
  58742. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58743. if (!this._getEffect(this.blendMode).isReady()) {
  58744. return false;
  58745. }
  58746. }
  58747. else {
  58748. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58749. return false;
  58750. }
  58751. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58752. return false;
  58753. }
  58754. }
  58755. return true;
  58756. };
  58757. ParticleSystem.prototype._render = function (blendMode) {
  58758. var effect = this._getEffect(blendMode);
  58759. var engine = this._scene.getEngine();
  58760. // Render
  58761. engine.enableEffect(effect);
  58762. var viewMatrix = this._scene.getViewMatrix();
  58763. effect.setTexture("diffuseSampler", this.particleTexture);
  58764. effect.setMatrix("view", viewMatrix);
  58765. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58766. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58767. var baseSize = this.particleTexture.getBaseSize();
  58768. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58769. }
  58770. effect.setVector2("translationPivot", this.translationPivot);
  58771. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58772. if (this._isBillboardBased) {
  58773. var camera = this._scene.activeCamera;
  58774. effect.setVector3("eyePosition", camera.globalPosition);
  58775. }
  58776. if (this._rampGradientsTexture) {
  58777. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58778. }
  58779. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58780. var invView = viewMatrix.clone();
  58781. invView.invert();
  58782. effect.setMatrix("invView", invView);
  58783. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58784. }
  58785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58786. // image processing
  58787. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58788. this._imageProcessingConfiguration.bind(effect);
  58789. }
  58790. // Draw order
  58791. switch (blendMode) {
  58792. case ParticleSystem.BLENDMODE_ADD:
  58793. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58794. break;
  58795. case ParticleSystem.BLENDMODE_ONEONE:
  58796. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58797. break;
  58798. case ParticleSystem.BLENDMODE_STANDARD:
  58799. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58800. break;
  58801. case ParticleSystem.BLENDMODE_MULTIPLY:
  58802. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58803. break;
  58804. }
  58805. if (this._useInstancing) {
  58806. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58807. }
  58808. else {
  58809. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58810. }
  58811. return this._particles.length;
  58812. };
  58813. /**
  58814. * Renders the particle system in its current state.
  58815. * @returns the current number of particles
  58816. */
  58817. ParticleSystem.prototype.render = function () {
  58818. // Check
  58819. if (!this.isReady() || !this._particles.length) {
  58820. return 0;
  58821. }
  58822. var engine = this._scene.getEngine();
  58823. engine.setState(false);
  58824. if (this.forceDepthWrite) {
  58825. engine.setDepthWrite(true);
  58826. }
  58827. var outparticles = 0;
  58828. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58829. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58830. }
  58831. outparticles = this._render(this.blendMode);
  58832. engine.unbindInstanceAttributes();
  58833. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58834. return outparticles;
  58835. };
  58836. /**
  58837. * Disposes the particle system and free the associated resources
  58838. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58839. */
  58840. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58841. if (disposeTexture === void 0) { disposeTexture = true; }
  58842. if (this._vertexBuffer) {
  58843. this._vertexBuffer.dispose();
  58844. this._vertexBuffer = null;
  58845. }
  58846. if (this._spriteBuffer) {
  58847. this._spriteBuffer.dispose();
  58848. this._spriteBuffer = null;
  58849. }
  58850. if (this._indexBuffer) {
  58851. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58852. this._indexBuffer = null;
  58853. }
  58854. if (disposeTexture && this.particleTexture) {
  58855. this.particleTexture.dispose();
  58856. this.particleTexture = null;
  58857. }
  58858. if (disposeTexture && this.noiseTexture) {
  58859. this.noiseTexture.dispose();
  58860. this.noiseTexture = null;
  58861. }
  58862. if (this._rampGradientsTexture) {
  58863. this._rampGradientsTexture.dispose();
  58864. this._rampGradientsTexture = null;
  58865. }
  58866. this._removeFromRoot();
  58867. if (this._subEmitters && this._subEmitters.length) {
  58868. for (var index = 0; index < this._subEmitters.length; index++) {
  58869. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58870. var subEmitter = _a[_i];
  58871. subEmitter.dispose();
  58872. }
  58873. }
  58874. this._subEmitters = [];
  58875. this.subEmitters = [];
  58876. }
  58877. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58878. this.emitter.dispose(true);
  58879. }
  58880. // Remove from scene
  58881. var index = this._scene.particleSystems.indexOf(this);
  58882. if (index > -1) {
  58883. this._scene.particleSystems.splice(index, 1);
  58884. }
  58885. this._scene._activeParticleSystems.dispose();
  58886. // Callback
  58887. this.onDisposeObservable.notifyObservers(this);
  58888. this.onDisposeObservable.clear();
  58889. this.reset();
  58890. };
  58891. // Clone
  58892. /**
  58893. * Clones the particle system.
  58894. * @param name The name of the cloned object
  58895. * @param newEmitter The new emitter to use
  58896. * @returns the cloned particle system
  58897. */
  58898. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58899. var custom = null;
  58900. var program = null;
  58901. if (this.customShader != null) {
  58902. program = this.customShader;
  58903. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58904. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58905. }
  58906. else if (this._customEffect) {
  58907. custom = this._customEffect;
  58908. }
  58909. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58910. result.customShader = program;
  58911. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58912. if (newEmitter === undefined) {
  58913. newEmitter = this.emitter;
  58914. }
  58915. result.noiseTexture = this.noiseTexture;
  58916. result.emitter = newEmitter;
  58917. if (this.particleTexture) {
  58918. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58919. }
  58920. // Clone gradients
  58921. if (this._colorGradients) {
  58922. this._colorGradients.forEach(function (v) {
  58923. result.addColorGradient(v.gradient, v.color1, v.color2);
  58924. });
  58925. }
  58926. if (this._dragGradients) {
  58927. this._dragGradients.forEach(function (v) {
  58928. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58929. });
  58930. }
  58931. if (this._angularSpeedGradients) {
  58932. this._angularSpeedGradients.forEach(function (v) {
  58933. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58934. });
  58935. }
  58936. if (this._emitRateGradients) {
  58937. this._emitRateGradients.forEach(function (v) {
  58938. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58939. });
  58940. }
  58941. if (this._lifeTimeGradients) {
  58942. this._lifeTimeGradients.forEach(function (v) {
  58943. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58944. });
  58945. }
  58946. if (this._limitVelocityGradients) {
  58947. this._limitVelocityGradients.forEach(function (v) {
  58948. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58949. });
  58950. }
  58951. if (this._sizeGradients) {
  58952. this._sizeGradients.forEach(function (v) {
  58953. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58954. });
  58955. }
  58956. if (this._startSizeGradients) {
  58957. this._startSizeGradients.forEach(function (v) {
  58958. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58959. });
  58960. }
  58961. if (this._velocityGradients) {
  58962. this._velocityGradients.forEach(function (v) {
  58963. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58964. });
  58965. }
  58966. if (this._rampGradients) {
  58967. this._rampGradients.forEach(function (v) {
  58968. result.addRampGradient(v.gradient, v.color);
  58969. });
  58970. }
  58971. if (this._colorRemapGradients) {
  58972. this._colorRemapGradients.forEach(function (v) {
  58973. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58974. });
  58975. }
  58976. if (this._alphaRemapGradients) {
  58977. this._alphaRemapGradients.forEach(function (v) {
  58978. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58979. });
  58980. }
  58981. if (!this.preventAutoStart) {
  58982. result.start();
  58983. }
  58984. return result;
  58985. };
  58986. /**
  58987. * Serializes the particle system to a JSON object.
  58988. * @returns the JSON object
  58989. */
  58990. ParticleSystem.prototype.serialize = function () {
  58991. var serializationObject = {};
  58992. ParticleSystem._Serialize(serializationObject, this);
  58993. serializationObject.textureMask = this.textureMask.asArray();
  58994. serializationObject.customShader = this.customShader;
  58995. serializationObject.preventAutoStart = this.preventAutoStart;
  58996. // SubEmitters
  58997. if (this.subEmitters) {
  58998. serializationObject.subEmitters = [];
  58999. if (!this._subEmitters) {
  59000. this._prepareSubEmitterInternalArray();
  59001. }
  59002. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59003. var subs = _a[_i];
  59004. var cell = [];
  59005. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59006. var sub = subs_1[_b];
  59007. cell.push(sub.serialize());
  59008. }
  59009. serializationObject.subEmitters.push(cell);
  59010. }
  59011. }
  59012. return serializationObject;
  59013. };
  59014. /** @hidden */
  59015. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59016. serializationObject.name = particleSystem.name;
  59017. serializationObject.id = particleSystem.id;
  59018. serializationObject.capacity = particleSystem.getCapacity();
  59019. // Emitter
  59020. if (particleSystem.emitter.position) {
  59021. var emitterMesh = particleSystem.emitter;
  59022. serializationObject.emitterId = emitterMesh.id;
  59023. }
  59024. else {
  59025. var emitterPosition = particleSystem.emitter;
  59026. serializationObject.emitter = emitterPosition.asArray();
  59027. }
  59028. // Emitter
  59029. if (particleSystem.particleEmitterType) {
  59030. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59031. }
  59032. if (particleSystem.particleTexture) {
  59033. serializationObject.textureName = particleSystem.particleTexture.name;
  59034. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59035. }
  59036. // Animations
  59037. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59038. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59039. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59040. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59041. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59042. // Particle system
  59043. serializationObject.startDelay = particleSystem.startDelay;
  59044. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59045. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59046. serializationObject.billboardMode = particleSystem.billboardMode;
  59047. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59048. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59049. serializationObject.minSize = particleSystem.minSize;
  59050. serializationObject.maxSize = particleSystem.maxSize;
  59051. serializationObject.minScaleX = particleSystem.minScaleX;
  59052. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59053. serializationObject.minScaleY = particleSystem.minScaleY;
  59054. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59055. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59056. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59057. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59058. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59059. serializationObject.emitRate = particleSystem.emitRate;
  59060. serializationObject.gravity = particleSystem.gravity.asArray();
  59061. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59062. serializationObject.color1 = particleSystem.color1.asArray();
  59063. serializationObject.color2 = particleSystem.color2.asArray();
  59064. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59065. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59066. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59067. serializationObject.blendMode = particleSystem.blendMode;
  59068. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59069. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59070. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59071. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59072. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59073. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59074. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59075. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59076. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59077. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59078. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59079. var colorGradients = particleSystem.getColorGradients();
  59080. if (colorGradients) {
  59081. serializationObject.colorGradients = [];
  59082. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59083. var colorGradient = colorGradients_1[_i];
  59084. var serializedGradient = {
  59085. gradient: colorGradient.gradient,
  59086. color1: colorGradient.color1.asArray()
  59087. };
  59088. if (colorGradient.color2) {
  59089. serializedGradient.color2 = colorGradient.color2.asArray();
  59090. }
  59091. serializationObject.colorGradients.push(serializedGradient);
  59092. }
  59093. }
  59094. var rampGradients = particleSystem.getRampGradients();
  59095. if (rampGradients) {
  59096. serializationObject.rampGradients = [];
  59097. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59098. var rampGradient = rampGradients_1[_a];
  59099. var serializedGradient = {
  59100. gradient: rampGradient.gradient,
  59101. color: rampGradient.color.asArray()
  59102. };
  59103. serializationObject.rampGradients.push(serializedGradient);
  59104. }
  59105. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59106. }
  59107. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59108. if (colorRemapGradients) {
  59109. serializationObject.colorRemapGradients = [];
  59110. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59111. var colorRemapGradient = colorRemapGradients_1[_b];
  59112. var serializedGradient = {
  59113. gradient: colorRemapGradient.gradient,
  59114. factor1: colorRemapGradient.factor1
  59115. };
  59116. if (colorRemapGradient.factor2 !== undefined) {
  59117. serializedGradient.factor2 = colorRemapGradient.factor2;
  59118. }
  59119. serializationObject.colorRemapGradients.push(serializedGradient);
  59120. }
  59121. }
  59122. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59123. if (alphaRemapGradients) {
  59124. serializationObject.alphaRemapGradients = [];
  59125. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59126. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59127. var serializedGradient = {
  59128. gradient: alphaRemapGradient.gradient,
  59129. factor1: alphaRemapGradient.factor1
  59130. };
  59131. if (alphaRemapGradient.factor2 !== undefined) {
  59132. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59133. }
  59134. serializationObject.alphaRemapGradients.push(serializedGradient);
  59135. }
  59136. }
  59137. var sizeGradients = particleSystem.getSizeGradients();
  59138. if (sizeGradients) {
  59139. serializationObject.sizeGradients = [];
  59140. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59141. var sizeGradient = sizeGradients_1[_d];
  59142. var serializedGradient = {
  59143. gradient: sizeGradient.gradient,
  59144. factor1: sizeGradient.factor1
  59145. };
  59146. if (sizeGradient.factor2 !== undefined) {
  59147. serializedGradient.factor2 = sizeGradient.factor2;
  59148. }
  59149. serializationObject.sizeGradients.push(serializedGradient);
  59150. }
  59151. }
  59152. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59153. if (angularSpeedGradients) {
  59154. serializationObject.angularSpeedGradients = [];
  59155. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59156. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59157. var serializedGradient = {
  59158. gradient: angularSpeedGradient.gradient,
  59159. factor1: angularSpeedGradient.factor1
  59160. };
  59161. if (angularSpeedGradient.factor2 !== undefined) {
  59162. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59163. }
  59164. serializationObject.angularSpeedGradients.push(serializedGradient);
  59165. }
  59166. }
  59167. var velocityGradients = particleSystem.getVelocityGradients();
  59168. if (velocityGradients) {
  59169. serializationObject.velocityGradients = [];
  59170. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59171. var velocityGradient = velocityGradients_1[_f];
  59172. var serializedGradient = {
  59173. gradient: velocityGradient.gradient,
  59174. factor1: velocityGradient.factor1
  59175. };
  59176. if (velocityGradient.factor2 !== undefined) {
  59177. serializedGradient.factor2 = velocityGradient.factor2;
  59178. }
  59179. serializationObject.velocityGradients.push(serializedGradient);
  59180. }
  59181. }
  59182. var dragGradients = particleSystem.getDragGradients();
  59183. if (dragGradients) {
  59184. serializationObject.dragyGradients = [];
  59185. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59186. var dragGradient = dragGradients_1[_g];
  59187. var serializedGradient = {
  59188. gradient: dragGradient.gradient,
  59189. factor1: dragGradient.factor1
  59190. };
  59191. if (dragGradient.factor2 !== undefined) {
  59192. serializedGradient.factor2 = dragGradient.factor2;
  59193. }
  59194. serializationObject.dragGradients.push(serializedGradient);
  59195. }
  59196. }
  59197. var emitRateGradients = particleSystem.getEmitRateGradients();
  59198. if (emitRateGradients) {
  59199. serializationObject.emitRateGradients = [];
  59200. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59201. var emitRateGradient = emitRateGradients_1[_h];
  59202. var serializedGradient = {
  59203. gradient: emitRateGradient.gradient,
  59204. factor1: emitRateGradient.factor1
  59205. };
  59206. if (emitRateGradient.factor2 !== undefined) {
  59207. serializedGradient.factor2 = emitRateGradient.factor2;
  59208. }
  59209. serializationObject.emitRateGradients.push(serializedGradient);
  59210. }
  59211. }
  59212. var startSizeGradients = particleSystem.getStartSizeGradients();
  59213. if (startSizeGradients) {
  59214. serializationObject.startSizeGradients = [];
  59215. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59216. var startSizeGradient = startSizeGradients_1[_j];
  59217. var serializedGradient = {
  59218. gradient: startSizeGradient.gradient,
  59219. factor1: startSizeGradient.factor1
  59220. };
  59221. if (startSizeGradient.factor2 !== undefined) {
  59222. serializedGradient.factor2 = startSizeGradient.factor2;
  59223. }
  59224. serializationObject.startSizeGradients.push(serializedGradient);
  59225. }
  59226. }
  59227. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59228. if (lifeTimeGradients) {
  59229. serializationObject.lifeTimeGradients = [];
  59230. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59231. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59232. var serializedGradient = {
  59233. gradient: lifeTimeGradient.gradient,
  59234. factor1: lifeTimeGradient.factor1
  59235. };
  59236. if (lifeTimeGradient.factor2 !== undefined) {
  59237. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59238. }
  59239. serializationObject.lifeTimeGradients.push(serializedGradient);
  59240. }
  59241. }
  59242. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59243. if (limitVelocityGradients) {
  59244. serializationObject.limitVelocityGradients = [];
  59245. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59246. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59247. var serializedGradient = {
  59248. gradient: limitVelocityGradient.gradient,
  59249. factor1: limitVelocityGradient.factor1
  59250. };
  59251. if (limitVelocityGradient.factor2 !== undefined) {
  59252. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59253. }
  59254. serializationObject.limitVelocityGradients.push(serializedGradient);
  59255. }
  59256. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59257. }
  59258. if (particleSystem.noiseTexture) {
  59259. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59260. }
  59261. };
  59262. /** @hidden */
  59263. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59264. // Texture
  59265. if (parsedParticleSystem.textureName) {
  59266. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59267. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59268. }
  59269. // Emitter
  59270. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59271. particleSystem.emitter = BABYLON.Vector3.Zero();
  59272. }
  59273. else if (parsedParticleSystem.emitterId) {
  59274. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59275. }
  59276. else {
  59277. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59278. }
  59279. // Misc.
  59280. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59281. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59282. }
  59283. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59284. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59285. }
  59286. if (parsedParticleSystem.billboardMode !== undefined) {
  59287. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59288. }
  59289. // Animations
  59290. if (parsedParticleSystem.animations) {
  59291. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59292. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59293. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59294. }
  59295. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  59296. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  59297. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  59298. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  59299. }
  59300. if (parsedParticleSystem.autoAnimate) {
  59301. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59302. }
  59303. // Particle system
  59304. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59305. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59306. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59307. particleSystem.minSize = parsedParticleSystem.minSize;
  59308. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59309. if (parsedParticleSystem.minScaleX) {
  59310. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59311. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59312. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59313. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59314. }
  59315. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59316. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59317. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59318. }
  59319. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59320. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59321. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59322. }
  59323. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59324. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59325. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59326. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59327. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59328. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59329. if (parsedParticleSystem.noiseStrength) {
  59330. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59331. }
  59332. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59333. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59334. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59335. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59336. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59337. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59338. if (parsedParticleSystem.colorGradients) {
  59339. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59340. var colorGradient = _a[_i];
  59341. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59342. }
  59343. }
  59344. if (parsedParticleSystem.rampGradients) {
  59345. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59346. var rampGradient = _c[_b];
  59347. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59348. }
  59349. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59350. }
  59351. if (parsedParticleSystem.colorRemapGradients) {
  59352. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59353. var colorRemapGradient = _e[_d];
  59354. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59355. }
  59356. }
  59357. if (parsedParticleSystem.alphaRemapGradients) {
  59358. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59359. var alphaRemapGradient = _g[_f];
  59360. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59361. }
  59362. }
  59363. if (parsedParticleSystem.sizeGradients) {
  59364. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59365. var sizeGradient = _j[_h];
  59366. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59367. }
  59368. }
  59369. if (parsedParticleSystem.sizeGradients) {
  59370. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59371. var sizeGradient = _l[_k];
  59372. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59373. }
  59374. }
  59375. if (parsedParticleSystem.angularSpeedGradients) {
  59376. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59377. var angularSpeedGradient = _o[_m];
  59378. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59379. }
  59380. }
  59381. if (parsedParticleSystem.velocityGradients) {
  59382. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59383. var velocityGradient = _q[_p];
  59384. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59385. }
  59386. }
  59387. if (parsedParticleSystem.dragGradients) {
  59388. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59389. var dragGradient = _s[_r];
  59390. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59391. }
  59392. }
  59393. if (parsedParticleSystem.emitRateGradients) {
  59394. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59395. var emitRateGradient = _u[_t];
  59396. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59397. }
  59398. }
  59399. if (parsedParticleSystem.startSizeGradients) {
  59400. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59401. var startSizeGradient = _w[_v];
  59402. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59403. }
  59404. }
  59405. if (parsedParticleSystem.lifeTimeGradients) {
  59406. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  59407. var lifeTimeGradient = _y[_x];
  59408. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  59409. }
  59410. }
  59411. if (parsedParticleSystem.limitVelocityGradients) {
  59412. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  59413. var limitVelocityGradient = _0[_z];
  59414. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59415. }
  59416. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59417. }
  59418. if (parsedParticleSystem.noiseTexture) {
  59419. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59420. }
  59421. // Emitter
  59422. var emitterType;
  59423. if (parsedParticleSystem.particleEmitterType) {
  59424. switch (parsedParticleSystem.particleEmitterType.type) {
  59425. case "SphereParticleEmitter":
  59426. emitterType = new BABYLON.SphereParticleEmitter();
  59427. break;
  59428. case "SphereDirectedParticleEmitter":
  59429. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59430. break;
  59431. case "ConeEmitter":
  59432. case "ConeParticleEmitter":
  59433. emitterType = new BABYLON.ConeParticleEmitter();
  59434. break;
  59435. case "CylinderParticleEmitter":
  59436. emitterType = new BABYLON.CylinderParticleEmitter();
  59437. break;
  59438. case "HemisphericParticleEmitter":
  59439. emitterType = new BABYLON.HemisphericParticleEmitter();
  59440. break;
  59441. case "BoxEmitter":
  59442. case "BoxParticleEmitter":
  59443. default:
  59444. emitterType = new BABYLON.BoxParticleEmitter();
  59445. break;
  59446. }
  59447. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59448. }
  59449. else {
  59450. emitterType = new BABYLON.BoxParticleEmitter();
  59451. emitterType.parse(parsedParticleSystem);
  59452. }
  59453. particleSystem.particleEmitterType = emitterType;
  59454. // Animation sheet
  59455. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59456. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59457. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59458. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59459. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59460. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59461. };
  59462. /**
  59463. * Parses a JSON object to create a particle system.
  59464. * @param parsedParticleSystem The JSON object to parse
  59465. * @param scene The scene to create the particle system in
  59466. * @param rootUrl The root url to use to load external dependencies like texture
  59467. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  59468. * @returns the Parsed particle system
  59469. */
  59470. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  59471. if (doNotStart === void 0) { doNotStart = false; }
  59472. var name = parsedParticleSystem.name;
  59473. var custom = null;
  59474. var program = null;
  59475. if (parsedParticleSystem.customShader) {
  59476. program = parsedParticleSystem.customShader;
  59477. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59478. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59479. }
  59480. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59481. particleSystem.customShader = program;
  59482. if (parsedParticleSystem.id) {
  59483. particleSystem.id = parsedParticleSystem.id;
  59484. }
  59485. // SubEmitters
  59486. if (parsedParticleSystem.subEmitters) {
  59487. particleSystem.subEmitters = [];
  59488. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59489. var cell = _a[_i];
  59490. var cellArray = [];
  59491. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59492. var sub = cell_1[_b];
  59493. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59494. }
  59495. particleSystem.subEmitters.push(cellArray);
  59496. }
  59497. }
  59498. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59499. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59500. // Auto start
  59501. if (parsedParticleSystem.preventAutoStart) {
  59502. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59503. }
  59504. if (!doNotStart && !particleSystem.preventAutoStart) {
  59505. particleSystem.start();
  59506. }
  59507. return particleSystem;
  59508. };
  59509. /**
  59510. * Billboard mode will only apply to Y axis
  59511. */
  59512. ParticleSystem.BILLBOARDMODE_Y = 2;
  59513. /**
  59514. * Billboard mode will apply to all axes
  59515. */
  59516. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59517. /**
  59518. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59519. */
  59520. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59521. return ParticleSystem;
  59522. }(BABYLON.BaseParticleSystem));
  59523. BABYLON.ParticleSystem = ParticleSystem;
  59524. })(BABYLON || (BABYLON = {}));
  59525. //# sourceMappingURL=babylon.particleSystem.js.map
  59526. var BABYLON;
  59527. (function (BABYLON) {
  59528. /**
  59529. * Particle emitter emitting particles from the inside of a box.
  59530. * It emits the particles randomly between 2 given directions.
  59531. */
  59532. var BoxParticleEmitter = /** @class */ (function () {
  59533. /**
  59534. * Creates a new instance BoxParticleEmitter
  59535. */
  59536. function BoxParticleEmitter() {
  59537. /**
  59538. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59539. */
  59540. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59541. /**
  59542. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59543. */
  59544. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59545. /**
  59546. * 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.
  59547. */
  59548. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59549. /**
  59550. * 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.
  59551. */
  59552. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59553. }
  59554. /**
  59555. * Called by the particle System when the direction is computed for the created particle.
  59556. * @param worldMatrix is the world matrix of the particle system
  59557. * @param directionToUpdate is the direction vector to update with the result
  59558. * @param particle is the particle we are computed the direction for
  59559. */
  59560. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59561. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59562. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59563. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59564. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59565. };
  59566. /**
  59567. * Called by the particle System when the position is computed for the created particle.
  59568. * @param worldMatrix is the world matrix of the particle system
  59569. * @param positionToUpdate is the position vector to update with the result
  59570. * @param particle is the particle we are computed the position for
  59571. */
  59572. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59573. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59574. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59575. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59576. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59577. };
  59578. /**
  59579. * Clones the current emitter and returns a copy of it
  59580. * @returns the new emitter
  59581. */
  59582. BoxParticleEmitter.prototype.clone = function () {
  59583. var newOne = new BoxParticleEmitter();
  59584. BABYLON.Tools.DeepCopy(this, newOne);
  59585. return newOne;
  59586. };
  59587. /**
  59588. * Called by the GPUParticleSystem to setup the update shader
  59589. * @param effect defines the update shader
  59590. */
  59591. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59592. effect.setVector3("direction1", this.direction1);
  59593. effect.setVector3("direction2", this.direction2);
  59594. effect.setVector3("minEmitBox", this.minEmitBox);
  59595. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59596. };
  59597. /**
  59598. * Returns a string to use to update the GPU particles update shader
  59599. * @returns a string containng the defines string
  59600. */
  59601. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59602. return "#define BOXEMITTER";
  59603. };
  59604. /**
  59605. * Returns the string "BoxParticleEmitter"
  59606. * @returns a string containing the class name
  59607. */
  59608. BoxParticleEmitter.prototype.getClassName = function () {
  59609. return "BoxParticleEmitter";
  59610. };
  59611. /**
  59612. * Serializes the particle system to a JSON object.
  59613. * @returns the JSON object
  59614. */
  59615. BoxParticleEmitter.prototype.serialize = function () {
  59616. var serializationObject = {};
  59617. serializationObject.type = this.getClassName();
  59618. serializationObject.direction1 = this.direction1.asArray();
  59619. serializationObject.direction2 = this.direction2.asArray();
  59620. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59621. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59622. return serializationObject;
  59623. };
  59624. /**
  59625. * Parse properties from a JSON object
  59626. * @param serializationObject defines the JSON object
  59627. */
  59628. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59629. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59630. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59631. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59632. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59633. };
  59634. return BoxParticleEmitter;
  59635. }());
  59636. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59637. })(BABYLON || (BABYLON = {}));
  59638. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59639. var BABYLON;
  59640. (function (BABYLON) {
  59641. /**
  59642. * Particle emitter emitting particles from the inside of a cylinder.
  59643. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59644. */
  59645. var CylinderParticleEmitter = /** @class */ (function () {
  59646. /**
  59647. * Creates a new instance CylinderParticleEmitter
  59648. * @param radius the radius of the emission cylinder (1 by default)
  59649. * @param height the height of the emission cylinder (1 by default)
  59650. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59651. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59652. */
  59653. function CylinderParticleEmitter(
  59654. /**
  59655. * The radius of the emission cylinder.
  59656. */
  59657. radius,
  59658. /**
  59659. * The height of the emission cylinder.
  59660. */
  59661. height,
  59662. /**
  59663. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59664. */
  59665. radiusRange,
  59666. /**
  59667. * How much to randomize the particle direction [0-1].
  59668. */
  59669. directionRandomizer) {
  59670. if (radius === void 0) { radius = 1; }
  59671. if (height === void 0) { height = 1; }
  59672. if (radiusRange === void 0) { radiusRange = 1; }
  59673. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59674. this.radius = radius;
  59675. this.height = height;
  59676. this.radiusRange = radiusRange;
  59677. this.directionRandomizer = directionRandomizer;
  59678. }
  59679. /**
  59680. * Called by the particle System when the direction is computed for the created particle.
  59681. * @param worldMatrix is the world matrix of the particle system
  59682. * @param directionToUpdate is the direction vector to update with the result
  59683. * @param particle is the particle we are computed the direction for
  59684. */
  59685. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59686. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59687. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59688. var angle = Math.atan2(direction.x, direction.z);
  59689. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59690. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59691. direction.x = Math.sin(angle);
  59692. direction.z = Math.cos(angle);
  59693. direction.normalize();
  59694. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59695. };
  59696. /**
  59697. * Called by the particle System when the position is computed for the created particle.
  59698. * @param worldMatrix is the world matrix of the particle system
  59699. * @param positionToUpdate is the position vector to update with the result
  59700. * @param particle is the particle we are computed the position for
  59701. */
  59702. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59703. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59704. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59705. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59706. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59707. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59708. var xPos = positionRadius * Math.cos(angle);
  59709. var zPos = positionRadius * Math.sin(angle);
  59710. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59711. };
  59712. /**
  59713. * Clones the current emitter and returns a copy of it
  59714. * @returns the new emitter
  59715. */
  59716. CylinderParticleEmitter.prototype.clone = function () {
  59717. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59718. BABYLON.Tools.DeepCopy(this, newOne);
  59719. return newOne;
  59720. };
  59721. /**
  59722. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59723. * @param effect defines the update shader
  59724. */
  59725. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59726. effect.setFloat("radius", this.radius);
  59727. effect.setFloat("height", this.height);
  59728. effect.setFloat("radiusRange", this.radiusRange);
  59729. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59730. };
  59731. /**
  59732. * Returns a string to use to update the GPU particles update shader
  59733. * @returns a string containng the defines string
  59734. */
  59735. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59736. return "#define CYLINDEREMITTER";
  59737. };
  59738. /**
  59739. * Returns the string "CylinderParticleEmitter"
  59740. * @returns a string containing the class name
  59741. */
  59742. CylinderParticleEmitter.prototype.getClassName = function () {
  59743. return "CylinderParticleEmitter";
  59744. };
  59745. /**
  59746. * Serializes the particle system to a JSON object.
  59747. * @returns the JSON object
  59748. */
  59749. CylinderParticleEmitter.prototype.serialize = function () {
  59750. var serializationObject = {};
  59751. serializationObject.type = this.getClassName();
  59752. serializationObject.radius = this.radius;
  59753. serializationObject.height = this.height;
  59754. serializationObject.radiusRange = this.radiusRange;
  59755. serializationObject.directionRandomizer = this.directionRandomizer;
  59756. return serializationObject;
  59757. };
  59758. /**
  59759. * Parse properties from a JSON object
  59760. * @param serializationObject defines the JSON object
  59761. */
  59762. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59763. this.radius = serializationObject.radius;
  59764. this.height = serializationObject.height;
  59765. this.radiusRange = serializationObject.radiusRange;
  59766. this.directionRandomizer = serializationObject.directionRandomizer;
  59767. };
  59768. return CylinderParticleEmitter;
  59769. }());
  59770. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59771. /**
  59772. * Particle emitter emitting particles from the inside of a cylinder.
  59773. * It emits the particles randomly between two vectors.
  59774. */
  59775. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59776. __extends(CylinderDirectedParticleEmitter, _super);
  59777. /**
  59778. * Creates a new instance CylinderDirectedParticleEmitter
  59779. * @param radius the radius of the emission cylinder (1 by default)
  59780. * @param height the height of the emission cylinder (1 by default)
  59781. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59782. * @param direction1 the min limit of the emission direction (up vector by default)
  59783. * @param direction2 the max limit of the emission direction (up vector by default)
  59784. */
  59785. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59786. /**
  59787. * The min limit of the emission direction.
  59788. */
  59789. direction1,
  59790. /**
  59791. * The max limit of the emission direction.
  59792. */
  59793. direction2) {
  59794. if (radius === void 0) { radius = 1; }
  59795. if (height === void 0) { height = 1; }
  59796. if (radiusRange === void 0) { radiusRange = 1; }
  59797. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59798. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59799. var _this = _super.call(this, radius, height, radiusRange) || this;
  59800. _this.direction1 = direction1;
  59801. _this.direction2 = direction2;
  59802. return _this;
  59803. }
  59804. /**
  59805. * Called by the particle System when the direction is computed for the created particle.
  59806. * @param worldMatrix is the world matrix of the particle system
  59807. * @param directionToUpdate is the direction vector to update with the result
  59808. * @param particle is the particle we are computed the direction for
  59809. */
  59810. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59811. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59812. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59813. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59814. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59815. };
  59816. /**
  59817. * Clones the current emitter and returns a copy of it
  59818. * @returns the new emitter
  59819. */
  59820. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59821. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59822. BABYLON.Tools.DeepCopy(this, newOne);
  59823. return newOne;
  59824. };
  59825. /**
  59826. * Called by the GPUParticleSystem to setup the update shader
  59827. * @param effect defines the update shader
  59828. */
  59829. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59830. effect.setFloat("radius", this.radius);
  59831. effect.setFloat("height", this.height);
  59832. effect.setFloat("radiusRange", this.radiusRange);
  59833. effect.setVector3("direction1", this.direction1);
  59834. effect.setVector3("direction2", this.direction2);
  59835. };
  59836. /**
  59837. * Returns a string to use to update the GPU particles update shader
  59838. * @returns a string containng the defines string
  59839. */
  59840. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59841. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59842. };
  59843. /**
  59844. * Returns the string "CylinderDirectedParticleEmitter"
  59845. * @returns a string containing the class name
  59846. */
  59847. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59848. return "CylinderDirectedParticleEmitter";
  59849. };
  59850. /**
  59851. * Serializes the particle system to a JSON object.
  59852. * @returns the JSON object
  59853. */
  59854. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59855. var serializationObject = _super.prototype.serialize.call(this);
  59856. serializationObject.direction1 = this.direction1.asArray();
  59857. serializationObject.direction2 = this.direction2.asArray();
  59858. return serializationObject;
  59859. };
  59860. /**
  59861. * Parse properties from a JSON object
  59862. * @param serializationObject defines the JSON object
  59863. */
  59864. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59865. _super.prototype.parse.call(this, serializationObject);
  59866. this.direction1.copyFrom(serializationObject.direction1);
  59867. this.direction2.copyFrom(serializationObject.direction2);
  59868. };
  59869. return CylinderDirectedParticleEmitter;
  59870. }(CylinderParticleEmitter));
  59871. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59872. })(BABYLON || (BABYLON = {}));
  59873. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59874. var BABYLON;
  59875. (function (BABYLON) {
  59876. /**
  59877. * Particle emitter emitting particles from the inside of a cone.
  59878. * It emits the particles alongside the cone volume from the base to the particle.
  59879. * The emission direction might be randomized.
  59880. */
  59881. var ConeParticleEmitter = /** @class */ (function () {
  59882. /**
  59883. * Creates a new instance ConeParticleEmitter
  59884. * @param radius the radius of the emission cone (1 by default)
  59885. * @param angles the cone base angle (PI by default)
  59886. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59887. */
  59888. function ConeParticleEmitter(radius, angle,
  59889. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59890. directionRandomizer) {
  59891. if (radius === void 0) { radius = 1; }
  59892. if (angle === void 0) { angle = Math.PI; }
  59893. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59894. this.directionRandomizer = directionRandomizer;
  59895. /**
  59896. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59897. */
  59898. this.radiusRange = 1;
  59899. /**
  59900. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59901. */
  59902. this.heightRange = 1;
  59903. /**
  59904. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59905. */
  59906. this.emitFromSpawnPointOnly = false;
  59907. this.angle = angle;
  59908. this.radius = radius;
  59909. }
  59910. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59911. /**
  59912. * Gets or sets the radius of the emission cone
  59913. */
  59914. get: function () {
  59915. return this._radius;
  59916. },
  59917. set: function (value) {
  59918. this._radius = value;
  59919. this._buildHeight();
  59920. },
  59921. enumerable: true,
  59922. configurable: true
  59923. });
  59924. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59925. /**
  59926. * Gets or sets the angle of the emission cone
  59927. */
  59928. get: function () {
  59929. return this._angle;
  59930. },
  59931. set: function (value) {
  59932. this._angle = value;
  59933. this._buildHeight();
  59934. },
  59935. enumerable: true,
  59936. configurable: true
  59937. });
  59938. ConeParticleEmitter.prototype._buildHeight = function () {
  59939. if (this._angle !== 0) {
  59940. this._height = this._radius / Math.tan(this._angle / 2);
  59941. }
  59942. else {
  59943. this._height = 1;
  59944. }
  59945. };
  59946. /**
  59947. * Called by the particle System when the direction is computed for the created particle.
  59948. * @param worldMatrix is the world matrix of the particle system
  59949. * @param directionToUpdate is the direction vector to update with the result
  59950. * @param particle is the particle we are computed the direction for
  59951. */
  59952. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59953. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59954. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59955. }
  59956. else {
  59957. // measure the direction Vector from the emitter to the particle.
  59958. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59959. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59960. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59961. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59962. direction.x += randX;
  59963. direction.y += randY;
  59964. direction.z += randZ;
  59965. direction.normalize();
  59966. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59967. }
  59968. };
  59969. /**
  59970. * Called by the particle System when the position is computed for the created particle.
  59971. * @param worldMatrix is the world matrix of the particle system
  59972. * @param positionToUpdate is the position vector to update with the result
  59973. * @param particle is the particle we are computed the position for
  59974. */
  59975. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59976. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59977. var h;
  59978. if (!this.emitFromSpawnPointOnly) {
  59979. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59980. // Better distribution in a cone at normal angles.
  59981. h = 1 - h * h;
  59982. }
  59983. else {
  59984. h = 0.0001;
  59985. }
  59986. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59987. radius = radius * h;
  59988. var randX = radius * Math.sin(s);
  59989. var randZ = radius * Math.cos(s);
  59990. var randY = h * this._height;
  59991. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59992. };
  59993. /**
  59994. * Clones the current emitter and returns a copy of it
  59995. * @returns the new emitter
  59996. */
  59997. ConeParticleEmitter.prototype.clone = function () {
  59998. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59999. BABYLON.Tools.DeepCopy(this, newOne);
  60000. return newOne;
  60001. };
  60002. /**
  60003. * Called by the GPUParticleSystem to setup the update shader
  60004. * @param effect defines the update shader
  60005. */
  60006. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60007. effect.setFloat2("radius", this._radius, this.radiusRange);
  60008. effect.setFloat("coneAngle", this._angle);
  60009. effect.setFloat2("height", this._height, this.heightRange);
  60010. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60011. };
  60012. /**
  60013. * Returns a string to use to update the GPU particles update shader
  60014. * @returns a string containng the defines string
  60015. */
  60016. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60017. var defines = "#define CONEEMITTER";
  60018. if (this.emitFromSpawnPointOnly) {
  60019. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60020. }
  60021. return defines;
  60022. };
  60023. /**
  60024. * Returns the string "ConeParticleEmitter"
  60025. * @returns a string containing the class name
  60026. */
  60027. ConeParticleEmitter.prototype.getClassName = function () {
  60028. return "ConeParticleEmitter";
  60029. };
  60030. /**
  60031. * Serializes the particle system to a JSON object.
  60032. * @returns the JSON object
  60033. */
  60034. ConeParticleEmitter.prototype.serialize = function () {
  60035. var serializationObject = {};
  60036. serializationObject.type = this.getClassName();
  60037. serializationObject.radius = this._radius;
  60038. serializationObject.angle = this._angle;
  60039. serializationObject.directionRandomizer = this.directionRandomizer;
  60040. return serializationObject;
  60041. };
  60042. /**
  60043. * Parse properties from a JSON object
  60044. * @param serializationObject defines the JSON object
  60045. */
  60046. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60047. this.radius = serializationObject.radius;
  60048. this.angle = serializationObject.angle;
  60049. this.directionRandomizer = serializationObject.directionRandomizer;
  60050. };
  60051. return ConeParticleEmitter;
  60052. }());
  60053. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60054. })(BABYLON || (BABYLON = {}));
  60055. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60056. var BABYLON;
  60057. (function (BABYLON) {
  60058. /**
  60059. * Particle emitter emitting particles from the inside of a sphere.
  60060. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60061. */
  60062. var SphereParticleEmitter = /** @class */ (function () {
  60063. /**
  60064. * Creates a new instance SphereParticleEmitter
  60065. * @param radius the radius of the emission sphere (1 by default)
  60066. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60067. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60068. */
  60069. function SphereParticleEmitter(
  60070. /**
  60071. * The radius of the emission sphere.
  60072. */
  60073. radius,
  60074. /**
  60075. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60076. */
  60077. radiusRange,
  60078. /**
  60079. * How much to randomize the particle direction [0-1].
  60080. */
  60081. directionRandomizer) {
  60082. if (radius === void 0) { radius = 1; }
  60083. if (radiusRange === void 0) { radiusRange = 1; }
  60084. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60085. this.radius = radius;
  60086. this.radiusRange = radiusRange;
  60087. this.directionRandomizer = directionRandomizer;
  60088. }
  60089. /**
  60090. * Called by the particle System when the direction is computed for the created particle.
  60091. * @param worldMatrix is the world matrix of the particle system
  60092. * @param directionToUpdate is the direction vector to update with the result
  60093. * @param particle is the particle we are computed the direction for
  60094. */
  60095. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60096. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60097. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60098. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60099. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60100. direction.x += randX;
  60101. direction.y += randY;
  60102. direction.z += randZ;
  60103. direction.normalize();
  60104. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60105. };
  60106. /**
  60107. * Called by the particle System when the position is computed for the created particle.
  60108. * @param worldMatrix is the world matrix of the particle system
  60109. * @param positionToUpdate is the position vector to update with the result
  60110. * @param particle is the particle we are computed the position for
  60111. */
  60112. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60113. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60114. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60115. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60116. var theta = Math.acos(2 * v - 1);
  60117. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60118. var randY = randRadius * Math.cos(theta);
  60119. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60120. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60121. };
  60122. /**
  60123. * Clones the current emitter and returns a copy of it
  60124. * @returns the new emitter
  60125. */
  60126. SphereParticleEmitter.prototype.clone = function () {
  60127. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60128. BABYLON.Tools.DeepCopy(this, newOne);
  60129. return newOne;
  60130. };
  60131. /**
  60132. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60133. * @param effect defines the update shader
  60134. */
  60135. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60136. effect.setFloat("radius", this.radius);
  60137. effect.setFloat("radiusRange", this.radiusRange);
  60138. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60139. };
  60140. /**
  60141. * Returns a string to use to update the GPU particles update shader
  60142. * @returns a string containng the defines string
  60143. */
  60144. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60145. return "#define SPHEREEMITTER";
  60146. };
  60147. /**
  60148. * Returns the string "SphereParticleEmitter"
  60149. * @returns a string containing the class name
  60150. */
  60151. SphereParticleEmitter.prototype.getClassName = function () {
  60152. return "SphereParticleEmitter";
  60153. };
  60154. /**
  60155. * Serializes the particle system to a JSON object.
  60156. * @returns the JSON object
  60157. */
  60158. SphereParticleEmitter.prototype.serialize = function () {
  60159. var serializationObject = {};
  60160. serializationObject.type = this.getClassName();
  60161. serializationObject.radius = this.radius;
  60162. serializationObject.radiusRange = this.radiusRange;
  60163. serializationObject.directionRandomizer = this.directionRandomizer;
  60164. return serializationObject;
  60165. };
  60166. /**
  60167. * Parse properties from a JSON object
  60168. * @param serializationObject defines the JSON object
  60169. */
  60170. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60171. this.radius = serializationObject.radius;
  60172. this.radiusRange = serializationObject.radiusRange;
  60173. this.directionRandomizer = serializationObject.directionRandomizer;
  60174. };
  60175. return SphereParticleEmitter;
  60176. }());
  60177. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60178. /**
  60179. * Particle emitter emitting particles from the inside of a sphere.
  60180. * It emits the particles randomly between two vectors.
  60181. */
  60182. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60183. __extends(SphereDirectedParticleEmitter, _super);
  60184. /**
  60185. * Creates a new instance SphereDirectedParticleEmitter
  60186. * @param radius the radius of the emission sphere (1 by default)
  60187. * @param direction1 the min limit of the emission direction (up vector by default)
  60188. * @param direction2 the max limit of the emission direction (up vector by default)
  60189. */
  60190. function SphereDirectedParticleEmitter(radius,
  60191. /**
  60192. * The min limit of the emission direction.
  60193. */
  60194. direction1,
  60195. /**
  60196. * The max limit of the emission direction.
  60197. */
  60198. direction2) {
  60199. if (radius === void 0) { radius = 1; }
  60200. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60201. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60202. var _this = _super.call(this, radius) || this;
  60203. _this.direction1 = direction1;
  60204. _this.direction2 = direction2;
  60205. return _this;
  60206. }
  60207. /**
  60208. * Called by the particle System when the direction is computed for the created particle.
  60209. * @param worldMatrix is the world matrix of the particle system
  60210. * @param directionToUpdate is the direction vector to update with the result
  60211. * @param particle is the particle we are computed the direction for
  60212. */
  60213. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60214. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60215. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60216. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60217. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60218. };
  60219. /**
  60220. * Clones the current emitter and returns a copy of it
  60221. * @returns the new emitter
  60222. */
  60223. SphereDirectedParticleEmitter.prototype.clone = function () {
  60224. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60225. BABYLON.Tools.DeepCopy(this, newOne);
  60226. return newOne;
  60227. };
  60228. /**
  60229. * Called by the GPUParticleSystem to setup the update shader
  60230. * @param effect defines the update shader
  60231. */
  60232. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60233. effect.setFloat("radius", this.radius);
  60234. effect.setFloat("radiusRange", this.radiusRange);
  60235. effect.setVector3("direction1", this.direction1);
  60236. effect.setVector3("direction2", this.direction2);
  60237. };
  60238. /**
  60239. * Returns a string to use to update the GPU particles update shader
  60240. * @returns a string containng the defines string
  60241. */
  60242. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60243. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60244. };
  60245. /**
  60246. * Returns the string "SphereDirectedParticleEmitter"
  60247. * @returns a string containing the class name
  60248. */
  60249. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60250. return "SphereDirectedParticleEmitter";
  60251. };
  60252. /**
  60253. * Serializes the particle system to a JSON object.
  60254. * @returns the JSON object
  60255. */
  60256. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60257. var serializationObject = _super.prototype.serialize.call(this);
  60258. serializationObject.direction1 = this.direction1.asArray();
  60259. serializationObject.direction2 = this.direction2.asArray();
  60260. return serializationObject;
  60261. };
  60262. /**
  60263. * Parse properties from a JSON object
  60264. * @param serializationObject defines the JSON object
  60265. */
  60266. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60267. _super.prototype.parse.call(this, serializationObject);
  60268. this.direction1.copyFrom(serializationObject.direction1);
  60269. this.direction2.copyFrom(serializationObject.direction2);
  60270. };
  60271. return SphereDirectedParticleEmitter;
  60272. }(SphereParticleEmitter));
  60273. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60274. })(BABYLON || (BABYLON = {}));
  60275. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60276. var BABYLON;
  60277. (function (BABYLON) {
  60278. /**
  60279. * Particle emitter emitting particles from the inside of a hemisphere.
  60280. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60281. */
  60282. var HemisphericParticleEmitter = /** @class */ (function () {
  60283. /**
  60284. * Creates a new instance HemisphericParticleEmitter
  60285. * @param radius the radius of the emission hemisphere (1 by default)
  60286. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60287. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60288. */
  60289. function HemisphericParticleEmitter(
  60290. /**
  60291. * The radius of the emission hemisphere.
  60292. */
  60293. radius,
  60294. /**
  60295. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60296. */
  60297. radiusRange,
  60298. /**
  60299. * How much to randomize the particle direction [0-1].
  60300. */
  60301. directionRandomizer) {
  60302. if (radius === void 0) { radius = 1; }
  60303. if (radiusRange === void 0) { radiusRange = 1; }
  60304. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60305. this.radius = radius;
  60306. this.radiusRange = radiusRange;
  60307. this.directionRandomizer = directionRandomizer;
  60308. }
  60309. /**
  60310. * Called by the particle System when the direction is computed for the created particle.
  60311. * @param worldMatrix is the world matrix of the particle system
  60312. * @param directionToUpdate is the direction vector to update with the result
  60313. * @param particle is the particle we are computed the direction for
  60314. */
  60315. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60316. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60317. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60318. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60319. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60320. direction.x += randX;
  60321. direction.y += randY;
  60322. direction.z += randZ;
  60323. direction.normalize();
  60324. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60325. };
  60326. /**
  60327. * Called by the particle System when the position is computed for the created particle.
  60328. * @param worldMatrix is the world matrix of the particle system
  60329. * @param positionToUpdate is the position vector to update with the result
  60330. * @param particle is the particle we are computed the position for
  60331. */
  60332. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60333. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60334. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60335. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60336. var theta = Math.acos(2 * v - 1);
  60337. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60338. var randY = randRadius * Math.cos(theta);
  60339. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60340. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60341. };
  60342. /**
  60343. * Clones the current emitter and returns a copy of it
  60344. * @returns the new emitter
  60345. */
  60346. HemisphericParticleEmitter.prototype.clone = function () {
  60347. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60348. BABYLON.Tools.DeepCopy(this, newOne);
  60349. return newOne;
  60350. };
  60351. /**
  60352. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60353. * @param effect defines the update shader
  60354. */
  60355. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60356. effect.setFloat("radius", this.radius);
  60357. effect.setFloat("radiusRange", this.radiusRange);
  60358. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60359. };
  60360. /**
  60361. * Returns a string to use to update the GPU particles update shader
  60362. * @returns a string containng the defines string
  60363. */
  60364. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60365. return "#define HEMISPHERICEMITTER";
  60366. };
  60367. /**
  60368. * Returns the string "HemisphericParticleEmitter"
  60369. * @returns a string containing the class name
  60370. */
  60371. HemisphericParticleEmitter.prototype.getClassName = function () {
  60372. return "HemisphericParticleEmitter";
  60373. };
  60374. /**
  60375. * Serializes the particle system to a JSON object.
  60376. * @returns the JSON object
  60377. */
  60378. HemisphericParticleEmitter.prototype.serialize = function () {
  60379. var serializationObject = {};
  60380. serializationObject.type = this.getClassName();
  60381. serializationObject.radius = this.radius;
  60382. serializationObject.radiusRange = this.radiusRange;
  60383. serializationObject.directionRandomizer = this.directionRandomizer;
  60384. return serializationObject;
  60385. };
  60386. /**
  60387. * Parse properties from a JSON object
  60388. * @param serializationObject defines the JSON object
  60389. */
  60390. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60391. this.radius = serializationObject.radius;
  60392. this.radiusRange = serializationObject.radiusRange;
  60393. this.directionRandomizer = serializationObject.directionRandomizer;
  60394. };
  60395. return HemisphericParticleEmitter;
  60396. }());
  60397. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60398. })(BABYLON || (BABYLON = {}));
  60399. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60400. var BABYLON;
  60401. (function (BABYLON) {
  60402. /**
  60403. * Particle emitter emitting particles from a point.
  60404. * It emits the particles randomly between 2 given directions.
  60405. */
  60406. var PointParticleEmitter = /** @class */ (function () {
  60407. /**
  60408. * Creates a new instance PointParticleEmitter
  60409. */
  60410. function PointParticleEmitter() {
  60411. /**
  60412. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60413. */
  60414. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60415. /**
  60416. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60417. */
  60418. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60419. }
  60420. /**
  60421. * Called by the particle System when the direction is computed for the created particle.
  60422. * @param worldMatrix is the world matrix of the particle system
  60423. * @param directionToUpdate is the direction vector to update with the result
  60424. * @param particle is the particle we are computed the direction for
  60425. */
  60426. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60427. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60428. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60429. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60430. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60431. };
  60432. /**
  60433. * Called by the particle System when the position is computed for the created particle.
  60434. * @param worldMatrix is the world matrix of the particle system
  60435. * @param positionToUpdate is the position vector to update with the result
  60436. * @param particle is the particle we are computed the position for
  60437. */
  60438. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60439. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60440. };
  60441. /**
  60442. * Clones the current emitter and returns a copy of it
  60443. * @returns the new emitter
  60444. */
  60445. PointParticleEmitter.prototype.clone = function () {
  60446. var newOne = new PointParticleEmitter();
  60447. BABYLON.Tools.DeepCopy(this, newOne);
  60448. return newOne;
  60449. };
  60450. /**
  60451. * Called by the GPUParticleSystem to setup the update shader
  60452. * @param effect defines the update shader
  60453. */
  60454. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60455. effect.setVector3("direction1", this.direction1);
  60456. effect.setVector3("direction2", this.direction2);
  60457. };
  60458. /**
  60459. * Returns a string to use to update the GPU particles update shader
  60460. * @returns a string containng the defines string
  60461. */
  60462. PointParticleEmitter.prototype.getEffectDefines = function () {
  60463. return "#define POINTEMITTER";
  60464. };
  60465. /**
  60466. * Returns the string "PointParticleEmitter"
  60467. * @returns a string containing the class name
  60468. */
  60469. PointParticleEmitter.prototype.getClassName = function () {
  60470. return "PointParticleEmitter";
  60471. };
  60472. /**
  60473. * Serializes the particle system to a JSON object.
  60474. * @returns the JSON object
  60475. */
  60476. PointParticleEmitter.prototype.serialize = function () {
  60477. var serializationObject = {};
  60478. serializationObject.type = this.getClassName();
  60479. serializationObject.direction1 = this.direction1.asArray();
  60480. serializationObject.direction2 = this.direction2.asArray();
  60481. return serializationObject;
  60482. };
  60483. /**
  60484. * Parse properties from a JSON object
  60485. * @param serializationObject defines the JSON object
  60486. */
  60487. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60488. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60489. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60490. };
  60491. return PointParticleEmitter;
  60492. }());
  60493. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60494. })(BABYLON || (BABYLON = {}));
  60495. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60496. var BABYLON;
  60497. (function (BABYLON) {
  60498. // Adds the parsers to the scene parsers.
  60499. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60500. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60501. if (!individualParser) {
  60502. return;
  60503. }
  60504. // Particles Systems
  60505. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60506. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60507. var parsedParticleSystem = parsedData.particleSystems[index];
  60508. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60509. }
  60510. }
  60511. });
  60512. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60513. if (parsedParticleSystem.activeParticleCount) {
  60514. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60515. return ps;
  60516. }
  60517. else {
  60518. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60519. return ps;
  60520. }
  60521. });
  60522. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60523. if (uniformsNames === void 0) { uniformsNames = []; }
  60524. if (samplers === void 0) { samplers = []; }
  60525. if (defines === void 0) { defines = ""; }
  60526. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60527. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60528. if (defines.indexOf(" BILLBOARD") === -1) {
  60529. defines += "\n#define BILLBOARD\n";
  60530. }
  60531. if (samplers.indexOf("diffuseSampler") === -1) {
  60532. samplers.push("diffuseSampler");
  60533. }
  60534. return this.createEffect({
  60535. vertex: "particles",
  60536. fragmentElement: fragmentName
  60537. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60538. };
  60539. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60540. var results = new Array();
  60541. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60542. var particleSystem = this.getScene().particleSystems[index];
  60543. if (particleSystem.emitter === this) {
  60544. results.push(particleSystem);
  60545. }
  60546. }
  60547. return results;
  60548. };
  60549. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60550. var results = new Array();
  60551. var descendants = this.getDescendants();
  60552. descendants.push(this);
  60553. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60554. var particleSystem = this.getScene().particleSystems[index];
  60555. var emitter = particleSystem.emitter;
  60556. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60557. results.push(particleSystem);
  60558. }
  60559. }
  60560. return results;
  60561. };
  60562. })(BABYLON || (BABYLON = {}));
  60563. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60564. var BABYLON;
  60565. (function (BABYLON) {
  60566. /**
  60567. * Type of sub emitter
  60568. */
  60569. var SubEmitterType;
  60570. (function (SubEmitterType) {
  60571. /**
  60572. * Attached to the particle over it's lifetime
  60573. */
  60574. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60575. /**
  60576. * Created when the particle dies
  60577. */
  60578. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60579. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60580. /**
  60581. * Sub emitter class used to emit particles from an existing particle
  60582. */
  60583. var SubEmitter = /** @class */ (function () {
  60584. /**
  60585. * Creates a sub emitter
  60586. * @param particleSystem the particle system to be used by the sub emitter
  60587. */
  60588. function SubEmitter(
  60589. /**
  60590. * the particle system to be used by the sub emitter
  60591. */
  60592. particleSystem) {
  60593. this.particleSystem = particleSystem;
  60594. /**
  60595. * Type of the submitter (Default: END)
  60596. */
  60597. this.type = SubEmitterType.END;
  60598. /**
  60599. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  60600. * Note: This only is supported when using an emitter of type Mesh
  60601. */
  60602. this.inheritDirection = false;
  60603. /**
  60604. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60605. */
  60606. this.inheritedVelocityAmount = 0;
  60607. }
  60608. /**
  60609. * Clones the sub emitter
  60610. * @returns the cloned sub emitter
  60611. */
  60612. SubEmitter.prototype.clone = function () {
  60613. // Clone particle system
  60614. var emitter = this.particleSystem.emitter;
  60615. if (!emitter) {
  60616. emitter = new BABYLON.Vector3();
  60617. }
  60618. else if (emitter instanceof BABYLON.Vector3) {
  60619. emitter = emitter.clone();
  60620. }
  60621. else if (emitter instanceof BABYLON.AbstractMesh) {
  60622. emitter = new BABYLON.Mesh("", emitter.getScene());
  60623. emitter.isVisible = false;
  60624. }
  60625. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60626. // Clone properties
  60627. clone.type = this.type;
  60628. clone.inheritDirection = this.inheritDirection;
  60629. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60630. clone.particleSystem._disposeEmitterOnDispose = true;
  60631. clone.particleSystem.disposeOnStop = true;
  60632. return clone;
  60633. };
  60634. /**
  60635. * Serialize current object to a JSON object
  60636. * @returns the serialized object
  60637. */
  60638. SubEmitter.prototype.serialize = function () {
  60639. var serializationObject = {};
  60640. serializationObject.type = this.type;
  60641. serializationObject.inheritDirection = this.inheritDirection;
  60642. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60643. serializationObject.particleSystem = this.particleSystem.serialize();
  60644. return serializationObject;
  60645. };
  60646. /**
  60647. * Creates a new SubEmitter from a serialized JSON version
  60648. * @param serializationObject defines the JSON object to read from
  60649. * @param scene defines the hosting scene
  60650. * @param rootUrl defines the rootUrl for data loading
  60651. * @returns a new SubEmitter
  60652. */
  60653. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60654. var system = serializationObject.particleSystem;
  60655. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60656. subEmitter.type = serializationObject.type;
  60657. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60658. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60659. subEmitter.particleSystem._isSubEmitter = true;
  60660. return subEmitter;
  60661. };
  60662. /** Release associated resources */
  60663. SubEmitter.prototype.dispose = function () {
  60664. this.particleSystem.dispose();
  60665. };
  60666. return SubEmitter;
  60667. }());
  60668. BABYLON.SubEmitter = SubEmitter;
  60669. })(BABYLON || (BABYLON = {}));
  60670. //# sourceMappingURL=babylon.subEmitter.js.map
  60671. var BABYLON;
  60672. (function (BABYLON) {
  60673. var ShaderMaterial = /** @class */ (function (_super) {
  60674. __extends(ShaderMaterial, _super);
  60675. function ShaderMaterial(name, scene, shaderPath, options) {
  60676. var _this = _super.call(this, name, scene) || this;
  60677. _this._textures = {};
  60678. _this._textureArrays = {};
  60679. _this._floats = {};
  60680. _this._ints = {};
  60681. _this._floatsArrays = {};
  60682. _this._colors3 = {};
  60683. _this._colors3Arrays = {};
  60684. _this._colors4 = {};
  60685. _this._vectors2 = {};
  60686. _this._vectors3 = {};
  60687. _this._vectors4 = {};
  60688. _this._matrices = {};
  60689. _this._matrices3x3 = {};
  60690. _this._matrices2x2 = {};
  60691. _this._vectors2Arrays = {};
  60692. _this._vectors3Arrays = {};
  60693. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60694. _this._shaderPath = shaderPath;
  60695. options.needAlphaBlending = options.needAlphaBlending || false;
  60696. options.needAlphaTesting = options.needAlphaTesting || false;
  60697. options.attributes = options.attributes || ["position", "normal", "uv"];
  60698. options.uniforms = options.uniforms || ["worldViewProjection"];
  60699. options.uniformBuffers = options.uniformBuffers || [];
  60700. options.samplers = options.samplers || [];
  60701. options.defines = options.defines || [];
  60702. _this._options = options;
  60703. return _this;
  60704. }
  60705. ShaderMaterial.prototype.getClassName = function () {
  60706. return "ShaderMaterial";
  60707. };
  60708. ShaderMaterial.prototype.needAlphaBlending = function () {
  60709. return this._options.needAlphaBlending;
  60710. };
  60711. ShaderMaterial.prototype.needAlphaTesting = function () {
  60712. return this._options.needAlphaTesting;
  60713. };
  60714. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60715. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60716. this._options.uniforms.push(uniformName);
  60717. }
  60718. };
  60719. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60720. if (this._options.samplers.indexOf(name) === -1) {
  60721. this._options.samplers.push(name);
  60722. }
  60723. this._textures[name] = texture;
  60724. return this;
  60725. };
  60726. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60727. if (this._options.samplers.indexOf(name) === -1) {
  60728. this._options.samplers.push(name);
  60729. }
  60730. this._checkUniform(name);
  60731. this._textureArrays[name] = textures;
  60732. return this;
  60733. };
  60734. ShaderMaterial.prototype.setFloat = function (name, value) {
  60735. this._checkUniform(name);
  60736. this._floats[name] = value;
  60737. return this;
  60738. };
  60739. ShaderMaterial.prototype.setInt = function (name, value) {
  60740. this._checkUniform(name);
  60741. this._ints[name] = value;
  60742. return this;
  60743. };
  60744. ShaderMaterial.prototype.setFloats = function (name, value) {
  60745. this._checkUniform(name);
  60746. this._floatsArrays[name] = value;
  60747. return this;
  60748. };
  60749. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60750. this._checkUniform(name);
  60751. this._colors3[name] = value;
  60752. return this;
  60753. };
  60754. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60755. this._checkUniform(name);
  60756. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60757. color.toArray(arr, arr.length);
  60758. return arr;
  60759. }, []);
  60760. return this;
  60761. };
  60762. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60763. this._checkUniform(name);
  60764. this._colors4[name] = value;
  60765. return this;
  60766. };
  60767. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60768. this._checkUniform(name);
  60769. this._vectors2[name] = value;
  60770. return this;
  60771. };
  60772. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60773. this._checkUniform(name);
  60774. this._vectors3[name] = value;
  60775. return this;
  60776. };
  60777. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60778. this._checkUniform(name);
  60779. this._vectors4[name] = value;
  60780. return this;
  60781. };
  60782. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60783. this._checkUniform(name);
  60784. this._matrices[name] = value;
  60785. return this;
  60786. };
  60787. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60788. this._checkUniform(name);
  60789. this._matrices3x3[name] = value;
  60790. return this;
  60791. };
  60792. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60793. this._checkUniform(name);
  60794. this._matrices2x2[name] = value;
  60795. return this;
  60796. };
  60797. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60798. this._checkUniform(name);
  60799. this._vectors2Arrays[name] = value;
  60800. return this;
  60801. };
  60802. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60803. this._checkUniform(name);
  60804. this._vectors3Arrays[name] = value;
  60805. return this;
  60806. };
  60807. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60808. if (!mesh) {
  60809. return true;
  60810. }
  60811. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60812. return false;
  60813. }
  60814. return false;
  60815. };
  60816. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60817. var scene = this.getScene();
  60818. var engine = scene.getEngine();
  60819. if (!this.checkReadyOnEveryCall) {
  60820. if (this._renderId === scene.getRenderId()) {
  60821. if (this._checkCache(scene, mesh, useInstances)) {
  60822. return true;
  60823. }
  60824. }
  60825. }
  60826. // Instances
  60827. var defines = [];
  60828. var attribs = [];
  60829. var fallbacks = new BABYLON.EffectFallbacks();
  60830. if (useInstances) {
  60831. defines.push("#define INSTANCES");
  60832. }
  60833. for (var index = 0; index < this._options.defines.length; index++) {
  60834. defines.push(this._options.defines[index]);
  60835. }
  60836. for (var index = 0; index < this._options.attributes.length; index++) {
  60837. attribs.push(this._options.attributes[index]);
  60838. }
  60839. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60840. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60841. defines.push("#define VERTEXCOLOR");
  60842. }
  60843. // Bones
  60844. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60845. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60846. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60847. if (mesh.numBoneInfluencers > 4) {
  60848. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60849. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60850. }
  60851. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60852. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60853. fallbacks.addCPUSkinningFallback(0, mesh);
  60854. if (this._options.uniforms.indexOf("mBones") === -1) {
  60855. this._options.uniforms.push("mBones");
  60856. }
  60857. }
  60858. else {
  60859. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60860. }
  60861. // Textures
  60862. for (var name in this._textures) {
  60863. if (!this._textures[name].isReady()) {
  60864. return false;
  60865. }
  60866. }
  60867. // Alpha test
  60868. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60869. defines.push("#define ALPHATEST");
  60870. }
  60871. var previousEffect = this._effect;
  60872. var join = defines.join("\n");
  60873. this._effect = engine.createEffect(this._shaderPath, {
  60874. attributes: attribs,
  60875. uniformsNames: this._options.uniforms,
  60876. uniformBuffersNames: this._options.uniformBuffers,
  60877. samplers: this._options.samplers,
  60878. defines: join,
  60879. fallbacks: fallbacks,
  60880. onCompiled: this.onCompiled,
  60881. onError: this.onError
  60882. }, engine);
  60883. if (!this._effect.isReady()) {
  60884. return false;
  60885. }
  60886. if (previousEffect !== this._effect) {
  60887. scene.resetCachedMaterial();
  60888. }
  60889. this._renderId = scene.getRenderId();
  60890. return true;
  60891. };
  60892. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60893. var scene = this.getScene();
  60894. if (!this._effect) {
  60895. return;
  60896. }
  60897. if (this._options.uniforms.indexOf("world") !== -1) {
  60898. this._effect.setMatrix("world", world);
  60899. }
  60900. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60901. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60902. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60903. }
  60904. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60905. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60906. }
  60907. };
  60908. ShaderMaterial.prototype.bind = function (world, mesh) {
  60909. // Std values
  60910. this.bindOnlyWorldMatrix(world);
  60911. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60912. if (this._options.uniforms.indexOf("view") !== -1) {
  60913. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60914. }
  60915. if (this._options.uniforms.indexOf("projection") !== -1) {
  60916. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60917. }
  60918. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60919. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60920. }
  60921. // Bones
  60922. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60923. var name;
  60924. // Texture
  60925. for (name in this._textures) {
  60926. this._effect.setTexture(name, this._textures[name]);
  60927. }
  60928. // Texture arrays
  60929. for (name in this._textureArrays) {
  60930. this._effect.setTextureArray(name, this._textureArrays[name]);
  60931. }
  60932. // Int
  60933. for (name in this._ints) {
  60934. this._effect.setInt(name, this._ints[name]);
  60935. }
  60936. // Float
  60937. for (name in this._floats) {
  60938. this._effect.setFloat(name, this._floats[name]);
  60939. }
  60940. // Floats
  60941. for (name in this._floatsArrays) {
  60942. this._effect.setArray(name, this._floatsArrays[name]);
  60943. }
  60944. // Color3
  60945. for (name in this._colors3) {
  60946. this._effect.setColor3(name, this._colors3[name]);
  60947. }
  60948. for (name in this._colors3Arrays) {
  60949. this._effect.setArray3(name, this._colors3Arrays[name]);
  60950. }
  60951. // Color4
  60952. for (name in this._colors4) {
  60953. var color = this._colors4[name];
  60954. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60955. }
  60956. // Vector2
  60957. for (name in this._vectors2) {
  60958. this._effect.setVector2(name, this._vectors2[name]);
  60959. }
  60960. // Vector3
  60961. for (name in this._vectors3) {
  60962. this._effect.setVector3(name, this._vectors3[name]);
  60963. }
  60964. // Vector4
  60965. for (name in this._vectors4) {
  60966. this._effect.setVector4(name, this._vectors4[name]);
  60967. }
  60968. // Matrix
  60969. for (name in this._matrices) {
  60970. this._effect.setMatrix(name, this._matrices[name]);
  60971. }
  60972. // Matrix 3x3
  60973. for (name in this._matrices3x3) {
  60974. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60975. }
  60976. // Matrix 2x2
  60977. for (name in this._matrices2x2) {
  60978. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60979. }
  60980. // Vector2Array
  60981. for (name in this._vectors2Arrays) {
  60982. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60983. }
  60984. // Vector3Array
  60985. for (name in this._vectors3Arrays) {
  60986. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60987. }
  60988. }
  60989. this._afterBind(mesh);
  60990. };
  60991. ShaderMaterial.prototype.getActiveTextures = function () {
  60992. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60993. for (var name in this._textures) {
  60994. activeTextures.push(this._textures[name]);
  60995. }
  60996. for (var name in this._textureArrays) {
  60997. var array = this._textureArrays[name];
  60998. for (var index = 0; index < array.length; index++) {
  60999. activeTextures.push(array[index]);
  61000. }
  61001. }
  61002. return activeTextures;
  61003. };
  61004. ShaderMaterial.prototype.hasTexture = function (texture) {
  61005. if (_super.prototype.hasTexture.call(this, texture)) {
  61006. return true;
  61007. }
  61008. for (var name in this._textures) {
  61009. if (this._textures[name] === texture) {
  61010. return true;
  61011. }
  61012. }
  61013. for (var name in this._textureArrays) {
  61014. var array = this._textureArrays[name];
  61015. for (var index = 0; index < array.length; index++) {
  61016. if (array[index] === texture) {
  61017. return true;
  61018. }
  61019. }
  61020. }
  61021. return false;
  61022. };
  61023. ShaderMaterial.prototype.clone = function (name) {
  61024. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  61025. return newShaderMaterial;
  61026. };
  61027. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61028. if (forceDisposeTextures) {
  61029. var name;
  61030. for (name in this._textures) {
  61031. this._textures[name].dispose();
  61032. }
  61033. for (name in this._textureArrays) {
  61034. var array = this._textureArrays[name];
  61035. for (var index = 0; index < array.length; index++) {
  61036. array[index].dispose();
  61037. }
  61038. }
  61039. }
  61040. this._textures = {};
  61041. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61042. };
  61043. ShaderMaterial.prototype.serialize = function () {
  61044. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61045. serializationObject.customType = "BABYLON.ShaderMaterial";
  61046. serializationObject.options = this._options;
  61047. serializationObject.shaderPath = this._shaderPath;
  61048. var name;
  61049. // Texture
  61050. serializationObject.textures = {};
  61051. for (name in this._textures) {
  61052. serializationObject.textures[name] = this._textures[name].serialize();
  61053. }
  61054. // Texture arrays
  61055. serializationObject.textureArrays = {};
  61056. for (name in this._textureArrays) {
  61057. serializationObject.textureArrays[name] = [];
  61058. var array = this._textureArrays[name];
  61059. for (var index = 0; index < array.length; index++) {
  61060. serializationObject.textureArrays[name].push(array[index].serialize());
  61061. }
  61062. }
  61063. // Float
  61064. serializationObject.floats = {};
  61065. for (name in this._floats) {
  61066. serializationObject.floats[name] = this._floats[name];
  61067. }
  61068. // Float s
  61069. serializationObject.FloatArrays = {};
  61070. for (name in this._floatsArrays) {
  61071. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61072. }
  61073. // Color3
  61074. serializationObject.colors3 = {};
  61075. for (name in this._colors3) {
  61076. serializationObject.colors3[name] = this._colors3[name].asArray();
  61077. }
  61078. // Color3 array
  61079. serializationObject.colors3Arrays = {};
  61080. for (name in this._colors3Arrays) {
  61081. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61082. }
  61083. // Color4
  61084. serializationObject.colors4 = {};
  61085. for (name in this._colors4) {
  61086. serializationObject.colors4[name] = this._colors4[name].asArray();
  61087. }
  61088. // Vector2
  61089. serializationObject.vectors2 = {};
  61090. for (name in this._vectors2) {
  61091. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61092. }
  61093. // Vector3
  61094. serializationObject.vectors3 = {};
  61095. for (name in this._vectors3) {
  61096. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61097. }
  61098. // Vector4
  61099. serializationObject.vectors4 = {};
  61100. for (name in this._vectors4) {
  61101. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61102. }
  61103. // Matrix
  61104. serializationObject.matrices = {};
  61105. for (name in this._matrices) {
  61106. serializationObject.matrices[name] = this._matrices[name].asArray();
  61107. }
  61108. // Matrix 3x3
  61109. serializationObject.matrices3x3 = {};
  61110. for (name in this._matrices3x3) {
  61111. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61112. }
  61113. // Matrix 2x2
  61114. serializationObject.matrices2x2 = {};
  61115. for (name in this._matrices2x2) {
  61116. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  61117. }
  61118. // Vector2Array
  61119. serializationObject.vectors2Arrays = {};
  61120. for (name in this._vectors2Arrays) {
  61121. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  61122. }
  61123. // Vector3Array
  61124. serializationObject.vectors3Arrays = {};
  61125. for (name in this._vectors3Arrays) {
  61126. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  61127. }
  61128. return serializationObject;
  61129. };
  61130. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  61131. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  61132. var name;
  61133. // Texture
  61134. for (name in source.textures) {
  61135. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  61136. }
  61137. // Texture arrays
  61138. for (name in source.textureArrays) {
  61139. var array = source.textureArrays[name];
  61140. var textureArray = new Array();
  61141. for (var index = 0; index < array.length; index++) {
  61142. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  61143. }
  61144. material.setTextureArray(name, textureArray);
  61145. }
  61146. // Float
  61147. for (name in source.floats) {
  61148. material.setFloat(name, source.floats[name]);
  61149. }
  61150. // Float s
  61151. for (name in source.floatsArrays) {
  61152. material.setFloats(name, source.floatsArrays[name]);
  61153. }
  61154. // Color3
  61155. for (name in source.colors3) {
  61156. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  61157. }
  61158. // Color3 arrays
  61159. for (name in source.colors3Arrays) {
  61160. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  61161. if (i % 3 === 0) {
  61162. arr.push([num]);
  61163. }
  61164. else {
  61165. arr[arr.length - 1].push(num);
  61166. }
  61167. return arr;
  61168. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  61169. material.setColor3Array(name, colors);
  61170. }
  61171. // Color4
  61172. for (name in source.colors4) {
  61173. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  61174. }
  61175. // Vector2
  61176. for (name in source.vectors2) {
  61177. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  61178. }
  61179. // Vector3
  61180. for (name in source.vectors3) {
  61181. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  61182. }
  61183. // Vector4
  61184. for (name in source.vectors4) {
  61185. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  61186. }
  61187. // Matrix
  61188. for (name in source.matrices) {
  61189. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  61190. }
  61191. // Matrix 3x3
  61192. for (name in source.matrices3x3) {
  61193. material.setMatrix3x3(name, source.matrices3x3[name]);
  61194. }
  61195. // Matrix 2x2
  61196. for (name in source.matrices2x2) {
  61197. material.setMatrix2x2(name, source.matrices2x2[name]);
  61198. }
  61199. // Vector2Array
  61200. for (name in source.vectors2Arrays) {
  61201. material.setArray2(name, source.vectors2Arrays[name]);
  61202. }
  61203. // Vector3Array
  61204. for (name in source.vectors3Arrays) {
  61205. material.setArray3(name, source.vectors3Arrays[name]);
  61206. }
  61207. return material;
  61208. };
  61209. return ShaderMaterial;
  61210. }(BABYLON.Material));
  61211. BABYLON.ShaderMaterial = ShaderMaterial;
  61212. })(BABYLON || (BABYLON = {}));
  61213. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61214. var BABYLON;
  61215. (function (BABYLON) {
  61216. var GroundMesh = /** @class */ (function (_super) {
  61217. __extends(GroundMesh, _super);
  61218. function GroundMesh(name, scene) {
  61219. var _this = _super.call(this, name, scene) || this;
  61220. _this.generateOctree = false;
  61221. return _this;
  61222. }
  61223. GroundMesh.prototype.getClassName = function () {
  61224. return "GroundMesh";
  61225. };
  61226. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61227. get: function () {
  61228. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61229. },
  61230. enumerable: true,
  61231. configurable: true
  61232. });
  61233. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61234. get: function () {
  61235. return this._subdivisionsX;
  61236. },
  61237. enumerable: true,
  61238. configurable: true
  61239. });
  61240. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61241. get: function () {
  61242. return this._subdivisionsY;
  61243. },
  61244. enumerable: true,
  61245. configurable: true
  61246. });
  61247. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61248. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61249. this._subdivisionsX = chunksCount;
  61250. this._subdivisionsY = chunksCount;
  61251. this.subdivide(chunksCount);
  61252. // Call the octree system optimization if it is defined.
  61253. var thisAsAny = this;
  61254. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61255. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61256. }
  61257. };
  61258. /**
  61259. * Returns a height (y) value in the Worl system :
  61260. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61261. * Returns the ground y position if (x, z) are outside the ground surface.
  61262. */
  61263. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61264. var world = this.getWorldMatrix();
  61265. var invMat = BABYLON.Tmp.Matrix[5];
  61266. world.invertToRef(invMat);
  61267. var tmpVect = BABYLON.Tmp.Vector3[8];
  61268. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61269. x = tmpVect.x;
  61270. z = tmpVect.z;
  61271. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61272. return this.position.y;
  61273. }
  61274. if (!this._heightQuads || this._heightQuads.length == 0) {
  61275. this._initHeightQuads();
  61276. this._computeHeightQuads();
  61277. }
  61278. var facet = this._getFacetAt(x, z);
  61279. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61280. // return y in the World system
  61281. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61282. return tmpVect.y;
  61283. };
  61284. /**
  61285. * Returns a normalized vector (Vector3) orthogonal to the ground
  61286. * at the ground coordinates (x, z) expressed in the World system.
  61287. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61288. */
  61289. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61290. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61291. this.getNormalAtCoordinatesToRef(x, z, normal);
  61292. return normal;
  61293. };
  61294. /**
  61295. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61296. * at the ground coordinates (x, z) expressed in the World system.
  61297. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61298. * Returns the GroundMesh.
  61299. */
  61300. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61301. var world = this.getWorldMatrix();
  61302. var tmpMat = BABYLON.Tmp.Matrix[5];
  61303. world.invertToRef(tmpMat);
  61304. var tmpVect = BABYLON.Tmp.Vector3[8];
  61305. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61306. x = tmpVect.x;
  61307. z = tmpVect.z;
  61308. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61309. return this;
  61310. }
  61311. if (!this._heightQuads || this._heightQuads.length == 0) {
  61312. this._initHeightQuads();
  61313. this._computeHeightQuads();
  61314. }
  61315. var facet = this._getFacetAt(x, z);
  61316. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61317. return this;
  61318. };
  61319. /**
  61320. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61321. * if the ground has been updated.
  61322. * This can be used in the render loop.
  61323. * Returns the GroundMesh.
  61324. */
  61325. GroundMesh.prototype.updateCoordinateHeights = function () {
  61326. if (!this._heightQuads || this._heightQuads.length == 0) {
  61327. this._initHeightQuads();
  61328. }
  61329. this._computeHeightQuads();
  61330. return this;
  61331. };
  61332. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61333. GroundMesh.prototype._getFacetAt = function (x, z) {
  61334. // retrieve col and row from x, z coordinates in the ground local system
  61335. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61336. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61337. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61338. var facet;
  61339. if (z < quad.slope.x * x + quad.slope.y) {
  61340. facet = quad.facet1;
  61341. }
  61342. else {
  61343. facet = quad.facet2;
  61344. }
  61345. return facet;
  61346. };
  61347. // Creates and populates the heightMap array with "facet" elements :
  61348. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61349. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61350. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61351. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61352. // Returns the GroundMesh.
  61353. GroundMesh.prototype._initHeightQuads = function () {
  61354. var subdivisionsX = this._subdivisionsX;
  61355. var subdivisionsY = this._subdivisionsY;
  61356. this._heightQuads = new Array();
  61357. for (var row = 0; row < subdivisionsY; row++) {
  61358. for (var col = 0; col < subdivisionsX; col++) {
  61359. 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) };
  61360. this._heightQuads[row * subdivisionsX + col] = quad;
  61361. }
  61362. }
  61363. return this;
  61364. };
  61365. // Compute each quad element values and update the the heightMap array :
  61366. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61367. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61368. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61369. // Returns the GroundMesh.
  61370. GroundMesh.prototype._computeHeightQuads = function () {
  61371. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61372. if (!positions) {
  61373. return this;
  61374. }
  61375. var v1 = BABYLON.Tmp.Vector3[3];
  61376. var v2 = BABYLON.Tmp.Vector3[2];
  61377. var v3 = BABYLON.Tmp.Vector3[1];
  61378. var v4 = BABYLON.Tmp.Vector3[0];
  61379. var v1v2 = BABYLON.Tmp.Vector3[4];
  61380. var v1v3 = BABYLON.Tmp.Vector3[5];
  61381. var v1v4 = BABYLON.Tmp.Vector3[6];
  61382. var norm1 = BABYLON.Tmp.Vector3[7];
  61383. var norm2 = BABYLON.Tmp.Vector3[8];
  61384. var i = 0;
  61385. var j = 0;
  61386. var k = 0;
  61387. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61388. var h = 0;
  61389. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61390. var d2 = 0;
  61391. var subdivisionsX = this._subdivisionsX;
  61392. var subdivisionsY = this._subdivisionsY;
  61393. for (var row = 0; row < subdivisionsY; row++) {
  61394. for (var col = 0; col < subdivisionsX; col++) {
  61395. i = col * 3;
  61396. j = row * (subdivisionsX + 1) * 3;
  61397. k = (row + 1) * (subdivisionsX + 1) * 3;
  61398. v1.x = positions[j + i];
  61399. v1.y = positions[j + i + 1];
  61400. v1.z = positions[j + i + 2];
  61401. v2.x = positions[j + i + 3];
  61402. v2.y = positions[j + i + 4];
  61403. v2.z = positions[j + i + 5];
  61404. v3.x = positions[k + i];
  61405. v3.y = positions[k + i + 1];
  61406. v3.z = positions[k + i + 2];
  61407. v4.x = positions[k + i + 3];
  61408. v4.y = positions[k + i + 4];
  61409. v4.z = positions[k + i + 5];
  61410. // 2D slope V1V4
  61411. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61412. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61413. // facet equations :
  61414. // we compute each facet normal vector
  61415. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61416. // we compute the value d by applying the equation to v1 which belongs to the plane
  61417. // then we store the facet equation in a Vector4
  61418. v2.subtractToRef(v1, v1v2);
  61419. v3.subtractToRef(v1, v1v3);
  61420. v4.subtractToRef(v1, v1v4);
  61421. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61422. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61423. norm1.normalize();
  61424. norm2.normalize();
  61425. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61426. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61427. var quad = this._heightQuads[row * subdivisionsX + col];
  61428. quad.slope.copyFromFloats(cd, h);
  61429. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61430. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61431. }
  61432. }
  61433. return this;
  61434. };
  61435. GroundMesh.prototype.serialize = function (serializationObject) {
  61436. _super.prototype.serialize.call(this, serializationObject);
  61437. serializationObject.subdivisionsX = this._subdivisionsX;
  61438. serializationObject.subdivisionsY = this._subdivisionsY;
  61439. serializationObject.minX = this._minX;
  61440. serializationObject.maxX = this._maxX;
  61441. serializationObject.minZ = this._minZ;
  61442. serializationObject.maxZ = this._maxZ;
  61443. serializationObject.width = this._width;
  61444. serializationObject.height = this._height;
  61445. };
  61446. GroundMesh.Parse = function (parsedMesh, scene) {
  61447. var result = new GroundMesh(parsedMesh.name, scene);
  61448. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61449. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61450. result._minX = parsedMesh.minX;
  61451. result._maxX = parsedMesh.maxX;
  61452. result._minZ = parsedMesh.minZ;
  61453. result._maxZ = parsedMesh.maxZ;
  61454. result._width = parsedMesh.width;
  61455. result._height = parsedMesh.height;
  61456. return result;
  61457. };
  61458. return GroundMesh;
  61459. }(BABYLON.Mesh));
  61460. BABYLON.GroundMesh = GroundMesh;
  61461. })(BABYLON || (BABYLON = {}));
  61462. //# sourceMappingURL=babylon.groundMesh.js.map
  61463. var BABYLON;
  61464. (function (BABYLON) {
  61465. /**
  61466. * Creates an instance based on a source mesh.
  61467. */
  61468. var InstancedMesh = /** @class */ (function (_super) {
  61469. __extends(InstancedMesh, _super);
  61470. function InstancedMesh(name, source) {
  61471. var _this = _super.call(this, name, source.getScene()) || this;
  61472. source.instances.push(_this);
  61473. _this._sourceMesh = source;
  61474. _this.position.copyFrom(source.position);
  61475. _this.rotation.copyFrom(source.rotation);
  61476. _this.scaling.copyFrom(source.scaling);
  61477. if (source.rotationQuaternion) {
  61478. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61479. }
  61480. _this.infiniteDistance = source.infiniteDistance;
  61481. _this.setPivotMatrix(source.getPivotMatrix());
  61482. _this.refreshBoundingInfo();
  61483. _this._syncSubMeshes();
  61484. return _this;
  61485. }
  61486. /**
  61487. * Returns the string "InstancedMesh".
  61488. */
  61489. InstancedMesh.prototype.getClassName = function () {
  61490. return "InstancedMesh";
  61491. };
  61492. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61493. // Methods
  61494. get: function () {
  61495. return this._sourceMesh.receiveShadows;
  61496. },
  61497. enumerable: true,
  61498. configurable: true
  61499. });
  61500. Object.defineProperty(InstancedMesh.prototype, "material", {
  61501. get: function () {
  61502. return this._sourceMesh.material;
  61503. },
  61504. enumerable: true,
  61505. configurable: true
  61506. });
  61507. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61508. get: function () {
  61509. return this._sourceMesh.visibility;
  61510. },
  61511. enumerable: true,
  61512. configurable: true
  61513. });
  61514. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61515. get: function () {
  61516. return this._sourceMesh.skeleton;
  61517. },
  61518. enumerable: true,
  61519. configurable: true
  61520. });
  61521. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61522. get: function () {
  61523. return this._sourceMesh.renderingGroupId;
  61524. },
  61525. set: function (value) {
  61526. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61527. return;
  61528. }
  61529. //no-op with warning
  61530. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61531. },
  61532. enumerable: true,
  61533. configurable: true
  61534. });
  61535. /**
  61536. * Returns the total number of vertices (integer).
  61537. */
  61538. InstancedMesh.prototype.getTotalVertices = function () {
  61539. return this._sourceMesh.getTotalVertices();
  61540. };
  61541. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61542. get: function () {
  61543. return this._sourceMesh;
  61544. },
  61545. enumerable: true,
  61546. configurable: true
  61547. });
  61548. /**
  61549. * Is this node ready to be used/rendered
  61550. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61551. * @return {boolean} is it ready
  61552. */
  61553. InstancedMesh.prototype.isReady = function (completeCheck) {
  61554. if (completeCheck === void 0) { completeCheck = false; }
  61555. return this._sourceMesh.isReady(completeCheck, true);
  61556. };
  61557. /**
  61558. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61559. */
  61560. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61561. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61562. };
  61563. /**
  61564. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61565. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61566. * The `data` are either a numeric array either a Float32Array.
  61567. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61568. * 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).
  61569. * Note that a new underlying VertexBuffer object is created each call.
  61570. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61571. *
  61572. * Possible `kind` values :
  61573. * - BABYLON.VertexBuffer.PositionKind
  61574. * - BABYLON.VertexBuffer.UVKind
  61575. * - BABYLON.VertexBuffer.UV2Kind
  61576. * - BABYLON.VertexBuffer.UV3Kind
  61577. * - BABYLON.VertexBuffer.UV4Kind
  61578. * - BABYLON.VertexBuffer.UV5Kind
  61579. * - BABYLON.VertexBuffer.UV6Kind
  61580. * - BABYLON.VertexBuffer.ColorKind
  61581. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61582. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61583. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61584. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61585. *
  61586. * Returns the Mesh.
  61587. */
  61588. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61589. if (this.sourceMesh) {
  61590. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61591. }
  61592. return this.sourceMesh;
  61593. };
  61594. /**
  61595. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61596. * If the mesh has no geometry, it is simply returned as it is.
  61597. * The `data` are either a numeric array either a Float32Array.
  61598. * No new underlying VertexBuffer object is created.
  61599. * 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.
  61600. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61601. *
  61602. * Possible `kind` values :
  61603. * - BABYLON.VertexBuffer.PositionKind
  61604. * - BABYLON.VertexBuffer.UVKind
  61605. * - BABYLON.VertexBuffer.UV2Kind
  61606. * - BABYLON.VertexBuffer.UV3Kind
  61607. * - BABYLON.VertexBuffer.UV4Kind
  61608. * - BABYLON.VertexBuffer.UV5Kind
  61609. * - BABYLON.VertexBuffer.UV6Kind
  61610. * - BABYLON.VertexBuffer.ColorKind
  61611. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61612. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61613. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61614. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61615. *
  61616. * Returns the Mesh.
  61617. */
  61618. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61619. if (this.sourceMesh) {
  61620. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61621. }
  61622. return this.sourceMesh;
  61623. };
  61624. /**
  61625. * Sets the mesh indices.
  61626. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61627. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61628. * This method creates a new index buffer each call.
  61629. * Returns the Mesh.
  61630. */
  61631. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61632. if (totalVertices === void 0) { totalVertices = null; }
  61633. if (this.sourceMesh) {
  61634. this.sourceMesh.setIndices(indices, totalVertices);
  61635. }
  61636. return this.sourceMesh;
  61637. };
  61638. /**
  61639. * Boolean : True if the mesh owns the requested kind of data.
  61640. */
  61641. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61642. return this._sourceMesh.isVerticesDataPresent(kind);
  61643. };
  61644. /**
  61645. * Returns an array of indices (IndicesArray).
  61646. */
  61647. InstancedMesh.prototype.getIndices = function () {
  61648. return this._sourceMesh.getIndices();
  61649. };
  61650. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61651. get: function () {
  61652. return this._sourceMesh._positions;
  61653. },
  61654. enumerable: true,
  61655. configurable: true
  61656. });
  61657. /**
  61658. * Sets a new updated BoundingInfo to the mesh.
  61659. * Returns the mesh.
  61660. */
  61661. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61662. var meshBB = this._sourceMesh.getBoundingInfo();
  61663. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61664. this._updateBoundingInfo();
  61665. return this;
  61666. };
  61667. /** @hidden */
  61668. InstancedMesh.prototype._preActivate = function () {
  61669. if (this._currentLOD) {
  61670. this._currentLOD._preActivate();
  61671. }
  61672. return this;
  61673. };
  61674. /** @hidden */
  61675. InstancedMesh.prototype._activate = function (renderId) {
  61676. if (this._currentLOD) {
  61677. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61678. }
  61679. return this;
  61680. };
  61681. /**
  61682. * Returns the current associated LOD AbstractMesh.
  61683. */
  61684. InstancedMesh.prototype.getLOD = function (camera) {
  61685. if (!camera) {
  61686. return this;
  61687. }
  61688. var boundingInfo = this.getBoundingInfo();
  61689. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61690. if (this._currentLOD === this.sourceMesh) {
  61691. return this;
  61692. }
  61693. return this._currentLOD;
  61694. };
  61695. /** @hidden */
  61696. InstancedMesh.prototype._syncSubMeshes = function () {
  61697. this.releaseSubMeshes();
  61698. if (this._sourceMesh.subMeshes) {
  61699. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61700. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61701. }
  61702. }
  61703. return this;
  61704. };
  61705. /** @hidden */
  61706. InstancedMesh.prototype._generatePointsArray = function () {
  61707. return this._sourceMesh._generatePointsArray();
  61708. };
  61709. /**
  61710. * Creates a new InstancedMesh from the current mesh.
  61711. * - name (string) : the cloned mesh name
  61712. * - newParent (optional Node) : the optional Node to parent the clone to.
  61713. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61714. *
  61715. * Returns the clone.
  61716. */
  61717. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61718. var result = this._sourceMesh.createInstance(name);
  61719. // Deep copy
  61720. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61721. // Bounding info
  61722. this.refreshBoundingInfo();
  61723. // Parent
  61724. if (newParent) {
  61725. result.parent = newParent;
  61726. }
  61727. if (!doNotCloneChildren) {
  61728. // Children
  61729. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61730. var mesh = this.getScene().meshes[index];
  61731. if (mesh.parent === this) {
  61732. mesh.clone(mesh.name, result);
  61733. }
  61734. }
  61735. }
  61736. result.computeWorldMatrix(true);
  61737. return result;
  61738. };
  61739. /**
  61740. * Disposes the InstancedMesh.
  61741. * Returns nothing.
  61742. */
  61743. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61744. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61745. // Remove from mesh
  61746. var index = this._sourceMesh.instances.indexOf(this);
  61747. this._sourceMesh.instances.splice(index, 1);
  61748. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61749. };
  61750. return InstancedMesh;
  61751. }(BABYLON.AbstractMesh));
  61752. BABYLON.InstancedMesh = InstancedMesh;
  61753. })(BABYLON || (BABYLON = {}));
  61754. //# sourceMappingURL=babylon.instancedMesh.js.map
  61755. var BABYLON;
  61756. (function (BABYLON) {
  61757. var LinesMesh = /** @class */ (function (_super) {
  61758. __extends(LinesMesh, _super);
  61759. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61760. if (scene === void 0) { scene = null; }
  61761. if (parent === void 0) { parent = null; }
  61762. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61763. _this.useVertexColor = useVertexColor;
  61764. _this.useVertexAlpha = useVertexAlpha;
  61765. _this.color = new BABYLON.Color3(1, 1, 1);
  61766. _this.alpha = 1;
  61767. if (source) {
  61768. _this.color = source.color.clone();
  61769. _this.alpha = source.alpha;
  61770. _this.useVertexColor = source.useVertexColor;
  61771. _this.useVertexAlpha = source.useVertexAlpha;
  61772. }
  61773. _this._intersectionThreshold = 0.1;
  61774. var defines = [];
  61775. var options = {
  61776. attributes: [BABYLON.VertexBuffer.PositionKind],
  61777. uniforms: ["world", "viewProjection"],
  61778. needAlphaBlending: true,
  61779. defines: defines
  61780. };
  61781. if (useVertexAlpha === false) {
  61782. options.needAlphaBlending = false;
  61783. }
  61784. if (!useVertexColor) {
  61785. options.uniforms.push("color");
  61786. }
  61787. else {
  61788. options.defines.push("#define VERTEXCOLOR");
  61789. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61790. }
  61791. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61792. return _this;
  61793. }
  61794. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61795. /**
  61796. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61797. * This margin is expressed in world space coordinates, so its value may vary.
  61798. * Default value is 0.1
  61799. * @returns the intersection Threshold value.
  61800. */
  61801. get: function () {
  61802. return this._intersectionThreshold;
  61803. },
  61804. /**
  61805. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61806. * This margin is expressed in world space coordinates, so its value may vary.
  61807. * @param value the new threshold to apply
  61808. */
  61809. set: function (value) {
  61810. if (this._intersectionThreshold === value) {
  61811. return;
  61812. }
  61813. this._intersectionThreshold = value;
  61814. if (this.geometry) {
  61815. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61816. }
  61817. },
  61818. enumerable: true,
  61819. configurable: true
  61820. });
  61821. /**
  61822. * Returns the string "LineMesh"
  61823. */
  61824. LinesMesh.prototype.getClassName = function () {
  61825. return "LinesMesh";
  61826. };
  61827. Object.defineProperty(LinesMesh.prototype, "material", {
  61828. /**
  61829. * @hidden
  61830. */
  61831. get: function () {
  61832. return this._colorShader;
  61833. },
  61834. /**
  61835. * @hidden
  61836. */
  61837. set: function (value) {
  61838. // Do nothing
  61839. },
  61840. enumerable: true,
  61841. configurable: true
  61842. });
  61843. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61844. /**
  61845. * @hidden
  61846. */
  61847. get: function () {
  61848. return false;
  61849. },
  61850. enumerable: true,
  61851. configurable: true
  61852. });
  61853. LinesMesh.prototype.createInstance = function (name) {
  61854. throw new Error("LinesMeshes do not support createInstance.");
  61855. };
  61856. /** @hidden */
  61857. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61858. if (!this._geometry) {
  61859. return this;
  61860. }
  61861. // VBOs
  61862. this._geometry._bind(this._colorShader.getEffect());
  61863. // Color
  61864. if (!this.useVertexColor) {
  61865. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61866. }
  61867. return this;
  61868. };
  61869. /** @hidden */
  61870. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61871. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61872. return this;
  61873. }
  61874. var engine = this.getScene().getEngine();
  61875. // Draw order
  61876. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61877. return this;
  61878. };
  61879. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61880. this._colorShader.dispose();
  61881. _super.prototype.dispose.call(this, doNotRecurse);
  61882. };
  61883. /**
  61884. * Returns a new LineMesh object cloned from the current one.
  61885. */
  61886. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61887. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61888. };
  61889. return LinesMesh;
  61890. }(BABYLON.Mesh));
  61891. BABYLON.LinesMesh = LinesMesh;
  61892. })(BABYLON || (BABYLON = {}));
  61893. //# sourceMappingURL=babylon.linesMesh.js.map
  61894. var BABYLON;
  61895. (function (BABYLON) {
  61896. /**
  61897. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61898. * The underlying implementation relies on an associative array to ensure the best performances.
  61899. * The value can be anything including 'null' but except 'undefined'
  61900. */
  61901. var StringDictionary = /** @class */ (function () {
  61902. function StringDictionary() {
  61903. this._count = 0;
  61904. this._data = {};
  61905. }
  61906. /**
  61907. * This will clear this dictionary and copy the content from the 'source' one.
  61908. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61909. * @param source the dictionary to take the content from and copy to this dictionary
  61910. */
  61911. StringDictionary.prototype.copyFrom = function (source) {
  61912. var _this = this;
  61913. this.clear();
  61914. source.forEach(function (t, v) { return _this.add(t, v); });
  61915. };
  61916. /**
  61917. * Get a value based from its key
  61918. * @param key the given key to get the matching value from
  61919. * @return the value if found, otherwise undefined is returned
  61920. */
  61921. StringDictionary.prototype.get = function (key) {
  61922. var val = this._data[key];
  61923. if (val !== undefined) {
  61924. return val;
  61925. }
  61926. return undefined;
  61927. };
  61928. /**
  61929. * Get a value from its key or add it if it doesn't exist.
  61930. * This method will ensure you that a given key/data will be present in the dictionary.
  61931. * @param key the given key to get the matching value from
  61932. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61933. * The factory will only be invoked if there's no data for the given key.
  61934. * @return the value corresponding to the key.
  61935. */
  61936. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61937. var val = this.get(key);
  61938. if (val !== undefined) {
  61939. return val;
  61940. }
  61941. val = factory(key);
  61942. if (val) {
  61943. this.add(key, val);
  61944. }
  61945. return val;
  61946. };
  61947. /**
  61948. * Get a value from its key if present in the dictionary otherwise add it
  61949. * @param key the key to get the value from
  61950. * @param val if there's no such key/value pair in the dictionary add it with this value
  61951. * @return the value corresponding to the key
  61952. */
  61953. StringDictionary.prototype.getOrAdd = function (key, val) {
  61954. var curVal = this.get(key);
  61955. if (curVal !== undefined) {
  61956. return curVal;
  61957. }
  61958. this.add(key, val);
  61959. return val;
  61960. };
  61961. /**
  61962. * Check if there's a given key in the dictionary
  61963. * @param key the key to check for
  61964. * @return true if the key is present, false otherwise
  61965. */
  61966. StringDictionary.prototype.contains = function (key) {
  61967. return this._data[key] !== undefined;
  61968. };
  61969. /**
  61970. * Add a new key and its corresponding value
  61971. * @param key the key to add
  61972. * @param value the value corresponding to the key
  61973. * @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
  61974. */
  61975. StringDictionary.prototype.add = function (key, value) {
  61976. if (this._data[key] !== undefined) {
  61977. return false;
  61978. }
  61979. this._data[key] = value;
  61980. ++this._count;
  61981. return true;
  61982. };
  61983. StringDictionary.prototype.set = function (key, value) {
  61984. if (this._data[key] === undefined) {
  61985. return false;
  61986. }
  61987. this._data[key] = value;
  61988. return true;
  61989. };
  61990. /**
  61991. * Get the element of the given key and remove it from the dictionary
  61992. * @param key
  61993. */
  61994. StringDictionary.prototype.getAndRemove = function (key) {
  61995. var val = this.get(key);
  61996. if (val !== undefined) {
  61997. delete this._data[key];
  61998. --this._count;
  61999. return val;
  62000. }
  62001. return null;
  62002. };
  62003. /**
  62004. * Remove a key/value from the dictionary.
  62005. * @param key the key to remove
  62006. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62007. */
  62008. StringDictionary.prototype.remove = function (key) {
  62009. if (this.contains(key)) {
  62010. delete this._data[key];
  62011. --this._count;
  62012. return true;
  62013. }
  62014. return false;
  62015. };
  62016. /**
  62017. * Clear the whole content of the dictionary
  62018. */
  62019. StringDictionary.prototype.clear = function () {
  62020. this._data = {};
  62021. this._count = 0;
  62022. };
  62023. Object.defineProperty(StringDictionary.prototype, "count", {
  62024. get: function () {
  62025. return this._count;
  62026. },
  62027. enumerable: true,
  62028. configurable: true
  62029. });
  62030. /**
  62031. * Execute a callback on each key/val of the dictionary.
  62032. * Note that you can remove any element in this dictionary in the callback implementation
  62033. * @param callback the callback to execute on a given key/value pair
  62034. */
  62035. StringDictionary.prototype.forEach = function (callback) {
  62036. for (var cur in this._data) {
  62037. var val = this._data[cur];
  62038. callback(cur, val);
  62039. }
  62040. };
  62041. /**
  62042. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62043. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62044. * Note that you can remove any element in this dictionary in the callback implementation
  62045. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62046. */
  62047. StringDictionary.prototype.first = function (callback) {
  62048. for (var cur in this._data) {
  62049. var val = this._data[cur];
  62050. var res = callback(cur, val);
  62051. if (res) {
  62052. return res;
  62053. }
  62054. }
  62055. return null;
  62056. };
  62057. return StringDictionary;
  62058. }());
  62059. BABYLON.StringDictionary = StringDictionary;
  62060. })(BABYLON || (BABYLON = {}));
  62061. //# sourceMappingURL=babylon.stringDictionary.js.map
  62062. var BABYLON;
  62063. (function (BABYLON) {
  62064. var Debug;
  62065. (function (Debug) {
  62066. /**
  62067. * Class used to render a debug view of a given skeleton
  62068. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62069. */
  62070. var SkeletonViewer = /** @class */ (function () {
  62071. /**
  62072. * Creates a new SkeletonViewer
  62073. * @param skeleton defines the skeleton to render
  62074. * @param mesh defines the mesh attached to the skeleton
  62075. * @param scene defines the hosting scene
  62076. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62077. * @param renderingGroupId defines the rendering group id to use with the viewer
  62078. */
  62079. function SkeletonViewer(
  62080. /** defines the skeleton to render */
  62081. skeleton,
  62082. /** defines the mesh attached to the skeleton */
  62083. mesh, scene,
  62084. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62085. autoUpdateBonesMatrices,
  62086. /** defines the rendering group id to use with the viewer */
  62087. renderingGroupId) {
  62088. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62089. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62090. this.skeleton = skeleton;
  62091. this.mesh = mesh;
  62092. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62093. this.renderingGroupId = renderingGroupId;
  62094. /** Gets or sets the color used to render the skeleton */
  62095. this.color = BABYLON.Color3.White();
  62096. this._debugLines = new Array();
  62097. this._isEnabled = false;
  62098. this._scene = scene;
  62099. this.update();
  62100. this._renderFunction = this.update.bind(this);
  62101. }
  62102. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62103. get: function () {
  62104. return this._isEnabled;
  62105. },
  62106. /** Gets or sets a boolean indicating if the viewer is enabled */
  62107. set: function (value) {
  62108. if (this._isEnabled === value) {
  62109. return;
  62110. }
  62111. this._isEnabled = value;
  62112. if (value) {
  62113. this._scene.registerBeforeRender(this._renderFunction);
  62114. }
  62115. else {
  62116. this._scene.unregisterBeforeRender(this._renderFunction);
  62117. }
  62118. },
  62119. enumerable: true,
  62120. configurable: true
  62121. });
  62122. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62123. if (x === void 0) { x = 0; }
  62124. if (y === void 0) { y = 0; }
  62125. if (z === void 0) { z = 0; }
  62126. var tmat = BABYLON.Tmp.Matrix[0];
  62127. var parentBone = bone.getParent();
  62128. tmat.copyFrom(bone.getLocalMatrix());
  62129. if (x !== 0 || y !== 0 || z !== 0) {
  62130. var tmat2 = BABYLON.Tmp.Matrix[1];
  62131. BABYLON.Matrix.IdentityToRef(tmat2);
  62132. tmat2.m[12] = x;
  62133. tmat2.m[13] = y;
  62134. tmat2.m[14] = z;
  62135. tmat2.multiplyToRef(tmat, tmat);
  62136. }
  62137. if (parentBone) {
  62138. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62139. }
  62140. tmat.multiplyToRef(meshMat, tmat);
  62141. position.x = tmat.m[12];
  62142. position.y = tmat.m[13];
  62143. position.z = tmat.m[14];
  62144. };
  62145. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62146. var len = bones.length;
  62147. var meshPos = this.mesh.position;
  62148. for (var i = 0; i < len; i++) {
  62149. var bone = bones[i];
  62150. var points = this._debugLines[i];
  62151. if (!points) {
  62152. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62153. this._debugLines[i] = points;
  62154. }
  62155. this._getBonePosition(points[0], bone, meshMat);
  62156. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62157. points[0].subtractInPlace(meshPos);
  62158. points[1].subtractInPlace(meshPos);
  62159. }
  62160. };
  62161. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62162. var len = bones.length;
  62163. var boneNum = 0;
  62164. var meshPos = this.mesh.position;
  62165. for (var i = len - 1; i >= 0; i--) {
  62166. var childBone = bones[i];
  62167. var parentBone = childBone.getParent();
  62168. if (!parentBone) {
  62169. continue;
  62170. }
  62171. var points = this._debugLines[boneNum];
  62172. if (!points) {
  62173. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62174. this._debugLines[boneNum] = points;
  62175. }
  62176. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62177. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62178. points[0].subtractInPlace(meshPos);
  62179. points[1].subtractInPlace(meshPos);
  62180. boneNum++;
  62181. }
  62182. };
  62183. /** Update the viewer to sync with current skeleton state */
  62184. SkeletonViewer.prototype.update = function () {
  62185. if (this.autoUpdateBonesMatrices) {
  62186. this.skeleton.computeAbsoluteTransforms();
  62187. }
  62188. if (this.skeleton.bones[0].length === undefined) {
  62189. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62190. }
  62191. else {
  62192. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62193. }
  62194. if (!this._debugMesh) {
  62195. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  62196. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62197. }
  62198. else {
  62199. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62200. }
  62201. this._debugMesh.position.copyFrom(this.mesh.position);
  62202. this._debugMesh.color = this.color;
  62203. };
  62204. /** Release associated resources */
  62205. SkeletonViewer.prototype.dispose = function () {
  62206. if (this._debugMesh) {
  62207. this.isEnabled = false;
  62208. this._debugMesh.dispose();
  62209. this._debugMesh = null;
  62210. }
  62211. };
  62212. return SkeletonViewer;
  62213. }());
  62214. Debug.SkeletonViewer = SkeletonViewer;
  62215. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62216. })(BABYLON || (BABYLON = {}));
  62217. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62218. /**
  62219. * Module Debug contains the (visual) components to debug a scene correctly
  62220. */
  62221. var BABYLON;
  62222. (function (BABYLON) {
  62223. var Debug;
  62224. (function (Debug) {
  62225. /**
  62226. * The Axes viewer will show 3 axes in a specific point in space
  62227. */
  62228. var AxesViewer = /** @class */ (function () {
  62229. /**
  62230. * Creates a new AxesViewer
  62231. * @param scene defines the hosting scene
  62232. * @param scaleLines defines a number used to scale line length (1 by default)
  62233. */
  62234. function AxesViewer(scene, scaleLines) {
  62235. if (scaleLines === void 0) { scaleLines = 1; }
  62236. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62237. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62238. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62239. /**
  62240. * Gets or sets a number used to scale line length
  62241. */
  62242. this.scaleLines = 1;
  62243. this.scaleLines = scaleLines;
  62244. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62245. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62246. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62247. this._xmesh.renderingGroupId = 2;
  62248. this._ymesh.renderingGroupId = 2;
  62249. this._zmesh.renderingGroupId = 2;
  62250. this._xmesh.material.checkReadyOnlyOnce = true;
  62251. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62252. this._ymesh.material.checkReadyOnlyOnce = true;
  62253. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62254. this._zmesh.material.checkReadyOnlyOnce = true;
  62255. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62256. this.scene = scene;
  62257. }
  62258. /**
  62259. * Force the viewer to update
  62260. * @param position defines the position of the viewer
  62261. * @param xaxis defines the x axis of the viewer
  62262. * @param yaxis defines the y axis of the viewer
  62263. * @param zaxis defines the z axis of the viewer
  62264. */
  62265. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62266. var scaleLines = this.scaleLines;
  62267. if (this._xmesh) {
  62268. this._xmesh.position.copyFrom(position);
  62269. }
  62270. if (this._ymesh) {
  62271. this._ymesh.position.copyFrom(position);
  62272. }
  62273. if (this._zmesh) {
  62274. this._zmesh.position.copyFrom(position);
  62275. }
  62276. var point2 = this._xline[1];
  62277. point2.x = xaxis.x * scaleLines;
  62278. point2.y = xaxis.y * scaleLines;
  62279. point2.z = xaxis.z * scaleLines;
  62280. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62281. point2 = this._yline[1];
  62282. point2.x = yaxis.x * scaleLines;
  62283. point2.y = yaxis.y * scaleLines;
  62284. point2.z = yaxis.z * scaleLines;
  62285. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62286. point2 = this._zline[1];
  62287. point2.x = zaxis.x * scaleLines;
  62288. point2.y = zaxis.y * scaleLines;
  62289. point2.z = zaxis.z * scaleLines;
  62290. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62291. };
  62292. /** Releases resources */
  62293. AxesViewer.prototype.dispose = function () {
  62294. if (this._xmesh) {
  62295. this._xmesh.dispose();
  62296. }
  62297. if (this._ymesh) {
  62298. this._ymesh.dispose();
  62299. }
  62300. if (this._zmesh) {
  62301. this._zmesh.dispose();
  62302. }
  62303. this._xmesh = null;
  62304. this._ymesh = null;
  62305. this._zmesh = null;
  62306. this.scene = null;
  62307. };
  62308. return AxesViewer;
  62309. }());
  62310. Debug.AxesViewer = AxesViewer;
  62311. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62312. })(BABYLON || (BABYLON = {}));
  62313. //# sourceMappingURL=babylon.axesViewer.js.map
  62314. var BABYLON;
  62315. (function (BABYLON) {
  62316. var Debug;
  62317. (function (Debug) {
  62318. /**
  62319. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62320. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62321. */
  62322. var BoneAxesViewer = /** @class */ (function (_super) {
  62323. __extends(BoneAxesViewer, _super);
  62324. /**
  62325. * Creates a new BoneAxesViewer
  62326. * @param scene defines the hosting scene
  62327. * @param bone defines the target bone
  62328. * @param mesh defines the target mesh
  62329. * @param scaleLines defines a scaling factor for line length (1 by default)
  62330. */
  62331. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62332. if (scaleLines === void 0) { scaleLines = 1; }
  62333. var _this = _super.call(this, scene, scaleLines) || this;
  62334. /** Gets current position */
  62335. _this.pos = BABYLON.Vector3.Zero();
  62336. /** Gets direction of X axis */
  62337. _this.xaxis = BABYLON.Vector3.Zero();
  62338. /** Gets direction of Y axis */
  62339. _this.yaxis = BABYLON.Vector3.Zero();
  62340. /** Gets direction of Z axis */
  62341. _this.zaxis = BABYLON.Vector3.Zero();
  62342. _this.mesh = mesh;
  62343. _this.bone = bone;
  62344. return _this;
  62345. }
  62346. /**
  62347. * Force the viewer to update
  62348. */
  62349. BoneAxesViewer.prototype.update = function () {
  62350. if (!this.mesh || !this.bone) {
  62351. return;
  62352. }
  62353. var bone = this.bone;
  62354. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62355. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62356. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62357. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62358. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62359. };
  62360. /** Releases resources */
  62361. BoneAxesViewer.prototype.dispose = function () {
  62362. if (this.mesh) {
  62363. this.mesh = null;
  62364. this.bone = null;
  62365. _super.prototype.dispose.call(this);
  62366. }
  62367. };
  62368. return BoneAxesViewer;
  62369. }(Debug.AxesViewer));
  62370. Debug.BoneAxesViewer = BoneAxesViewer;
  62371. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62372. })(BABYLON || (BABYLON = {}));
  62373. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62374. var BABYLON;
  62375. (function (BABYLON) {
  62376. /**
  62377. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62378. * in order to better appreciate the issue one might have.
  62379. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62380. */
  62381. var RayHelper = /** @class */ (function () {
  62382. /**
  62383. * Instantiate a new ray helper.
  62384. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62385. * in order to better appreciate the issue one might have.
  62386. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62387. * @param ray Defines the ray we are currently tryin to visualize
  62388. */
  62389. function RayHelper(ray) {
  62390. this.ray = ray;
  62391. }
  62392. /**
  62393. * Helper function to create a colored helper in a scene in one line.
  62394. * @param ray Defines the ray we are currently tryin to visualize
  62395. * @param scene Defines the scene the ray is used in
  62396. * @param color Defines the color we want to see the ray in
  62397. * @returns The newly created ray helper.
  62398. */
  62399. RayHelper.CreateAndShow = function (ray, scene, color) {
  62400. var helper = new RayHelper(ray);
  62401. helper.show(scene, color);
  62402. return helper;
  62403. };
  62404. /**
  62405. * Shows the ray we are willing to debug.
  62406. * @param scene Defines the scene the ray needs to be rendered in
  62407. * @param color Defines the color the ray needs to be rendered in
  62408. */
  62409. RayHelper.prototype.show = function (scene, color) {
  62410. if (!this._renderFunction && this.ray) {
  62411. var ray = this.ray;
  62412. this._renderFunction = this._render.bind(this);
  62413. this._scene = scene;
  62414. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62415. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62416. if (this._renderFunction) {
  62417. this._scene.registerBeforeRender(this._renderFunction);
  62418. }
  62419. }
  62420. if (color && this._renderLine) {
  62421. this._renderLine.color.copyFrom(color);
  62422. }
  62423. };
  62424. /**
  62425. * Hides the ray we are debugging.
  62426. */
  62427. RayHelper.prototype.hide = function () {
  62428. if (this._renderFunction && this._scene) {
  62429. this._scene.unregisterBeforeRender(this._renderFunction);
  62430. this._scene = null;
  62431. this._renderFunction = null;
  62432. if (this._renderLine) {
  62433. this._renderLine.dispose();
  62434. this._renderLine = null;
  62435. }
  62436. this._renderPoints = [];
  62437. }
  62438. };
  62439. RayHelper.prototype._render = function () {
  62440. var ray = this.ray;
  62441. if (!ray) {
  62442. return;
  62443. }
  62444. var point = this._renderPoints[1];
  62445. var len = Math.min(ray.length, 1000000);
  62446. point.copyFrom(ray.direction);
  62447. point.scaleInPlace(len);
  62448. point.addInPlace(ray.origin);
  62449. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62450. };
  62451. /**
  62452. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  62453. * @param mesh Defines the mesh we want the helper attached to
  62454. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  62455. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  62456. * @param length Defines the length of the ray
  62457. */
  62458. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62459. this._attachedToMesh = mesh;
  62460. var ray = this.ray;
  62461. if (!ray) {
  62462. return;
  62463. }
  62464. if (!ray.direction) {
  62465. ray.direction = BABYLON.Vector3.Zero();
  62466. }
  62467. if (!ray.origin) {
  62468. ray.origin = BABYLON.Vector3.Zero();
  62469. }
  62470. if (length) {
  62471. ray.length = length;
  62472. }
  62473. if (!meshSpaceOrigin) {
  62474. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62475. }
  62476. if (!meshSpaceDirection) {
  62477. // -1 so that this will work with Mesh.lookAt
  62478. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62479. }
  62480. if (!this._meshSpaceDirection) {
  62481. this._meshSpaceDirection = meshSpaceDirection.clone();
  62482. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62483. }
  62484. else {
  62485. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62486. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62487. }
  62488. if (!this._updateToMeshFunction) {
  62489. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62490. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62491. }
  62492. this._updateToMesh();
  62493. };
  62494. /**
  62495. * Detach the ray helper from the mesh it has previously been attached to.
  62496. */
  62497. RayHelper.prototype.detachFromMesh = function () {
  62498. if (this._attachedToMesh) {
  62499. if (this._updateToMeshFunction) {
  62500. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62501. }
  62502. this._attachedToMesh = null;
  62503. this._updateToMeshFunction = null;
  62504. }
  62505. };
  62506. RayHelper.prototype._updateToMesh = function () {
  62507. var ray = this.ray;
  62508. if (!this._attachedToMesh || !ray) {
  62509. return;
  62510. }
  62511. if (this._attachedToMesh._isDisposed) {
  62512. this.detachFromMesh();
  62513. return;
  62514. }
  62515. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62516. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62517. };
  62518. /**
  62519. * Dispose the helper and release its associated resources.
  62520. */
  62521. RayHelper.prototype.dispose = function () {
  62522. this.hide();
  62523. this.detachFromMesh();
  62524. this.ray = null;
  62525. };
  62526. return RayHelper;
  62527. }());
  62528. BABYLON.RayHelper = RayHelper;
  62529. })(BABYLON || (BABYLON = {}));
  62530. //# sourceMappingURL=babylon.rayHelper.js.map
  62531. var BABYLON;
  62532. (function (BABYLON) {
  62533. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62534. get: function () {
  62535. if (!this._debugLayer) {
  62536. this._debugLayer = new DebugLayer(this);
  62537. }
  62538. return this._debugLayer;
  62539. },
  62540. enumerable: true,
  62541. configurable: true
  62542. });
  62543. /**
  62544. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62545. * what is happening in your scene
  62546. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62547. */
  62548. var DebugLayer = /** @class */ (function () {
  62549. /**
  62550. * Instantiates a new debug layer.
  62551. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62552. * what is happening in your scene
  62553. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62554. * @param scene Defines the scene to inspect
  62555. */
  62556. function DebugLayer(scene) {
  62557. var _this = this;
  62558. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62559. /**
  62560. * Observable triggered when a property is changed through the inspector.
  62561. */
  62562. this.onPropertyChangedObservable = new BABYLON.Observable();
  62563. this._scene = scene;
  62564. this._scene.onDisposeObservable.add(function () {
  62565. // Debug layer
  62566. if (_this._scene._debugLayer) {
  62567. _this._scene._debugLayer.hide();
  62568. }
  62569. });
  62570. }
  62571. /** Creates the inspector window. */
  62572. DebugLayer.prototype._createInspector = function (config) {
  62573. if (config === void 0) { config = {}; }
  62574. var popup = config.popup || false;
  62575. var initialTab = config.initialTab || 0;
  62576. var parentElement = config.parentElement || null;
  62577. if (!this._inspector) {
  62578. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62579. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62580. } // else nothing to do as instance is already created
  62581. };
  62582. /**
  62583. * Get if the inspector is visible or not.
  62584. * @returns true if visible otherwise, false
  62585. */
  62586. DebugLayer.prototype.isVisible = function () {
  62587. if (!this._inspector) {
  62588. return false;
  62589. }
  62590. return true;
  62591. };
  62592. /**
  62593. * Hide the inspector and close its window.
  62594. */
  62595. DebugLayer.prototype.hide = function () {
  62596. if (this._inspector) {
  62597. try {
  62598. this._inspector.dispose();
  62599. }
  62600. catch (e) {
  62601. // If the inspector has been removed directly from the inspector tool
  62602. }
  62603. this.onPropertyChangedObservable.clear();
  62604. this._inspector = null;
  62605. }
  62606. };
  62607. /**
  62608. *
  62609. * Launch the debugLayer.
  62610. *
  62611. * initialTab:
  62612. * | Value | Tab Name |
  62613. * | --- | --- |
  62614. * | 0 | Scene |
  62615. * | 1 | Console |
  62616. * | 2 | Stats |
  62617. * | 3 | Textures |
  62618. * | 4 | Mesh |
  62619. * | 5 | Light |
  62620. * | 6 | Material |
  62621. * | 7 | GLTF |
  62622. * | 8 | GUI |
  62623. * | 9 | Physics |
  62624. * | 10 | Camera |
  62625. * | 11 | Audio |
  62626. *
  62627. * @param config Define the configuration of the inspector
  62628. */
  62629. DebugLayer.prototype.show = function (config) {
  62630. if (config === void 0) { config = {}; }
  62631. if (typeof this.BJSINSPECTOR == 'undefined') {
  62632. // Load inspector and add it to the DOM
  62633. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62634. }
  62635. else {
  62636. // Otherwise creates the inspector
  62637. this._createInspector(config);
  62638. }
  62639. };
  62640. /**
  62641. * Gets the active tab
  62642. * @return the index of the active tab or -1 if the inspector is hidden
  62643. */
  62644. DebugLayer.prototype.getActiveTab = function () {
  62645. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62646. };
  62647. /**
  62648. * Define the url to get the inspector script from.
  62649. * By default it uses the babylonjs CDN.
  62650. * @ignoreNaming
  62651. */
  62652. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62653. return DebugLayer;
  62654. }());
  62655. BABYLON.DebugLayer = DebugLayer;
  62656. })(BABYLON || (BABYLON = {}));
  62657. //# sourceMappingURL=babylon.debugLayer.js.map
  62658. var BABYLON;
  62659. (function (BABYLON) {
  62660. var Debug;
  62661. (function (Debug) {
  62662. /**
  62663. * Used to show the physics impostor around the specific mesh
  62664. */
  62665. var PhysicsViewer = /** @class */ (function () {
  62666. /**
  62667. * Creates a new PhysicsViewer
  62668. * @param scene defines the hosting scene
  62669. */
  62670. function PhysicsViewer(scene) {
  62671. /** @hidden */
  62672. this._impostors = [];
  62673. /** @hidden */
  62674. this._meshes = [];
  62675. /** @hidden */
  62676. this._numMeshes = 0;
  62677. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62678. var physicEngine = this._scene.getPhysicsEngine();
  62679. if (physicEngine) {
  62680. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62681. }
  62682. }
  62683. /** @hidden */
  62684. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62685. var plugin = this._physicsEnginePlugin;
  62686. for (var i = 0; i < this._numMeshes; i++) {
  62687. var impostor = this._impostors[i];
  62688. if (!impostor) {
  62689. continue;
  62690. }
  62691. if (impostor.isDisposed) {
  62692. this.hideImpostor(this._impostors[i--]);
  62693. }
  62694. else {
  62695. var mesh = this._meshes[i];
  62696. if (mesh && plugin) {
  62697. plugin.syncMeshWithImpostor(mesh, impostor);
  62698. }
  62699. }
  62700. }
  62701. };
  62702. /**
  62703. * Renders a specified physic impostor
  62704. * @param impostor defines the impostor to render
  62705. */
  62706. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62707. if (!this._scene) {
  62708. return;
  62709. }
  62710. for (var i = 0; i < this._numMeshes; i++) {
  62711. if (this._impostors[i] == impostor) {
  62712. return;
  62713. }
  62714. }
  62715. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62716. if (debugMesh) {
  62717. this._impostors[this._numMeshes] = impostor;
  62718. this._meshes[this._numMeshes] = debugMesh;
  62719. if (this._numMeshes === 0) {
  62720. this._renderFunction = this._updateDebugMeshes.bind(this);
  62721. this._scene.registerBeforeRender(this._renderFunction);
  62722. }
  62723. this._numMeshes++;
  62724. }
  62725. };
  62726. /**
  62727. * Hides a specified physic impostor
  62728. * @param impostor defines the impostor to hide
  62729. */
  62730. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62731. if (!impostor || !this._scene) {
  62732. return;
  62733. }
  62734. var removed = false;
  62735. for (var i = 0; i < this._numMeshes; i++) {
  62736. if (this._impostors[i] == impostor) {
  62737. var mesh = this._meshes[i];
  62738. if (!mesh) {
  62739. continue;
  62740. }
  62741. this._scene.removeMesh(mesh);
  62742. mesh.dispose();
  62743. this._numMeshes--;
  62744. if (this._numMeshes > 0) {
  62745. this._meshes[i] = this._meshes[this._numMeshes];
  62746. this._impostors[i] = this._impostors[this._numMeshes];
  62747. this._meshes[this._numMeshes] = null;
  62748. this._impostors[this._numMeshes] = null;
  62749. }
  62750. else {
  62751. this._meshes[0] = null;
  62752. this._impostors[0] = null;
  62753. }
  62754. removed = true;
  62755. break;
  62756. }
  62757. }
  62758. if (removed && this._numMeshes === 0) {
  62759. this._scene.unregisterBeforeRender(this._renderFunction);
  62760. }
  62761. };
  62762. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62763. if (!this._debugMaterial) {
  62764. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62765. this._debugMaterial.wireframe = true;
  62766. }
  62767. return this._debugMaterial;
  62768. };
  62769. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62770. if (!this._debugBoxMesh) {
  62771. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62772. this._debugBoxMesh.renderingGroupId = 1;
  62773. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62774. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62775. scene.removeMesh(this._debugBoxMesh);
  62776. }
  62777. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62778. };
  62779. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62780. if (!this._debugSphereMesh) {
  62781. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62782. this._debugSphereMesh.renderingGroupId = 1;
  62783. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62784. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62785. scene.removeMesh(this._debugSphereMesh);
  62786. }
  62787. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62788. };
  62789. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62790. var mesh = null;
  62791. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62792. mesh = this._getDebugBoxMesh(scene);
  62793. impostor.getBoxSizeToRef(mesh.scaling);
  62794. }
  62795. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62796. mesh = this._getDebugSphereMesh(scene);
  62797. var radius = impostor.getRadius();
  62798. mesh.scaling.x = radius * 2;
  62799. mesh.scaling.y = radius * 2;
  62800. mesh.scaling.z = radius * 2;
  62801. }
  62802. return mesh;
  62803. };
  62804. /** Releases all resources */
  62805. PhysicsViewer.prototype.dispose = function () {
  62806. for (var i = 0; i < this._numMeshes; i++) {
  62807. this.hideImpostor(this._impostors[i]);
  62808. }
  62809. if (this._debugBoxMesh) {
  62810. this._debugBoxMesh.dispose();
  62811. }
  62812. if (this._debugSphereMesh) {
  62813. this._debugSphereMesh.dispose();
  62814. }
  62815. if (this._debugMaterial) {
  62816. this._debugMaterial.dispose();
  62817. }
  62818. this._impostors.length = 0;
  62819. this._scene = null;
  62820. this._physicsEnginePlugin = null;
  62821. };
  62822. return PhysicsViewer;
  62823. }());
  62824. Debug.PhysicsViewer = PhysicsViewer;
  62825. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62826. })(BABYLON || (BABYLON = {}));
  62827. //# sourceMappingURL=babylon.physicsViewer.js.map
  62828. var BABYLON;
  62829. (function (BABYLON) {
  62830. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62831. get: function () {
  62832. return this._forceShowBoundingBoxes || false;
  62833. },
  62834. set: function (value) {
  62835. this._forceShowBoundingBoxes = value;
  62836. // Lazyly creates a BB renderer if needed.
  62837. if (value) {
  62838. this.getBoundingBoxRenderer();
  62839. }
  62840. },
  62841. enumerable: true,
  62842. configurable: true
  62843. });
  62844. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62845. if (!this._boundingBoxRenderer) {
  62846. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62847. }
  62848. return this._boundingBoxRenderer;
  62849. };
  62850. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62851. get: function () {
  62852. return this._showBoundingBox || false;
  62853. },
  62854. set: function (value) {
  62855. this._showBoundingBox = value;
  62856. // Lazyly creates a BB renderer if needed.
  62857. if (value) {
  62858. this.getScene().getBoundingBoxRenderer();
  62859. }
  62860. },
  62861. enumerable: true,
  62862. configurable: true
  62863. });
  62864. /**
  62865. * Component responsible of rendering the bounding box of the meshes in a scene.
  62866. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  62867. */
  62868. var BoundingBoxRenderer = /** @class */ (function () {
  62869. /**
  62870. * Instantiates a new bounding box renderer in a scene.
  62871. * @param scene the scene the renderer renders in
  62872. */
  62873. function BoundingBoxRenderer(scene) {
  62874. /**
  62875. * The component name helpfull to identify the component in the list of scene components.
  62876. */
  62877. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62878. /**
  62879. * Color of the bounding box lines placed in front of an object
  62880. */
  62881. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62882. /**
  62883. * Color of the bounding box lines placed behind an object
  62884. */
  62885. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62886. /**
  62887. * Defines if the renderer should show the back lines or not
  62888. */
  62889. this.showBackLines = true;
  62890. /**
  62891. * @hidden
  62892. */
  62893. this.renderList = new BABYLON.SmartArray(32);
  62894. this._vertexBuffers = {};
  62895. this.scene = scene;
  62896. scene._addComponent(this);
  62897. }
  62898. /**
  62899. * Registers the component in a given scene
  62900. */
  62901. BoundingBoxRenderer.prototype.register = function () {
  62902. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62903. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62904. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62905. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62906. };
  62907. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62908. if (mesh.showSubMeshesBoundingBox) {
  62909. var boundingInfo = subMesh.getBoundingInfo();
  62910. if (boundingInfo !== null && boundingInfo !== undefined) {
  62911. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62912. this.renderList.push(boundingInfo.boundingBox);
  62913. }
  62914. }
  62915. };
  62916. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62917. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62918. var boundingInfo = sourceMesh.getBoundingInfo();
  62919. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62920. this.renderList.push(boundingInfo.boundingBox);
  62921. }
  62922. };
  62923. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62924. if (this._colorShader) {
  62925. return;
  62926. }
  62927. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62928. attributes: [BABYLON.VertexBuffer.PositionKind],
  62929. uniforms: ["world", "viewProjection", "color"]
  62930. });
  62931. var engine = this.scene.getEngine();
  62932. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62934. this._createIndexBuffer();
  62935. };
  62936. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62937. var engine = this.scene.getEngine();
  62938. 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]);
  62939. };
  62940. /**
  62941. * Rebuilds the elements related to this component in case of
  62942. * context lost for instance.
  62943. */
  62944. BoundingBoxRenderer.prototype.rebuild = function () {
  62945. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62946. if (vb) {
  62947. vb._rebuild();
  62948. }
  62949. this._createIndexBuffer();
  62950. };
  62951. /**
  62952. * @hidden
  62953. */
  62954. BoundingBoxRenderer.prototype.reset = function () {
  62955. this.renderList.reset();
  62956. };
  62957. /**
  62958. * Render the bounding boxes of a specific rendering group
  62959. * @param renderingGroupId defines the rendering group to render
  62960. */
  62961. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62962. if (this.renderList.length === 0) {
  62963. return;
  62964. }
  62965. this._prepareRessources();
  62966. if (!this._colorShader.isReady()) {
  62967. return;
  62968. }
  62969. var engine = this.scene.getEngine();
  62970. engine.setDepthWrite(false);
  62971. this._colorShader._preBind();
  62972. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62973. var boundingBox = this.renderList.data[boundingBoxIndex];
  62974. if (boundingBox._tag !== renderingGroupId) {
  62975. continue;
  62976. }
  62977. var min = boundingBox.minimum;
  62978. var max = boundingBox.maximum;
  62979. var diff = max.subtract(min);
  62980. var median = min.add(diff.scale(0.5));
  62981. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62982. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62983. .multiply(boundingBox.getWorldMatrix());
  62984. // VBOs
  62985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62986. if (this.showBackLines) {
  62987. // Back
  62988. engine.setDepthFunctionToGreaterOrEqual();
  62989. this.scene.resetCachedMaterial();
  62990. this._colorShader.setColor4("color", this.backColor.toColor4());
  62991. this._colorShader.bind(worldMatrix);
  62992. // Draw order
  62993. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62994. }
  62995. // Front
  62996. engine.setDepthFunctionToLess();
  62997. this.scene.resetCachedMaterial();
  62998. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62999. this._colorShader.bind(worldMatrix);
  63000. // Draw order
  63001. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63002. }
  63003. this._colorShader.unbind();
  63004. engine.setDepthFunctionToLessOrEqual();
  63005. engine.setDepthWrite(true);
  63006. };
  63007. /**
  63008. * In case of occlusion queries, we can render the occlusion bounding box through this method
  63009. * @param mesh Define the mesh to render the occlusion bounding box for
  63010. */
  63011. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63012. this._prepareRessources();
  63013. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  63014. return;
  63015. }
  63016. var engine = this.scene.getEngine();
  63017. engine.setDepthWrite(false);
  63018. engine.setColorWrite(false);
  63019. this._colorShader._preBind();
  63020. var boundingBox = mesh._boundingInfo.boundingBox;
  63021. var min = boundingBox.minimum;
  63022. var max = boundingBox.maximum;
  63023. var diff = max.subtract(min);
  63024. var median = min.add(diff.scale(0.5));
  63025. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63026. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63027. .multiply(boundingBox.getWorldMatrix());
  63028. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63029. engine.setDepthFunctionToLess();
  63030. this.scene.resetCachedMaterial();
  63031. this._colorShader.bind(worldMatrix);
  63032. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63033. this._colorShader.unbind();
  63034. engine.setDepthFunctionToLessOrEqual();
  63035. engine.setDepthWrite(true);
  63036. engine.setColorWrite(true);
  63037. };
  63038. /**
  63039. * Dispose and release the resources attached to this renderer.
  63040. */
  63041. BoundingBoxRenderer.prototype.dispose = function () {
  63042. if (!this._colorShader) {
  63043. return;
  63044. }
  63045. this.renderList.dispose();
  63046. this._colorShader.dispose();
  63047. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63048. if (buffer) {
  63049. buffer.dispose();
  63050. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63051. }
  63052. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63053. };
  63054. return BoundingBoxRenderer;
  63055. }());
  63056. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63057. })(BABYLON || (BABYLON = {}));
  63058. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63059. var BABYLON;
  63060. (function (BABYLON) {
  63061. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63062. return this._gl.createTransformFeedback();
  63063. };
  63064. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63065. this._gl.deleteTransformFeedback(value);
  63066. };
  63067. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63068. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63069. };
  63070. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63071. if (usePoints === void 0) { usePoints = true; }
  63072. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63073. };
  63074. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63075. this._gl.endTransformFeedback();
  63076. };
  63077. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63078. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63079. };
  63080. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63081. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63082. };
  63083. })(BABYLON || (BABYLON = {}));
  63084. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63085. var BABYLON;
  63086. (function (BABYLON) {
  63087. /**
  63088. * This represents a GPU particle system in Babylon
  63089. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63090. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63091. */
  63092. var GPUParticleSystem = /** @class */ (function (_super) {
  63093. __extends(GPUParticleSystem, _super);
  63094. /**
  63095. * Instantiates a GPU particle system.
  63096. * 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.
  63097. * @param name The name of the particle system
  63098. * @param options The options used to create the system
  63099. * @param scene The scene the particle system belongs to
  63100. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63101. */
  63102. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63103. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63104. var _this = _super.call(this, name) || this;
  63105. /**
  63106. * The layer mask we are rendering the particles through.
  63107. */
  63108. _this.layerMask = 0x0FFFFFFF;
  63109. _this._accumulatedCount = 0;
  63110. _this._targetIndex = 0;
  63111. _this._currentRenderId = -1;
  63112. _this._started = false;
  63113. _this._stopped = false;
  63114. _this._timeDelta = 0;
  63115. _this._attributesStrideSize = 21;
  63116. _this._actualFrame = 0;
  63117. _this._rawTextureWidth = 256;
  63118. /**
  63119. * An event triggered when the system is disposed.
  63120. */
  63121. _this.onDisposeObservable = new BABYLON.Observable();
  63122. /**
  63123. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  63124. * to override the particles.
  63125. */
  63126. _this.forceDepthWrite = false;
  63127. _this._preWarmDone = false;
  63128. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63129. // Setup the default processing configuration to the scene.
  63130. _this._attachImageProcessingConfiguration(null);
  63131. _this._engine = _this._scene.getEngine();
  63132. if (!options.randomTextureSize) {
  63133. delete options.randomTextureSize;
  63134. }
  63135. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  63136. var optionsAsNumber = options;
  63137. if (isFinite(optionsAsNumber)) {
  63138. fullOptions.capacity = optionsAsNumber;
  63139. }
  63140. _this._capacity = fullOptions.capacity;
  63141. _this._activeCount = fullOptions.capacity;
  63142. _this._currentActiveCount = 0;
  63143. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  63144. _this._scene.particleSystems.push(_this);
  63145. _this._updateEffectOptions = {
  63146. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  63147. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  63148. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  63149. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  63150. uniformBuffersNames: [],
  63151. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  63152. defines: "",
  63153. fallbacks: null,
  63154. onCompiled: null,
  63155. onError: null,
  63156. indexParameters: null,
  63157. maxSimultaneousLights: 0,
  63158. transformFeedbackVaryings: []
  63159. };
  63160. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  63161. // Random data
  63162. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  63163. var d = [];
  63164. for (var i = 0; i < maxTextureSize; ++i) {
  63165. d.push(Math.random());
  63166. d.push(Math.random());
  63167. d.push(Math.random());
  63168. d.push(Math.random());
  63169. }
  63170. _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);
  63171. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63172. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63173. d = [];
  63174. for (var i = 0; i < maxTextureSize; ++i) {
  63175. d.push(Math.random());
  63176. d.push(Math.random());
  63177. d.push(Math.random());
  63178. d.push(Math.random());
  63179. }
  63180. _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);
  63181. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63182. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63183. _this._randomTextureSize = maxTextureSize;
  63184. return _this;
  63185. }
  63186. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  63187. /**
  63188. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  63189. */
  63190. get: function () {
  63191. if (!BABYLON.Engine.LastCreatedEngine) {
  63192. return false;
  63193. }
  63194. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  63195. },
  63196. enumerable: true,
  63197. configurable: true
  63198. });
  63199. /**
  63200. * Gets the maximum number of particles active at the same time.
  63201. * @returns The max number of active particles.
  63202. */
  63203. GPUParticleSystem.prototype.getCapacity = function () {
  63204. return this._capacity;
  63205. };
  63206. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  63207. /**
  63208. * Gets or set the number of active particles
  63209. */
  63210. get: function () {
  63211. return this._activeCount;
  63212. },
  63213. set: function (value) {
  63214. this._activeCount = Math.min(value, this._capacity);
  63215. },
  63216. enumerable: true,
  63217. configurable: true
  63218. });
  63219. /**
  63220. * Is this system ready to be used/rendered
  63221. * @return true if the system is ready
  63222. */
  63223. GPUParticleSystem.prototype.isReady = function () {
  63224. if (!this._updateEffect) {
  63225. this._recreateUpdateEffect();
  63226. this._recreateRenderEffect();
  63227. return false;
  63228. }
  63229. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  63230. return false;
  63231. }
  63232. return true;
  63233. };
  63234. /**
  63235. * Gets if the system has been started. (Note: this will still be true after stop is called)
  63236. * @returns True if it has been started, otherwise false.
  63237. */
  63238. GPUParticleSystem.prototype.isStarted = function () {
  63239. return this._started;
  63240. };
  63241. /**
  63242. * Starts the particle system and begins to emit
  63243. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  63244. */
  63245. GPUParticleSystem.prototype.start = function (delay) {
  63246. var _this = this;
  63247. if (delay === void 0) { delay = this.startDelay; }
  63248. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  63249. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  63250. }
  63251. if (delay) {
  63252. setTimeout(function () {
  63253. _this.start(0);
  63254. }, delay);
  63255. return;
  63256. }
  63257. this._started = true;
  63258. this._stopped = false;
  63259. this._preWarmDone = false;
  63260. // Animations
  63261. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  63262. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  63263. }
  63264. };
  63265. /**
  63266. * Stops the particle system.
  63267. */
  63268. GPUParticleSystem.prototype.stop = function () {
  63269. this._stopped = true;
  63270. };
  63271. /**
  63272. * Remove all active particles
  63273. */
  63274. GPUParticleSystem.prototype.reset = function () {
  63275. this._releaseBuffers();
  63276. this._releaseVAOs();
  63277. this._currentActiveCount = 0;
  63278. this._targetIndex = 0;
  63279. };
  63280. /**
  63281. * Returns the string "GPUParticleSystem"
  63282. * @returns a string containing the class name
  63283. */
  63284. GPUParticleSystem.prototype.getClassName = function () {
  63285. return "GPUParticleSystem";
  63286. };
  63287. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63288. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63289. this._releaseBuffers();
  63290. return this;
  63291. };
  63292. /**
  63293. * Adds a new color gradient
  63294. * @param gradient defines the gradient to use (between 0 and 1)
  63295. * @param color1 defines the color to affect to the specified gradient
  63296. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63297. * @returns the current particle system
  63298. */
  63299. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63300. if (!this._colorGradients) {
  63301. this._colorGradients = [];
  63302. }
  63303. var colorGradient = new BABYLON.ColorGradient();
  63304. colorGradient.gradient = gradient;
  63305. colorGradient.color1 = color1;
  63306. this._colorGradients.push(colorGradient);
  63307. this._colorGradients.sort(function (a, b) {
  63308. if (a.gradient < b.gradient) {
  63309. return -1;
  63310. }
  63311. else if (a.gradient > b.gradient) {
  63312. return 1;
  63313. }
  63314. return 0;
  63315. });
  63316. if (this._colorGradientsTexture) {
  63317. this._colorGradientsTexture.dispose();
  63318. this._colorGradientsTexture = null;
  63319. }
  63320. this._releaseBuffers();
  63321. return this;
  63322. };
  63323. /**
  63324. * Remove a specific color gradient
  63325. * @param gradient defines the gradient to remove
  63326. * @returns the current particle system
  63327. */
  63328. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63329. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63330. this._colorGradientsTexture = null;
  63331. return this;
  63332. };
  63333. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63334. var valueGradient = new BABYLON.FactorGradient();
  63335. valueGradient.gradient = gradient;
  63336. valueGradient.factor1 = factor;
  63337. factorGradients.push(valueGradient);
  63338. factorGradients.sort(function (a, b) {
  63339. if (a.gradient < b.gradient) {
  63340. return -1;
  63341. }
  63342. else if (a.gradient > b.gradient) {
  63343. return 1;
  63344. }
  63345. return 0;
  63346. });
  63347. this._releaseBuffers();
  63348. };
  63349. /**
  63350. * Adds a new size gradient
  63351. * @param gradient defines the gradient to use (between 0 and 1)
  63352. * @param factor defines the size factor to affect to the specified gradient
  63353. * @returns the current particle system
  63354. */
  63355. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63356. if (!this._sizeGradients) {
  63357. this._sizeGradients = [];
  63358. }
  63359. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63360. if (this._sizeGradientsTexture) {
  63361. this._sizeGradientsTexture.dispose();
  63362. this._sizeGradientsTexture = null;
  63363. }
  63364. this._releaseBuffers();
  63365. return this;
  63366. };
  63367. /**
  63368. * Remove a specific size gradient
  63369. * @param gradient defines the gradient to remove
  63370. * @returns the current particle system
  63371. */
  63372. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63373. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63374. this._sizeGradientsTexture = null;
  63375. return this;
  63376. };
  63377. /**
  63378. * Adds a new angular speed gradient
  63379. * @param gradient defines the gradient to use (between 0 and 1)
  63380. * @param factor defines the angular speed to affect to the specified gradient
  63381. * @returns the current particle system
  63382. */
  63383. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63384. if (!this._angularSpeedGradients) {
  63385. this._angularSpeedGradients = [];
  63386. }
  63387. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63388. if (this._angularSpeedGradientsTexture) {
  63389. this._angularSpeedGradientsTexture.dispose();
  63390. this._angularSpeedGradientsTexture = null;
  63391. }
  63392. this._releaseBuffers();
  63393. return this;
  63394. };
  63395. /**
  63396. * Remove a specific angular speed gradient
  63397. * @param gradient defines the gradient to remove
  63398. * @returns the current particle system
  63399. */
  63400. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63401. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63402. this._angularSpeedGradientsTexture = null;
  63403. return this;
  63404. };
  63405. /**
  63406. * Adds a new velocity gradient
  63407. * @param gradient defines the gradient to use (between 0 and 1)
  63408. * @param factor defines the velocity to affect to the specified gradient
  63409. * @returns the current particle system
  63410. */
  63411. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63412. if (!this._velocityGradients) {
  63413. this._velocityGradients = [];
  63414. }
  63415. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63416. if (this._velocityGradientsTexture) {
  63417. this._velocityGradientsTexture.dispose();
  63418. this._velocityGradientsTexture = null;
  63419. }
  63420. this._releaseBuffers();
  63421. return this;
  63422. };
  63423. /**
  63424. * Remove a specific velocity gradient
  63425. * @param gradient defines the gradient to remove
  63426. * @returns the current particle system
  63427. */
  63428. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63429. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63430. this._velocityGradientsTexture = null;
  63431. return this;
  63432. };
  63433. /**
  63434. * Adds a new limit velocity gradient
  63435. * @param gradient defines the gradient to use (between 0 and 1)
  63436. * @param factor defines the limit velocity value to affect to the specified gradient
  63437. * @returns the current particle system
  63438. */
  63439. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63440. if (!this._limitVelocityGradients) {
  63441. this._limitVelocityGradients = [];
  63442. }
  63443. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63444. if (this._limitVelocityGradientsTexture) {
  63445. this._limitVelocityGradientsTexture.dispose();
  63446. this._limitVelocityGradientsTexture = null;
  63447. }
  63448. this._releaseBuffers();
  63449. return this;
  63450. };
  63451. /**
  63452. * Remove a specific limit velocity gradient
  63453. * @param gradient defines the gradient to remove
  63454. * @returns the current particle system
  63455. */
  63456. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63457. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63458. this._limitVelocityGradientsTexture = null;
  63459. return this;
  63460. };
  63461. /**
  63462. * Adds a new drag gradient
  63463. * @param gradient defines the gradient to use (between 0 and 1)
  63464. * @param factor defines the drag value to affect to the specified gradient
  63465. * @returns the current particle system
  63466. */
  63467. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63468. if (!this._dragGradients) {
  63469. this._dragGradients = [];
  63470. }
  63471. this._addFactorGradient(this._dragGradients, gradient, factor);
  63472. if (this._dragGradientsTexture) {
  63473. this._dragGradientsTexture.dispose();
  63474. this._dragGradientsTexture = null;
  63475. }
  63476. this._releaseBuffers();
  63477. return this;
  63478. };
  63479. /**
  63480. * Remove a specific drag gradient
  63481. * @param gradient defines the gradient to remove
  63482. * @returns the current particle system
  63483. */
  63484. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63485. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63486. this._dragGradientsTexture = null;
  63487. return this;
  63488. };
  63489. /**
  63490. * Not supported by GPUParticleSystem
  63491. * @param gradient defines the gradient to use (between 0 and 1)
  63492. * @param factor defines the emit rate value to affect to the specified gradient
  63493. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63494. * @returns the current particle system
  63495. */
  63496. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63497. // Do nothing as emit rate is not supported by GPUParticleSystem
  63498. return this;
  63499. };
  63500. /**
  63501. * Not supported by GPUParticleSystem
  63502. * @param gradient defines the gradient to remove
  63503. * @returns the current particle system
  63504. */
  63505. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63506. // Do nothing as emit rate is not supported by GPUParticleSystem
  63507. return this;
  63508. };
  63509. /**
  63510. * Not supported by GPUParticleSystem
  63511. * @param gradient defines the gradient to use (between 0 and 1)
  63512. * @param factor defines the start size value to affect to the specified gradient
  63513. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63514. * @returns the current particle system
  63515. */
  63516. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63517. // Do nothing as start size is not supported by GPUParticleSystem
  63518. return this;
  63519. };
  63520. /**
  63521. * Not supported by GPUParticleSystem
  63522. * @param gradient defines the gradient to remove
  63523. * @returns the current particle system
  63524. */
  63525. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63526. // Do nothing as start size is not supported by GPUParticleSystem
  63527. return this;
  63528. };
  63529. /**
  63530. * Not supported by GPUParticleSystem
  63531. * @param gradient defines the gradient to use (between 0 and 1)
  63532. * @param min defines the color remap minimal range
  63533. * @param max defines the color remap maximal range
  63534. * @returns the current particle system
  63535. */
  63536. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63537. // Do nothing as start size is not supported by GPUParticleSystem
  63538. return this;
  63539. };
  63540. /**
  63541. * Not supported by GPUParticleSystem
  63542. * @param gradient defines the gradient to remove
  63543. * @returns the current particle system
  63544. */
  63545. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63546. // Do nothing as start size is not supported by GPUParticleSystem
  63547. return this;
  63548. };
  63549. /**
  63550. * Not supported by GPUParticleSystem
  63551. * @param gradient defines the gradient to use (between 0 and 1)
  63552. * @param min defines the alpha remap minimal range
  63553. * @param max defines the alpha remap maximal range
  63554. * @returns the current particle system
  63555. */
  63556. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63557. // Do nothing as start size is not supported by GPUParticleSystem
  63558. return this;
  63559. };
  63560. /**
  63561. * Not supported by GPUParticleSystem
  63562. * @param gradient defines the gradient to remove
  63563. * @returns the current particle system
  63564. */
  63565. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63566. // Do nothing as start size is not supported by GPUParticleSystem
  63567. return this;
  63568. };
  63569. /**
  63570. * Not supported by GPUParticleSystem
  63571. * @param gradient defines the gradient to use (between 0 and 1)
  63572. * @param color defines the color to affect to the specified gradient
  63573. * @returns the current particle system
  63574. */
  63575. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63576. //Not supported by GPUParticleSystem
  63577. return this;
  63578. };
  63579. /**
  63580. * Not supported by GPUParticleSystem
  63581. * @param gradient defines the gradient to remove
  63582. * @returns the current particle system
  63583. */
  63584. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63585. //Not supported by GPUParticleSystem
  63586. return this;
  63587. };
  63588. /**
  63589. * Not supported by GPUParticleSystem
  63590. * @returns the list of ramp gradients
  63591. */
  63592. GPUParticleSystem.prototype.getRampGradients = function () {
  63593. return null;
  63594. };
  63595. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63596. /**
  63597. * Not supported by GPUParticleSystem
  63598. * Gets or sets a boolean indicating that ramp gradients must be used
  63599. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63600. */
  63601. get: function () {
  63602. //Not supported by GPUParticleSystem
  63603. return false;
  63604. },
  63605. set: function (value) {
  63606. //Not supported by GPUParticleSystem
  63607. },
  63608. enumerable: true,
  63609. configurable: true
  63610. });
  63611. /**
  63612. * Not supported by GPUParticleSystem
  63613. * @param gradient defines the gradient to use (between 0 and 1)
  63614. * @param factor defines the life time factor to affect to the specified gradient
  63615. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63616. * @returns the current particle system
  63617. */
  63618. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  63619. //Not supported by GPUParticleSystem
  63620. return this;
  63621. };
  63622. /**
  63623. * Not supported by GPUParticleSystem
  63624. * @param gradient defines the gradient to remove
  63625. * @returns the current particle system
  63626. */
  63627. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  63628. //Not supported by GPUParticleSystem
  63629. return this;
  63630. };
  63631. GPUParticleSystem.prototype._reset = function () {
  63632. this._releaseBuffers();
  63633. };
  63634. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63635. var updateVertexBuffers = {};
  63636. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63637. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63638. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63639. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63640. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63641. var offset = 12;
  63642. if (!this._colorGradientsTexture) {
  63643. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63644. offset += 4;
  63645. }
  63646. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63647. offset += 3;
  63648. if (!this._isBillboardBased) {
  63649. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63650. offset += 3;
  63651. }
  63652. if (this._angularSpeedGradientsTexture) {
  63653. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63654. offset += 1;
  63655. }
  63656. else {
  63657. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63658. offset += 2;
  63659. }
  63660. if (this._isAnimationSheetEnabled) {
  63661. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63662. offset += 1;
  63663. if (this.spriteRandomStartCell) {
  63664. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63665. offset += 1;
  63666. }
  63667. }
  63668. if (this.noiseTexture) {
  63669. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63670. offset += 3;
  63671. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63672. offset += 3;
  63673. }
  63674. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63675. this._engine.bindArrayBuffer(null);
  63676. return vao;
  63677. };
  63678. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63679. var renderVertexBuffers = {};
  63680. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63681. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63682. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63683. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63684. var offset = 12;
  63685. if (!this._colorGradientsTexture) {
  63686. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63687. offset += 4;
  63688. }
  63689. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63690. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63691. }
  63692. offset += 3; // Direction
  63693. if (!this._isBillboardBased) {
  63694. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63695. offset += 3;
  63696. }
  63697. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63698. if (this._angularSpeedGradientsTexture) {
  63699. offset++;
  63700. }
  63701. else {
  63702. offset += 2;
  63703. }
  63704. if (this._isAnimationSheetEnabled) {
  63705. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63706. offset += 1;
  63707. if (this.spriteRandomStartCell) {
  63708. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63709. offset += 1;
  63710. }
  63711. }
  63712. if (this.noiseTexture) {
  63713. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63714. offset += 3;
  63715. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63716. offset += 3;
  63717. }
  63718. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63719. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63720. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63721. this._engine.bindArrayBuffer(null);
  63722. return vao;
  63723. };
  63724. GPUParticleSystem.prototype._initialize = function (force) {
  63725. if (force === void 0) { force = false; }
  63726. if (this._buffer0 && !force) {
  63727. return;
  63728. }
  63729. var engine = this._scene.getEngine();
  63730. var data = new Array();
  63731. if (!this.isBillboardBased) {
  63732. this._attributesStrideSize += 3;
  63733. }
  63734. if (this._colorGradientsTexture) {
  63735. this._attributesStrideSize -= 4;
  63736. }
  63737. if (this._angularSpeedGradientsTexture) {
  63738. this._attributesStrideSize -= 1;
  63739. }
  63740. if (this._isAnimationSheetEnabled) {
  63741. this._attributesStrideSize += 1;
  63742. if (this.spriteRandomStartCell) {
  63743. this._attributesStrideSize += 1;
  63744. }
  63745. }
  63746. if (this.noiseTexture) {
  63747. this._attributesStrideSize += 6;
  63748. }
  63749. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63750. // position
  63751. data.push(0.0);
  63752. data.push(0.0);
  63753. data.push(0.0);
  63754. // Age and life
  63755. data.push(0.0); // create the particle as a dead one to create a new one at start
  63756. data.push(0.0);
  63757. // Seed
  63758. data.push(Math.random());
  63759. data.push(Math.random());
  63760. data.push(Math.random());
  63761. data.push(Math.random());
  63762. // Size
  63763. data.push(0.0);
  63764. data.push(0.0);
  63765. data.push(0.0);
  63766. if (!this._colorGradientsTexture) {
  63767. // color
  63768. data.push(0.0);
  63769. data.push(0.0);
  63770. data.push(0.0);
  63771. data.push(0.0);
  63772. }
  63773. // direction
  63774. data.push(0.0);
  63775. data.push(0.0);
  63776. data.push(0.0);
  63777. if (!this.isBillboardBased) {
  63778. // initialDirection
  63779. data.push(0.0);
  63780. data.push(0.0);
  63781. data.push(0.0);
  63782. }
  63783. // angle
  63784. data.push(0.0);
  63785. if (!this._angularSpeedGradientsTexture) {
  63786. data.push(0.0);
  63787. }
  63788. if (this._isAnimationSheetEnabled) {
  63789. data.push(0.0);
  63790. if (this.spriteRandomStartCell) {
  63791. data.push(0.0);
  63792. }
  63793. }
  63794. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  63795. data.push(Math.random());
  63796. data.push(Math.random());
  63797. data.push(Math.random());
  63798. data.push(Math.random());
  63799. data.push(Math.random());
  63800. data.push(Math.random());
  63801. }
  63802. }
  63803. // Sprite data
  63804. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63805. -0.5, 0.5, 0, 1,
  63806. -0.5, -0.5, 0, 0,
  63807. 0.5, -0.5, 1, 0]);
  63808. // Buffers
  63809. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63810. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63811. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63812. // Update VAO
  63813. this._updateVAO = [];
  63814. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63815. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63816. // Render VAO
  63817. this._renderVAO = [];
  63818. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63819. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63820. // Links
  63821. this._sourceBuffer = this._buffer0;
  63822. this._targetBuffer = this._buffer1;
  63823. };
  63824. /** @hidden */
  63825. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63826. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63827. if (this._isBillboardBased) {
  63828. defines += "\n#define BILLBOARD";
  63829. }
  63830. if (this._colorGradientsTexture) {
  63831. defines += "\n#define COLORGRADIENTS";
  63832. }
  63833. if (this._sizeGradientsTexture) {
  63834. defines += "\n#define SIZEGRADIENTS";
  63835. }
  63836. if (this._angularSpeedGradientsTexture) {
  63837. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63838. }
  63839. if (this._velocityGradientsTexture) {
  63840. defines += "\n#define VELOCITYGRADIENTS";
  63841. }
  63842. if (this._limitVelocityGradientsTexture) {
  63843. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63844. }
  63845. if (this._dragGradientsTexture) {
  63846. defines += "\n#define DRAGGRADIENTS";
  63847. }
  63848. if (this.isAnimationSheetEnabled) {
  63849. defines += "\n#define ANIMATESHEET";
  63850. if (this.spriteRandomStartCell) {
  63851. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63852. }
  63853. }
  63854. if (this.noiseTexture) {
  63855. defines += "\n#define NOISE";
  63856. }
  63857. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63858. return;
  63859. }
  63860. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63861. if (!this._colorGradientsTexture) {
  63862. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63863. }
  63864. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63865. if (!this._isBillboardBased) {
  63866. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63867. }
  63868. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63869. if (this.isAnimationSheetEnabled) {
  63870. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63871. if (this.spriteRandomStartCell) {
  63872. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63873. }
  63874. }
  63875. if (this.noiseTexture) {
  63876. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63877. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63878. }
  63879. this._updateEffectOptions.defines = defines;
  63880. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63881. };
  63882. /** @hidden */
  63883. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63884. var defines = "";
  63885. if (this._scene.clipPlane) {
  63886. defines = "\n#define CLIPPLANE";
  63887. }
  63888. if (this._scene.clipPlane2) {
  63889. defines = "\n#define CLIPPLANE2";
  63890. }
  63891. if (this._scene.clipPlane3) {
  63892. defines = "\n#define CLIPPLANE3";
  63893. }
  63894. if (this._scene.clipPlane4) {
  63895. defines = "\n#define CLIPPLANE4";
  63896. }
  63897. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63898. defines = "\n#define BLENDMULTIPLYMODE";
  63899. }
  63900. if (this._isBillboardBased) {
  63901. defines += "\n#define BILLBOARD";
  63902. switch (this.billboardMode) {
  63903. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63904. defines += "\n#define BILLBOARDY";
  63905. break;
  63906. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63907. defines += "\n#define BILLBOARDSTRETCHED";
  63908. break;
  63909. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63910. default:
  63911. break;
  63912. }
  63913. }
  63914. if (this._colorGradientsTexture) {
  63915. defines += "\n#define COLORGRADIENTS";
  63916. }
  63917. if (this.isAnimationSheetEnabled) {
  63918. defines += "\n#define ANIMATESHEET";
  63919. }
  63920. if (this._imageProcessingConfiguration) {
  63921. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63922. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63923. }
  63924. if (this._renderEffect && this._renderEffect.defines === defines) {
  63925. return;
  63926. }
  63927. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63928. var samplers = ["textureSampler", "colorGradientSampler"];
  63929. if (BABYLON.ImageProcessingConfiguration) {
  63930. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63931. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63932. }
  63933. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63934. };
  63935. /**
  63936. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63937. * @param preWarm defines if we are in the pre-warmimg phase
  63938. */
  63939. GPUParticleSystem.prototype.animate = function (preWarm) {
  63940. if (preWarm === void 0) { preWarm = false; }
  63941. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63942. this._actualFrame += this._timeDelta;
  63943. if (!this._stopped) {
  63944. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63945. this.stop();
  63946. }
  63947. }
  63948. };
  63949. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63950. var texture = this[textureName];
  63951. if (!factorGradients || !factorGradients.length || texture) {
  63952. return;
  63953. }
  63954. var data = new Float32Array(this._rawTextureWidth);
  63955. for (var x = 0; x < this._rawTextureWidth; x++) {
  63956. var ratio = x / this._rawTextureWidth;
  63957. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63958. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63959. });
  63960. }
  63961. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63962. };
  63963. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63964. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63965. };
  63966. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63967. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63968. };
  63969. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63970. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63971. };
  63972. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63973. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63974. };
  63975. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63976. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63977. };
  63978. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63979. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63980. return;
  63981. }
  63982. var data = new Uint8Array(this._rawTextureWidth * 4);
  63983. var tmpColor = BABYLON.Tmp.Color4[0];
  63984. for (var x = 0; x < this._rawTextureWidth; x++) {
  63985. var ratio = x / this._rawTextureWidth;
  63986. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63987. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63988. data[x * 4] = tmpColor.r * 255;
  63989. data[x * 4 + 1] = tmpColor.g * 255;
  63990. data[x * 4 + 2] = tmpColor.b * 255;
  63991. data[x * 4 + 3] = tmpColor.a * 255;
  63992. });
  63993. }
  63994. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63995. };
  63996. /**
  63997. * Renders the particle system in its current state
  63998. * @param preWarm defines if the system should only update the particles but not render them
  63999. * @returns the current number of particles
  64000. */
  64001. GPUParticleSystem.prototype.render = function (preWarm) {
  64002. if (preWarm === void 0) { preWarm = false; }
  64003. if (!this._started) {
  64004. return 0;
  64005. }
  64006. this._createColorGradientTexture();
  64007. this._createSizeGradientTexture();
  64008. this._createAngularSpeedGradientTexture();
  64009. this._createVelocityGradientTexture();
  64010. this._createLimitVelocityGradientTexture();
  64011. this._createDragGradientTexture();
  64012. this._recreateUpdateEffect();
  64013. this._recreateRenderEffect();
  64014. if (!this.isReady()) {
  64015. return 0;
  64016. }
  64017. if (!preWarm) {
  64018. if (!this._preWarmDone && this.preWarmCycles) {
  64019. for (var index = 0; index < this.preWarmCycles; index++) {
  64020. this.animate(true);
  64021. this.render(true);
  64022. }
  64023. this._preWarmDone = true;
  64024. }
  64025. if (this._currentRenderId === this._scene.getRenderId()) {
  64026. return 0;
  64027. }
  64028. this._currentRenderId = this._scene.getRenderId();
  64029. }
  64030. // Get everything ready to render
  64031. this._initialize();
  64032. this._accumulatedCount += this.emitRate * this._timeDelta;
  64033. if (this._accumulatedCount > 1) {
  64034. var intPart = this._accumulatedCount | 0;
  64035. this._accumulatedCount -= intPart;
  64036. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64037. }
  64038. if (!this._currentActiveCount) {
  64039. return 0;
  64040. }
  64041. // Enable update effect
  64042. this._engine.enableEffect(this._updateEffect);
  64043. this._engine.setState(false);
  64044. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64045. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64046. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64047. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64048. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64049. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64050. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64051. if (!this._colorGradientsTexture) {
  64052. this._updateEffect.setDirectColor4("color1", this.color1);
  64053. this._updateEffect.setDirectColor4("color2", this.color2);
  64054. }
  64055. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64056. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64057. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64058. this._updateEffect.setVector3("gravity", this.gravity);
  64059. if (this._sizeGradientsTexture) {
  64060. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64061. }
  64062. if (this._angularSpeedGradientsTexture) {
  64063. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64064. }
  64065. if (this._velocityGradientsTexture) {
  64066. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64067. }
  64068. if (this._limitVelocityGradientsTexture) {
  64069. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64070. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64071. }
  64072. if (this._dragGradientsTexture) {
  64073. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64074. }
  64075. if (this.particleEmitterType) {
  64076. this.particleEmitterType.applyToShader(this._updateEffect);
  64077. }
  64078. if (this._isAnimationSheetEnabled) {
  64079. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64080. }
  64081. if (this.noiseTexture) {
  64082. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64083. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64084. }
  64085. var emitterWM;
  64086. if (this.emitter.position) {
  64087. var emitterMesh = this.emitter;
  64088. emitterWM = emitterMesh.getWorldMatrix();
  64089. }
  64090. else {
  64091. var emitterPosition = this.emitter;
  64092. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64093. }
  64094. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64095. // Bind source VAO
  64096. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64097. // Update
  64098. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64099. this._engine.setRasterizerState(false);
  64100. this._engine.beginTransformFeedback(true);
  64101. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64102. this._engine.endTransformFeedback();
  64103. this._engine.setRasterizerState(true);
  64104. this._engine.bindTransformFeedbackBuffer(null);
  64105. if (!preWarm) {
  64106. // Enable render effect
  64107. this._engine.enableEffect(this._renderEffect);
  64108. var viewMatrix = this._scene.getViewMatrix();
  64109. this._renderEffect.setMatrix("view", viewMatrix);
  64110. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  64111. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  64112. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  64113. if (this._colorGradientsTexture) {
  64114. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  64115. }
  64116. else {
  64117. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  64118. }
  64119. if (this._isAnimationSheetEnabled && this.particleTexture) {
  64120. var baseSize = this.particleTexture.getBaseSize();
  64121. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  64122. }
  64123. if (this._isBillboardBased) {
  64124. var camera = this._scene.activeCamera;
  64125. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  64126. }
  64127. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  64128. var invView = viewMatrix.clone();
  64129. invView.invert();
  64130. this._renderEffect.setMatrix("invView", invView);
  64131. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  64132. }
  64133. // image processing
  64134. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  64135. this._imageProcessingConfiguration.bind(this._renderEffect);
  64136. }
  64137. // Draw order
  64138. switch (this.blendMode) {
  64139. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  64140. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  64141. break;
  64142. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  64143. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  64144. break;
  64145. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  64146. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64147. break;
  64148. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  64149. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  64150. break;
  64151. }
  64152. if (this.forceDepthWrite) {
  64153. this._engine.setDepthWrite(true);
  64154. }
  64155. // Bind source VAO
  64156. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  64157. // Render
  64158. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  64159. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64160. }
  64161. // Switch VAOs
  64162. this._targetIndex++;
  64163. if (this._targetIndex === 2) {
  64164. this._targetIndex = 0;
  64165. }
  64166. // Switch buffers
  64167. var tmpBuffer = this._sourceBuffer;
  64168. this._sourceBuffer = this._targetBuffer;
  64169. this._targetBuffer = tmpBuffer;
  64170. return this._currentActiveCount;
  64171. };
  64172. /**
  64173. * Rebuilds the particle system
  64174. */
  64175. GPUParticleSystem.prototype.rebuild = function () {
  64176. this._initialize(true);
  64177. };
  64178. GPUParticleSystem.prototype._releaseBuffers = function () {
  64179. if (this._buffer0) {
  64180. this._buffer0.dispose();
  64181. this._buffer0 = null;
  64182. }
  64183. if (this._buffer1) {
  64184. this._buffer1.dispose();
  64185. this._buffer1 = null;
  64186. }
  64187. if (this._spriteBuffer) {
  64188. this._spriteBuffer.dispose();
  64189. this._spriteBuffer = null;
  64190. }
  64191. };
  64192. GPUParticleSystem.prototype._releaseVAOs = function () {
  64193. if (!this._updateVAO) {
  64194. return;
  64195. }
  64196. for (var index = 0; index < this._updateVAO.length; index++) {
  64197. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  64198. }
  64199. this._updateVAO = [];
  64200. for (var index = 0; index < this._renderVAO.length; index++) {
  64201. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  64202. }
  64203. this._renderVAO = [];
  64204. };
  64205. /**
  64206. * Disposes the particle system and free the associated resources
  64207. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  64208. */
  64209. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  64210. if (disposeTexture === void 0) { disposeTexture = true; }
  64211. var index = this._scene.particleSystems.indexOf(this);
  64212. if (index > -1) {
  64213. this._scene.particleSystems.splice(index, 1);
  64214. }
  64215. this._releaseBuffers();
  64216. this._releaseVAOs();
  64217. if (this._colorGradientsTexture) {
  64218. this._colorGradientsTexture.dispose();
  64219. this._colorGradientsTexture = null;
  64220. }
  64221. if (this._sizeGradientsTexture) {
  64222. this._sizeGradientsTexture.dispose();
  64223. this._sizeGradientsTexture = null;
  64224. }
  64225. if (this._angularSpeedGradientsTexture) {
  64226. this._angularSpeedGradientsTexture.dispose();
  64227. this._angularSpeedGradientsTexture = null;
  64228. }
  64229. if (this._velocityGradientsTexture) {
  64230. this._velocityGradientsTexture.dispose();
  64231. this._velocityGradientsTexture = null;
  64232. }
  64233. if (this._limitVelocityGradientsTexture) {
  64234. this._limitVelocityGradientsTexture.dispose();
  64235. this._limitVelocityGradientsTexture = null;
  64236. }
  64237. if (this._dragGradientsTexture) {
  64238. this._dragGradientsTexture.dispose();
  64239. this._dragGradientsTexture = null;
  64240. }
  64241. if (this._randomTexture) {
  64242. this._randomTexture.dispose();
  64243. this._randomTexture = null;
  64244. }
  64245. if (this._randomTexture2) {
  64246. this._randomTexture2.dispose();
  64247. this._randomTexture2 = null;
  64248. }
  64249. if (disposeTexture && this.particleTexture) {
  64250. this.particleTexture.dispose();
  64251. this.particleTexture = null;
  64252. }
  64253. if (disposeTexture && this.noiseTexture) {
  64254. this.noiseTexture.dispose();
  64255. this.noiseTexture = null;
  64256. }
  64257. // Callback
  64258. this.onDisposeObservable.notifyObservers(this);
  64259. this.onDisposeObservable.clear();
  64260. };
  64261. /**
  64262. * Clones the particle system.
  64263. * @param name The name of the cloned object
  64264. * @param newEmitter The new emitter to use
  64265. * @returns the cloned particle system
  64266. */
  64267. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  64268. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  64269. BABYLON.Tools.DeepCopy(this, result);
  64270. if (newEmitter === undefined) {
  64271. newEmitter = this.emitter;
  64272. }
  64273. result.emitter = newEmitter;
  64274. if (this.particleTexture) {
  64275. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  64276. }
  64277. return result;
  64278. };
  64279. /**
  64280. * Serializes the particle system to a JSON object.
  64281. * @returns the JSON object
  64282. */
  64283. GPUParticleSystem.prototype.serialize = function () {
  64284. var serializationObject = {};
  64285. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  64286. serializationObject.activeParticleCount = this.activeParticleCount;
  64287. return serializationObject;
  64288. };
  64289. /**
  64290. * Parses a JSON object to create a GPU particle system.
  64291. * @param parsedParticleSystem The JSON object to parse
  64292. * @param scene The scene to create the particle system in
  64293. * @param rootUrl The root url to use to load external dependencies like texture
  64294. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  64295. * @returns the parsed GPU particle system
  64296. */
  64297. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  64298. if (doNotStart === void 0) { doNotStart = false; }
  64299. var name = parsedParticleSystem.name;
  64300. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64301. if (parsedParticleSystem.activeParticleCount) {
  64302. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64303. }
  64304. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64305. // Auto start
  64306. if (parsedParticleSystem.preventAutoStart) {
  64307. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  64308. }
  64309. if (!doNotStart && !particleSystem.preventAutoStart) {
  64310. particleSystem.start();
  64311. }
  64312. return particleSystem;
  64313. };
  64314. return GPUParticleSystem;
  64315. }(BABYLON.BaseParticleSystem));
  64316. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64317. })(BABYLON || (BABYLON = {}));
  64318. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64319. var BABYLON;
  64320. (function (BABYLON) {
  64321. /**
  64322. * Represents one particle of a solid particle system.
  64323. */
  64324. var SolidParticle = /** @class */ (function () {
  64325. /**
  64326. * Creates a Solid Particle object.
  64327. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64328. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64329. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64330. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64331. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64332. * @param shapeId (integer) is the model shape identifier in the SPS.
  64333. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64334. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64335. */
  64336. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64337. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64338. /**
  64339. * particle global index
  64340. */
  64341. this.idx = 0;
  64342. /**
  64343. * The color of the particle
  64344. */
  64345. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64346. /**
  64347. * The world space position of the particle.
  64348. */
  64349. this.position = BABYLON.Vector3.Zero();
  64350. /**
  64351. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64352. */
  64353. this.rotation = BABYLON.Vector3.Zero();
  64354. /**
  64355. * The scaling of the particle.
  64356. */
  64357. this.scaling = BABYLON.Vector3.One();
  64358. /**
  64359. * The uvs of the particle.
  64360. */
  64361. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64362. /**
  64363. * The current speed of the particle.
  64364. */
  64365. this.velocity = BABYLON.Vector3.Zero();
  64366. /**
  64367. * The pivot point in the particle local space.
  64368. */
  64369. this.pivot = BABYLON.Vector3.Zero();
  64370. /**
  64371. * Must the particle be translated from its pivot point in its local space ?
  64372. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64373. * Default : false
  64374. */
  64375. this.translateFromPivot = false;
  64376. /**
  64377. * Is the particle active or not ?
  64378. */
  64379. this.alive = true;
  64380. /**
  64381. * Is the particle visible or not ?
  64382. */
  64383. this.isVisible = true;
  64384. /**
  64385. * Index of this particle in the global "positions" array (Internal use)
  64386. * @hidden
  64387. */
  64388. this._pos = 0;
  64389. /**
  64390. * @hidden Index of this particle in the global "indices" array (Internal use)
  64391. */
  64392. this._ind = 0;
  64393. /**
  64394. * ModelShape id of this particle
  64395. */
  64396. this.shapeId = 0;
  64397. /**
  64398. * Index of the particle in its shape id (Internal use)
  64399. */
  64400. this.idxInShape = 0;
  64401. /**
  64402. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64403. */
  64404. this._stillInvisible = false;
  64405. /**
  64406. * @hidden Last computed particle rotation matrix
  64407. */
  64408. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64409. /**
  64410. * Parent particle Id, if any.
  64411. * Default null.
  64412. */
  64413. this.parentId = null;
  64414. /**
  64415. * @hidden Internal global position in the SPS.
  64416. */
  64417. this._globalPosition = BABYLON.Vector3.Zero();
  64418. this.idx = particleIndex;
  64419. this._pos = positionIndex;
  64420. this._ind = indiceIndex;
  64421. this._model = model;
  64422. this.shapeId = shapeId;
  64423. this.idxInShape = idxInShape;
  64424. this._sps = sps;
  64425. if (modelBoundingInfo) {
  64426. this._modelBoundingInfo = modelBoundingInfo;
  64427. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64428. }
  64429. }
  64430. Object.defineProperty(SolidParticle.prototype, "scale", {
  64431. /**
  64432. * Legacy support, changed scale to scaling
  64433. */
  64434. get: function () {
  64435. return this.scaling;
  64436. },
  64437. /**
  64438. * Legacy support, changed scale to scaling
  64439. */
  64440. set: function (scale) {
  64441. this.scaling = scale;
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64447. /**
  64448. * Legacy support, changed quaternion to rotationQuaternion
  64449. */
  64450. get: function () {
  64451. return this.rotationQuaternion;
  64452. },
  64453. /**
  64454. * Legacy support, changed quaternion to rotationQuaternion
  64455. */
  64456. set: function (q) {
  64457. this.rotationQuaternion = q;
  64458. },
  64459. enumerable: true,
  64460. configurable: true
  64461. });
  64462. /**
  64463. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64464. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64465. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64466. * @returns true if it intersects
  64467. */
  64468. SolidParticle.prototype.intersectsMesh = function (target) {
  64469. if (!this._boundingInfo || !target._boundingInfo) {
  64470. return false;
  64471. }
  64472. if (this._sps._bSphereOnly) {
  64473. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64474. }
  64475. return this._boundingInfo.intersects(target._boundingInfo, false);
  64476. };
  64477. return SolidParticle;
  64478. }());
  64479. BABYLON.SolidParticle = SolidParticle;
  64480. /**
  64481. * Represents the shape of the model used by one particle of a solid particle system.
  64482. * SPS internal tool, don't use it manually.
  64483. */
  64484. var ModelShape = /** @class */ (function () {
  64485. /**
  64486. * 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.
  64487. * SPS internal tool, don't use it manually.
  64488. * @hidden
  64489. */
  64490. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64491. /**
  64492. * length of the shape in the model indices array (internal use)
  64493. * @hidden
  64494. */
  64495. this._indicesLength = 0;
  64496. this.shapeID = id;
  64497. this._shape = shape;
  64498. this._indicesLength = indicesLength;
  64499. this._shapeUV = shapeUV;
  64500. this._positionFunction = posFunction;
  64501. this._vertexFunction = vtxFunction;
  64502. }
  64503. return ModelShape;
  64504. }());
  64505. BABYLON.ModelShape = ModelShape;
  64506. /**
  64507. * Represents a Depth Sorted Particle in the solid particle system.
  64508. */
  64509. var DepthSortedParticle = /** @class */ (function () {
  64510. function DepthSortedParticle() {
  64511. /**
  64512. * Index of the particle in the "indices" array
  64513. */
  64514. this.ind = 0;
  64515. /**
  64516. * Length of the particle shape in the "indices" array
  64517. */
  64518. this.indicesLength = 0;
  64519. /**
  64520. * Squared distance from the particle to the camera
  64521. */
  64522. this.sqDistance = 0.0;
  64523. }
  64524. return DepthSortedParticle;
  64525. }());
  64526. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64527. })(BABYLON || (BABYLON = {}));
  64528. //# sourceMappingURL=babylon.solidParticle.js.map
  64529. var BABYLON;
  64530. (function (BABYLON) {
  64531. /**
  64532. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64533. *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.
  64534. * The SPS is also a particle system. It provides some methods to manage the particles.
  64535. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64536. *
  64537. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64538. */
  64539. var SolidParticleSystem = /** @class */ (function () {
  64540. /**
  64541. * Creates a SPS (Solid Particle System) object.
  64542. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64543. * @param scene (Scene) is the scene in which the SPS is added.
  64544. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64545. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64546. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64547. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64548. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64549. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64550. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64551. */
  64552. function SolidParticleSystem(name, scene, options) {
  64553. /**
  64554. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64555. * Example : var p = SPS.particles[i];
  64556. */
  64557. this.particles = new Array();
  64558. /**
  64559. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64560. */
  64561. this.nbParticles = 0;
  64562. /**
  64563. * If the particles must ever face the camera (default false). Useful for planar particles.
  64564. */
  64565. this.billboard = false;
  64566. /**
  64567. * Recompute normals when adding a shape
  64568. */
  64569. this.recomputeNormals = true;
  64570. /**
  64571. * This a counter ofr your own usage. It's not set by any SPS functions.
  64572. */
  64573. this.counter = 0;
  64574. /**
  64575. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64576. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64577. */
  64578. this.vars = {};
  64579. /**
  64580. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64581. * @hidden
  64582. */
  64583. this._bSphereOnly = false;
  64584. /**
  64585. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64586. * @hidden
  64587. */
  64588. this._bSphereRadiusFactor = 1.0;
  64589. this._positions = new Array();
  64590. this._indices = new Array();
  64591. this._normals = new Array();
  64592. this._colors = new Array();
  64593. this._uvs = new Array();
  64594. this._index = 0; // indices index
  64595. this._updatable = true;
  64596. this._pickable = false;
  64597. this._isVisibilityBoxLocked = false;
  64598. this._alwaysVisible = false;
  64599. this._depthSort = false;
  64600. this._shapeCounter = 0;
  64601. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64602. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64603. this._computeParticleColor = true;
  64604. this._computeParticleTexture = true;
  64605. this._computeParticleRotation = true;
  64606. this._computeParticleVertex = false;
  64607. this._computeBoundingBox = false;
  64608. this._depthSortParticles = true;
  64609. this._cam_axisZ = BABYLON.Vector3.Zero();
  64610. this._cam_axisY = BABYLON.Vector3.Zero();
  64611. this._cam_axisX = BABYLON.Vector3.Zero();
  64612. this._axisZ = BABYLON.Axis.Z;
  64613. this._camDir = BABYLON.Vector3.Zero();
  64614. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64615. this._rotMatrix = new BABYLON.Matrix();
  64616. this._invertMatrix = new BABYLON.Matrix();
  64617. this._rotated = BABYLON.Vector3.Zero();
  64618. this._quaternion = new BABYLON.Quaternion();
  64619. this._vertex = BABYLON.Vector3.Zero();
  64620. this._normal = BABYLON.Vector3.Zero();
  64621. this._yaw = 0.0;
  64622. this._pitch = 0.0;
  64623. this._roll = 0.0;
  64624. this._halfroll = 0.0;
  64625. this._halfpitch = 0.0;
  64626. this._halfyaw = 0.0;
  64627. this._sinRoll = 0.0;
  64628. this._cosRoll = 0.0;
  64629. this._sinPitch = 0.0;
  64630. this._cosPitch = 0.0;
  64631. this._sinYaw = 0.0;
  64632. this._cosYaw = 0.0;
  64633. this._mustUnrotateFixedNormals = false;
  64634. this._minimum = BABYLON.Vector3.Zero();
  64635. this._maximum = BABYLON.Vector3.Zero();
  64636. this._minBbox = BABYLON.Vector3.Zero();
  64637. this._maxBbox = BABYLON.Vector3.Zero();
  64638. this._particlesIntersect = false;
  64639. this._depthSortFunction = function (p1, p2) {
  64640. return (p2.sqDistance - p1.sqDistance);
  64641. };
  64642. this._needs32Bits = false;
  64643. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64644. this._scaledPivot = BABYLON.Vector3.Zero();
  64645. this._particleHasParent = false;
  64646. this.name = name;
  64647. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64648. this._camera = scene.activeCamera;
  64649. this._pickable = options ? options.isPickable : false;
  64650. this._depthSort = options ? options.enableDepthSort : false;
  64651. this._particlesIntersect = options ? options.particleIntersection : false;
  64652. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64653. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64654. if (options && options.updatable !== undefined) {
  64655. this._updatable = options.updatable;
  64656. }
  64657. else {
  64658. this._updatable = true;
  64659. }
  64660. if (this._pickable) {
  64661. this.pickedParticles = [];
  64662. }
  64663. if (this._depthSort) {
  64664. this.depthSortedParticles = [];
  64665. }
  64666. }
  64667. /**
  64668. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64669. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64670. * @returns the created mesh
  64671. */
  64672. SolidParticleSystem.prototype.buildMesh = function () {
  64673. if (this.nbParticles === 0) {
  64674. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64675. this.addShape(triangle, 1);
  64676. triangle.dispose();
  64677. }
  64678. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64679. this._positions32 = new Float32Array(this._positions);
  64680. this._uvs32 = new Float32Array(this._uvs);
  64681. this._colors32 = new Float32Array(this._colors);
  64682. if (this.recomputeNormals) {
  64683. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64684. }
  64685. this._normals32 = new Float32Array(this._normals);
  64686. this._fixedNormal32 = new Float32Array(this._normals);
  64687. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64688. this._unrotateFixedNormals();
  64689. }
  64690. var vertexData = new BABYLON.VertexData();
  64691. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64692. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64693. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64694. if (this._uvs32.length > 0) {
  64695. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64696. }
  64697. if (this._colors32.length > 0) {
  64698. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64699. }
  64700. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64701. vertexData.applyToMesh(mesh, this._updatable);
  64702. this.mesh = mesh;
  64703. this.mesh.isPickable = this._pickable;
  64704. // free memory
  64705. if (!this._depthSort) {
  64706. this._indices = null;
  64707. }
  64708. this._positions = null;
  64709. this._normals = null;
  64710. this._uvs = null;
  64711. this._colors = null;
  64712. if (!this._updatable) {
  64713. this.particles.length = 0;
  64714. }
  64715. return mesh;
  64716. };
  64717. /**
  64718. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64719. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64720. * Thus the particles generated from `digest()` have their property `position` set yet.
  64721. * @param mesh ( Mesh ) is the mesh to be digested
  64722. * @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
  64723. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64724. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64725. * @returns the current SPS
  64726. */
  64727. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64728. var size = (options && options.facetNb) || 1;
  64729. var number = (options && options.number) || 0;
  64730. var delta = (options && options.delta) || 0;
  64731. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64732. var meshInd = mesh.getIndices();
  64733. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64734. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64735. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64736. var f = 0; // facet counter
  64737. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64738. // compute size from number
  64739. if (number) {
  64740. number = (number > totalFacets) ? totalFacets : number;
  64741. size = Math.round(totalFacets / number);
  64742. delta = 0;
  64743. }
  64744. else {
  64745. size = (size > totalFacets) ? totalFacets : size;
  64746. }
  64747. var facetPos = []; // submesh positions
  64748. var facetInd = []; // submesh indices
  64749. var facetUV = []; // submesh UV
  64750. var facetCol = []; // submesh colors
  64751. var barycenter = BABYLON.Vector3.Zero();
  64752. var sizeO = size;
  64753. while (f < totalFacets) {
  64754. size = sizeO + Math.floor((1 + delta) * Math.random());
  64755. if (f > totalFacets - size) {
  64756. size = totalFacets - f;
  64757. }
  64758. // reset temp arrays
  64759. facetPos.length = 0;
  64760. facetInd.length = 0;
  64761. facetUV.length = 0;
  64762. facetCol.length = 0;
  64763. // iterate over "size" facets
  64764. var fi = 0;
  64765. for (var j = f * 3; j < (f + size) * 3; j++) {
  64766. facetInd.push(fi);
  64767. var i = meshInd[j];
  64768. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64769. if (meshUV) {
  64770. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64771. }
  64772. if (meshCol) {
  64773. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64774. }
  64775. fi++;
  64776. }
  64777. // create a model shape for each single particle
  64778. var idx = this.nbParticles;
  64779. var shape = this._posToShape(facetPos);
  64780. var shapeUV = this._uvsToShapeUV(facetUV);
  64781. // compute the barycenter of the shape
  64782. var v;
  64783. for (v = 0; v < shape.length; v++) {
  64784. barycenter.addInPlace(shape[v]);
  64785. }
  64786. barycenter.scaleInPlace(1 / shape.length);
  64787. // shift the shape from its barycenter to the origin
  64788. for (v = 0; v < shape.length; v++) {
  64789. shape[v].subtractInPlace(barycenter);
  64790. }
  64791. var bInfo;
  64792. if (this._particlesIntersect) {
  64793. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64794. }
  64795. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64796. // add the particle in the SPS
  64797. var currentPos = this._positions.length;
  64798. var currentInd = this._indices.length;
  64799. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64800. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64801. // initialize the particle position
  64802. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64803. this._index += shape.length;
  64804. idx++;
  64805. this.nbParticles++;
  64806. this._shapeCounter++;
  64807. f += size;
  64808. }
  64809. return this;
  64810. };
  64811. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64812. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64813. var index = 0;
  64814. var idx = 0;
  64815. for (var p = 0; p < this.particles.length; p++) {
  64816. this._particle = this.particles[p];
  64817. this._shape = this._particle._model._shape;
  64818. if (this._particle.rotationQuaternion) {
  64819. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64820. }
  64821. else {
  64822. this._yaw = this._particle.rotation.y;
  64823. this._pitch = this._particle.rotation.x;
  64824. this._roll = this._particle.rotation.z;
  64825. this._quaternionRotationYPR();
  64826. }
  64827. this._quaternionToRotationMatrix();
  64828. this._rotMatrix.invertToRef(this._invertMatrix);
  64829. for (var pt = 0; pt < this._shape.length; pt++) {
  64830. idx = index + pt * 3;
  64831. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64832. this._fixedNormal32[idx] = this._normal.x;
  64833. this._fixedNormal32[idx + 1] = this._normal.y;
  64834. this._fixedNormal32[idx + 2] = this._normal.z;
  64835. }
  64836. index = idx + 3;
  64837. }
  64838. };
  64839. //reset copy
  64840. SolidParticleSystem.prototype._resetCopy = function () {
  64841. this._copy.position.x = 0;
  64842. this._copy.position.y = 0;
  64843. this._copy.position.z = 0;
  64844. this._copy.rotation.x = 0;
  64845. this._copy.rotation.y = 0;
  64846. this._copy.rotation.z = 0;
  64847. this._copy.rotationQuaternion = null;
  64848. this._copy.scaling.x = 1.0;
  64849. this._copy.scaling.y = 1.0;
  64850. this._copy.scaling.z = 1.0;
  64851. this._copy.uvs.x = 0;
  64852. this._copy.uvs.y = 0;
  64853. this._copy.uvs.z = 1.0;
  64854. this._copy.uvs.w = 1.0;
  64855. this._copy.color = null;
  64856. this._copy.translateFromPivot = false;
  64857. };
  64858. // _meshBuilder : inserts the shape model in the global SPS mesh
  64859. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64860. var i;
  64861. var u = 0;
  64862. var c = 0;
  64863. var n = 0;
  64864. this._resetCopy();
  64865. if (options && options.positionFunction) { // call to custom positionFunction
  64866. options.positionFunction(this._copy, idx, idxInShape);
  64867. this._mustUnrotateFixedNormals = true;
  64868. }
  64869. if (this._copy.rotationQuaternion) {
  64870. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64871. }
  64872. else {
  64873. this._yaw = this._copy.rotation.y;
  64874. this._pitch = this._copy.rotation.x;
  64875. this._roll = this._copy.rotation.z;
  64876. this._quaternionRotationYPR();
  64877. }
  64878. this._quaternionToRotationMatrix();
  64879. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64880. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64881. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64882. if (this._copy.translateFromPivot) {
  64883. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64884. }
  64885. else {
  64886. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64887. }
  64888. for (i = 0; i < shape.length; i++) {
  64889. this._vertex.x = shape[i].x;
  64890. this._vertex.y = shape[i].y;
  64891. this._vertex.z = shape[i].z;
  64892. if (options && options.vertexFunction) {
  64893. options.vertexFunction(this._copy, this._vertex, i);
  64894. }
  64895. this._vertex.x *= this._copy.scaling.x;
  64896. this._vertex.y *= this._copy.scaling.y;
  64897. this._vertex.z *= this._copy.scaling.z;
  64898. this._vertex.x -= this._scaledPivot.x;
  64899. this._vertex.y -= this._scaledPivot.y;
  64900. this._vertex.z -= this._scaledPivot.z;
  64901. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64902. this._rotated.addInPlace(this._pivotBackTranslation);
  64903. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64904. if (meshUV) {
  64905. 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);
  64906. u += 2;
  64907. }
  64908. if (this._copy.color) {
  64909. this._color = this._copy.color;
  64910. }
  64911. else if (meshCol && meshCol[c] !== undefined) {
  64912. this._color.r = meshCol[c];
  64913. this._color.g = meshCol[c + 1];
  64914. this._color.b = meshCol[c + 2];
  64915. this._color.a = meshCol[c + 3];
  64916. }
  64917. else {
  64918. this._color.r = 1.0;
  64919. this._color.g = 1.0;
  64920. this._color.b = 1.0;
  64921. this._color.a = 1.0;
  64922. }
  64923. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64924. c += 4;
  64925. if (!this.recomputeNormals && meshNor) {
  64926. this._normal.x = meshNor[n];
  64927. this._normal.y = meshNor[n + 1];
  64928. this._normal.z = meshNor[n + 2];
  64929. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64930. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64931. n += 3;
  64932. }
  64933. }
  64934. for (i = 0; i < meshInd.length; i++) {
  64935. var current_ind = p + meshInd[i];
  64936. indices.push(current_ind);
  64937. if (current_ind > 65535) {
  64938. this._needs32Bits = true;
  64939. }
  64940. }
  64941. if (this._pickable) {
  64942. var nbfaces = meshInd.length / 3;
  64943. for (i = 0; i < nbfaces; i++) {
  64944. this.pickedParticles.push({ idx: idx, faceId: i });
  64945. }
  64946. }
  64947. if (this._depthSort) {
  64948. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64949. }
  64950. return this._copy;
  64951. };
  64952. // returns a shape array from positions array
  64953. SolidParticleSystem.prototype._posToShape = function (positions) {
  64954. var shape = [];
  64955. for (var i = 0; i < positions.length; i += 3) {
  64956. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64957. }
  64958. return shape;
  64959. };
  64960. // returns a shapeUV array from a Vector4 uvs
  64961. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64962. var shapeUV = [];
  64963. if (uvs) {
  64964. for (var i = 0; i < uvs.length; i++)
  64965. shapeUV.push(uvs[i]);
  64966. }
  64967. return shapeUV;
  64968. };
  64969. // adds a new particle object in the particles array
  64970. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64971. if (bInfo === void 0) { bInfo = null; }
  64972. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64973. this.particles.push(sp);
  64974. return sp;
  64975. };
  64976. /**
  64977. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64978. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64979. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64980. * @param nb (positive integer) the number of particles to be created from this model
  64981. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64982. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64983. * @returns the number of shapes in the system
  64984. */
  64985. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64986. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64987. var meshInd = mesh.getIndices();
  64988. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64989. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64990. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64991. var bbInfo;
  64992. if (this._particlesIntersect) {
  64993. bbInfo = mesh.getBoundingInfo();
  64994. }
  64995. var shape = this._posToShape(meshPos);
  64996. var shapeUV = this._uvsToShapeUV(meshUV);
  64997. var posfunc = options ? options.positionFunction : null;
  64998. var vtxfunc = options ? options.vertexFunction : null;
  64999. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  65000. // particles
  65001. var sp;
  65002. var currentCopy;
  65003. var idx = this.nbParticles;
  65004. for (var i = 0; i < nb; i++) {
  65005. var currentPos = this._positions.length;
  65006. var currentInd = this._indices.length;
  65007. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  65008. if (this._updatable) {
  65009. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  65010. sp.position.copyFrom(currentCopy.position);
  65011. sp.rotation.copyFrom(currentCopy.rotation);
  65012. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  65013. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  65014. }
  65015. if (currentCopy.color && sp.color) {
  65016. sp.color.copyFrom(currentCopy.color);
  65017. }
  65018. sp.scaling.copyFrom(currentCopy.scaling);
  65019. sp.uvs.copyFrom(currentCopy.uvs);
  65020. }
  65021. this._index += shape.length;
  65022. idx++;
  65023. }
  65024. this.nbParticles += nb;
  65025. this._shapeCounter++;
  65026. return this._shapeCounter - 1;
  65027. };
  65028. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65029. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65030. this._resetCopy();
  65031. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65032. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65033. }
  65034. if (this._copy.rotationQuaternion) {
  65035. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65036. }
  65037. else {
  65038. this._yaw = this._copy.rotation.y;
  65039. this._pitch = this._copy.rotation.x;
  65040. this._roll = this._copy.rotation.z;
  65041. this._quaternionRotationYPR();
  65042. }
  65043. this._quaternionToRotationMatrix();
  65044. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65045. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65046. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65047. if (this._copy.translateFromPivot) {
  65048. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65049. }
  65050. else {
  65051. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65052. }
  65053. this._shape = particle._model._shape;
  65054. for (var pt = 0; pt < this._shape.length; pt++) {
  65055. this._vertex.x = this._shape[pt].x;
  65056. this._vertex.y = this._shape[pt].y;
  65057. this._vertex.z = this._shape[pt].z;
  65058. if (particle._model._vertexFunction) {
  65059. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65060. }
  65061. this._vertex.x *= this._copy.scaling.x;
  65062. this._vertex.y *= this._copy.scaling.y;
  65063. this._vertex.z *= this._copy.scaling.z;
  65064. this._vertex.x -= this._scaledPivot.x;
  65065. this._vertex.y -= this._scaledPivot.y;
  65066. this._vertex.z -= this._scaledPivot.z;
  65067. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65068. this._rotated.addInPlace(this._pivotBackTranslation);
  65069. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65070. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65071. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65072. }
  65073. particle.position.x = 0.0;
  65074. particle.position.y = 0.0;
  65075. particle.position.z = 0.0;
  65076. particle.rotation.x = 0.0;
  65077. particle.rotation.y = 0.0;
  65078. particle.rotation.z = 0.0;
  65079. particle.rotationQuaternion = null;
  65080. particle.scaling.x = 1.0;
  65081. particle.scaling.y = 1.0;
  65082. particle.scaling.z = 1.0;
  65083. particle.uvs.x = 0.0;
  65084. particle.uvs.y = 0.0;
  65085. particle.uvs.z = 1.0;
  65086. particle.uvs.w = 1.0;
  65087. particle.pivot.x = 0.0;
  65088. particle.pivot.y = 0.0;
  65089. particle.pivot.z = 0.0;
  65090. particle.translateFromPivot = false;
  65091. particle.parentId = null;
  65092. };
  65093. /**
  65094. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65095. * @returns the SPS.
  65096. */
  65097. SolidParticleSystem.prototype.rebuildMesh = function () {
  65098. for (var p = 0; p < this.particles.length; p++) {
  65099. this._rebuildParticle(this.particles[p]);
  65100. }
  65101. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65102. return this;
  65103. };
  65104. /**
  65105. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65106. * This method calls `updateParticle()` for each particle of the SPS.
  65107. * For an animated SPS, it is usually called within the render loop.
  65108. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  65109. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  65110. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  65111. * @returns the SPS.
  65112. */
  65113. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  65114. if (start === void 0) { start = 0; }
  65115. if (end === void 0) { end = this.nbParticles - 1; }
  65116. if (update === void 0) { update = true; }
  65117. if (!this._updatable) {
  65118. return this;
  65119. }
  65120. // custom beforeUpdate
  65121. this.beforeUpdateParticles(start, end, update);
  65122. this._cam_axisX.x = 1.0;
  65123. this._cam_axisX.y = 0.0;
  65124. this._cam_axisX.z = 0.0;
  65125. this._cam_axisY.x = 0.0;
  65126. this._cam_axisY.y = 1.0;
  65127. this._cam_axisY.z = 0.0;
  65128. this._cam_axisZ.x = 0.0;
  65129. this._cam_axisZ.y = 0.0;
  65130. this._cam_axisZ.z = 1.0;
  65131. // cases when the World Matrix is to be computed first
  65132. if (this.billboard || this._depthSort) {
  65133. this.mesh.computeWorldMatrix(true);
  65134. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  65135. }
  65136. // if the particles will always face the camera
  65137. if (this.billboard) {
  65138. // compute the camera position and un-rotate it by the current mesh rotation
  65139. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  65140. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  65141. this._cam_axisZ.normalize();
  65142. // same for camera up vector extracted from the cam view matrix
  65143. var view = this._camera.getViewMatrix(true);
  65144. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  65145. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  65146. this._cam_axisY.normalize();
  65147. this._cam_axisX.normalize();
  65148. }
  65149. // if depthSort, compute the camera global position in the mesh local system
  65150. if (this._depthSort) {
  65151. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  65152. }
  65153. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  65154. var idx = 0; // current position index in the global array positions32
  65155. var index = 0; // position start index in the global array positions32 of the current particle
  65156. var colidx = 0; // current color index in the global array colors32
  65157. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  65158. var uvidx = 0; // current uv index in the global array uvs32
  65159. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  65160. var pt = 0; // current index in the particle model shape
  65161. if (this.mesh.isFacetDataEnabled) {
  65162. this._computeBoundingBox = true;
  65163. }
  65164. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  65165. if (this._computeBoundingBox) {
  65166. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  65167. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  65168. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  65169. }
  65170. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  65171. if (this.mesh._boundingInfo) {
  65172. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  65173. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  65174. }
  65175. }
  65176. }
  65177. // particle loop
  65178. index = this.particles[start]._pos;
  65179. var vpos = (index / 3) | 0;
  65180. colorIndex = vpos * 4;
  65181. uvIndex = vpos * 2;
  65182. for (var p = start; p <= end; p++) {
  65183. this._particle = this.particles[p];
  65184. this._shape = this._particle._model._shape;
  65185. this._shapeUV = this._particle._model._shapeUV;
  65186. // call to custom user function to update the particle properties
  65187. this.updateParticle(this._particle);
  65188. // camera-particle distance for depth sorting
  65189. if (this._depthSort && this._depthSortParticles) {
  65190. var dsp = this.depthSortedParticles[p];
  65191. dsp.ind = this._particle._ind;
  65192. dsp.indicesLength = this._particle._model._indicesLength;
  65193. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  65194. }
  65195. // skip the computations for inactive or already invisible particles
  65196. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  65197. // increment indexes for the next particle
  65198. pt = this._shape.length;
  65199. index += pt * 3;
  65200. colorIndex += pt * 4;
  65201. uvIndex += pt * 2;
  65202. continue;
  65203. }
  65204. if (this._particle.isVisible) {
  65205. this._particle._stillInvisible = false; // un-mark permanent invisibility
  65206. this._particleHasParent = (this._particle.parentId !== null);
  65207. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65208. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65209. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65210. // particle rotation matrix
  65211. if (this.billboard) {
  65212. this._particle.rotation.x = 0.0;
  65213. this._particle.rotation.y = 0.0;
  65214. }
  65215. if (this._computeParticleRotation || this.billboard) {
  65216. if (this._particle.rotationQuaternion) {
  65217. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65218. }
  65219. else {
  65220. this._yaw = this._particle.rotation.y;
  65221. this._pitch = this._particle.rotation.x;
  65222. this._roll = this._particle.rotation.z;
  65223. this._quaternionRotationYPR();
  65224. }
  65225. this._quaternionToRotationMatrix();
  65226. }
  65227. if (this._particleHasParent) {
  65228. this._parent = this.particles[this._particle.parentId];
  65229. 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];
  65230. 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];
  65231. 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];
  65232. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  65233. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  65234. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  65235. if (this._computeParticleRotation || this.billboard) {
  65236. 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];
  65237. 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];
  65238. 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];
  65239. 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];
  65240. 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];
  65241. 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];
  65242. 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];
  65243. 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];
  65244. 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];
  65245. }
  65246. }
  65247. else {
  65248. this._particle._globalPosition.x = this._particle.position.x;
  65249. this._particle._globalPosition.y = this._particle.position.y;
  65250. this._particle._globalPosition.z = this._particle.position.z;
  65251. if (this._computeParticleRotation || this.billboard) {
  65252. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  65253. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  65254. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  65255. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  65256. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  65257. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  65258. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  65259. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  65260. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  65261. }
  65262. }
  65263. if (this._particle.translateFromPivot) {
  65264. this._pivotBackTranslation.x = 0.0;
  65265. this._pivotBackTranslation.y = 0.0;
  65266. this._pivotBackTranslation.z = 0.0;
  65267. }
  65268. else {
  65269. this._pivotBackTranslation.x = this._scaledPivot.x;
  65270. this._pivotBackTranslation.y = this._scaledPivot.y;
  65271. this._pivotBackTranslation.z = this._scaledPivot.z;
  65272. }
  65273. // particle vertex loop
  65274. for (pt = 0; pt < this._shape.length; pt++) {
  65275. idx = index + pt * 3;
  65276. colidx = colorIndex + pt * 4;
  65277. uvidx = uvIndex + pt * 2;
  65278. this._vertex.x = this._shape[pt].x;
  65279. this._vertex.y = this._shape[pt].y;
  65280. this._vertex.z = this._shape[pt].z;
  65281. if (this._computeParticleVertex) {
  65282. this.updateParticleVertex(this._particle, this._vertex, pt);
  65283. }
  65284. // positions
  65285. this._vertex.x *= this._particle.scaling.x;
  65286. this._vertex.y *= this._particle.scaling.y;
  65287. this._vertex.z *= this._particle.scaling.z;
  65288. this._vertex.x -= this._scaledPivot.x;
  65289. this._vertex.y -= this._scaledPivot.y;
  65290. this._vertex.z -= this._scaledPivot.z;
  65291. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65292. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65293. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65294. this._rotated.x += this._pivotBackTranslation.x;
  65295. this._rotated.y += this._pivotBackTranslation.y;
  65296. this._rotated.z += this._pivotBackTranslation.z;
  65297. 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;
  65298. 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;
  65299. 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;
  65300. if (this._computeBoundingBox) {
  65301. if (this._positions32[idx] < this._minimum.x) {
  65302. this._minimum.x = this._positions32[idx];
  65303. }
  65304. if (this._positions32[idx] > this._maximum.x) {
  65305. this._maximum.x = this._positions32[idx];
  65306. }
  65307. if (this._positions32[idx + 1] < this._minimum.y) {
  65308. this._minimum.y = this._positions32[idx + 1];
  65309. }
  65310. if (this._positions32[idx + 1] > this._maximum.y) {
  65311. this._maximum.y = this._positions32[idx + 1];
  65312. }
  65313. if (this._positions32[idx + 2] < this._minimum.z) {
  65314. this._minimum.z = this._positions32[idx + 2];
  65315. }
  65316. if (this._positions32[idx + 2] > this._maximum.z) {
  65317. this._maximum.z = this._positions32[idx + 2];
  65318. }
  65319. }
  65320. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65321. if (!this._computeParticleVertex) {
  65322. this._normal.x = this._fixedNormal32[idx];
  65323. this._normal.y = this._fixedNormal32[idx + 1];
  65324. this._normal.z = this._fixedNormal32[idx + 2];
  65325. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65326. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65327. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65328. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65329. 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;
  65330. 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;
  65331. }
  65332. if (this._computeParticleColor && this._particle.color) {
  65333. this._colors32[colidx] = this._particle.color.r;
  65334. this._colors32[colidx + 1] = this._particle.color.g;
  65335. this._colors32[colidx + 2] = this._particle.color.b;
  65336. this._colors32[colidx + 3] = this._particle.color.a;
  65337. }
  65338. if (this._computeParticleTexture) {
  65339. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65340. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65341. }
  65342. }
  65343. }
  65344. // particle just set invisible : scaled to zero and positioned at the origin
  65345. else {
  65346. this._particle._stillInvisible = true; // mark the particle as invisible
  65347. for (pt = 0; pt < this._shape.length; pt++) {
  65348. idx = index + pt * 3;
  65349. colidx = colorIndex + pt * 4;
  65350. uvidx = uvIndex + pt * 2;
  65351. this._positions32[idx] = 0.0;
  65352. this._positions32[idx + 1] = 0.0;
  65353. this._positions32[idx + 2] = 0.0;
  65354. this._normals32[idx] = 0.0;
  65355. this._normals32[idx + 1] = 0.0;
  65356. this._normals32[idx + 2] = 0.0;
  65357. if (this._computeParticleColor && this._particle.color) {
  65358. this._colors32[colidx] = this._particle.color.r;
  65359. this._colors32[colidx + 1] = this._particle.color.g;
  65360. this._colors32[colidx + 2] = this._particle.color.b;
  65361. this._colors32[colidx + 3] = this._particle.color.a;
  65362. }
  65363. if (this._computeParticleTexture) {
  65364. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65365. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65366. }
  65367. }
  65368. }
  65369. // if the particle intersections must be computed : update the bbInfo
  65370. if (this._particlesIntersect) {
  65371. var bInfo = this._particle._boundingInfo;
  65372. var bBox = bInfo.boundingBox;
  65373. var bSphere = bInfo.boundingSphere;
  65374. if (!this._bSphereOnly) {
  65375. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65376. for (var b = 0; b < bBox.vectors.length; b++) {
  65377. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65378. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65379. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65380. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65381. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65382. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65383. 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;
  65384. 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;
  65385. 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;
  65386. }
  65387. bBox._update(this.mesh._worldMatrix);
  65388. }
  65389. // place and scale the particle bouding sphere in the SPS local system, then update it
  65390. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65391. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65392. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65393. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65394. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65395. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65396. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65397. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65398. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65399. 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));
  65400. bSphere._update(this.mesh._worldMatrix);
  65401. }
  65402. // increment indexes for the next particle
  65403. index = idx + 3;
  65404. colorIndex = colidx + 4;
  65405. uvIndex = uvidx + 2;
  65406. }
  65407. // if the VBO must be updated
  65408. if (update) {
  65409. if (this._computeParticleColor) {
  65410. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65411. }
  65412. if (this._computeParticleTexture) {
  65413. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65414. }
  65415. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65416. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65417. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65418. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65419. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65420. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65421. for (var i = 0; i < this._normals32.length; i++) {
  65422. this._fixedNormal32[i] = this._normals32[i];
  65423. }
  65424. }
  65425. if (!this.mesh.areNormalsFrozen) {
  65426. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65427. }
  65428. }
  65429. if (this._depthSort && this._depthSortParticles) {
  65430. this.depthSortedParticles.sort(this._depthSortFunction);
  65431. var dspl = this.depthSortedParticles.length;
  65432. var sorted = 0;
  65433. var lind = 0;
  65434. var sind = 0;
  65435. var sid = 0;
  65436. for (sorted = 0; sorted < dspl; sorted++) {
  65437. lind = this.depthSortedParticles[sorted].indicesLength;
  65438. sind = this.depthSortedParticles[sorted].ind;
  65439. for (var i = 0; i < lind; i++) {
  65440. this._indices32[sid] = this._indices[sind + i];
  65441. sid++;
  65442. }
  65443. }
  65444. this.mesh.updateIndices(this._indices32);
  65445. }
  65446. }
  65447. if (this._computeBoundingBox) {
  65448. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65449. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65450. }
  65451. this.afterUpdateParticles(start, end, update);
  65452. return this;
  65453. };
  65454. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65455. this._halfroll = this._roll * 0.5;
  65456. this._halfpitch = this._pitch * 0.5;
  65457. this._halfyaw = this._yaw * 0.5;
  65458. this._sinRoll = Math.sin(this._halfroll);
  65459. this._cosRoll = Math.cos(this._halfroll);
  65460. this._sinPitch = Math.sin(this._halfpitch);
  65461. this._cosPitch = Math.cos(this._halfpitch);
  65462. this._sinYaw = Math.sin(this._halfyaw);
  65463. this._cosYaw = Math.cos(this._halfyaw);
  65464. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65465. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65466. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65467. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65468. };
  65469. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65470. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65471. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65472. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65473. this._rotMatrix.m[3] = 0;
  65474. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65475. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65476. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65477. this._rotMatrix.m[7] = 0;
  65478. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65479. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65480. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65481. this._rotMatrix.m[11] = 0;
  65482. this._rotMatrix.m[12] = 0;
  65483. this._rotMatrix.m[13] = 0;
  65484. this._rotMatrix.m[14] = 0;
  65485. this._rotMatrix.m[15] = 1.0;
  65486. };
  65487. /**
  65488. * Disposes the SPS.
  65489. */
  65490. SolidParticleSystem.prototype.dispose = function () {
  65491. this.mesh.dispose();
  65492. this.vars = null;
  65493. // drop references to internal big arrays for the GC
  65494. this._positions = null;
  65495. this._indices = null;
  65496. this._normals = null;
  65497. this._uvs = null;
  65498. this._colors = null;
  65499. this._indices32 = null;
  65500. this._positions32 = null;
  65501. this._normals32 = null;
  65502. this._fixedNormal32 = null;
  65503. this._uvs32 = null;
  65504. this._colors32 = null;
  65505. this.pickedParticles = null;
  65506. };
  65507. /**
  65508. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65509. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65510. * @returns the SPS.
  65511. */
  65512. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65513. if (!this._isVisibilityBoxLocked) {
  65514. this.mesh.refreshBoundingInfo();
  65515. }
  65516. return this;
  65517. };
  65518. /**
  65519. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65520. * @param size the size (float) of the visibility box
  65521. * note : this doesn't lock the SPS mesh bounding box.
  65522. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65523. */
  65524. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65525. var vis = size / 2;
  65526. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65527. };
  65528. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65529. /**
  65530. * Gets whether the SPS as always visible or not
  65531. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65532. */
  65533. get: function () {
  65534. return this._alwaysVisible;
  65535. },
  65536. /**
  65537. * Sets the SPS as always visible or not
  65538. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65539. */
  65540. set: function (val) {
  65541. this._alwaysVisible = val;
  65542. this.mesh.alwaysSelectAsActiveMesh = val;
  65543. },
  65544. enumerable: true,
  65545. configurable: true
  65546. });
  65547. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65548. /**
  65549. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65550. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65551. */
  65552. get: function () {
  65553. return this._isVisibilityBoxLocked;
  65554. },
  65555. /**
  65556. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65557. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65558. */
  65559. set: function (val) {
  65560. this._isVisibilityBoxLocked = val;
  65561. var boundingInfo = this.mesh.getBoundingInfo();
  65562. boundingInfo.isLocked = val;
  65563. },
  65564. enumerable: true,
  65565. configurable: true
  65566. });
  65567. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65568. /**
  65569. * Gets if `setParticles()` computes the particle rotations or not.
  65570. * Default value : true. The SPS is faster when it's set to false.
  65571. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65572. */
  65573. get: function () {
  65574. return this._computeParticleRotation;
  65575. },
  65576. /**
  65577. * Tells to `setParticles()` to compute the particle rotations or not.
  65578. * Default value : true. The SPS is faster when it's set to false.
  65579. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65580. */
  65581. set: function (val) {
  65582. this._computeParticleRotation = val;
  65583. },
  65584. enumerable: true,
  65585. configurable: true
  65586. });
  65587. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65588. /**
  65589. * Gets if `setParticles()` computes the particle colors or not.
  65590. * Default value : true. The SPS is faster when it's set to false.
  65591. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65592. */
  65593. get: function () {
  65594. return this._computeParticleColor;
  65595. },
  65596. /**
  65597. * Tells to `setParticles()` to compute the particle colors or not.
  65598. * Default value : true. The SPS is faster when it's set to false.
  65599. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65600. */
  65601. set: function (val) {
  65602. this._computeParticleColor = val;
  65603. },
  65604. enumerable: true,
  65605. configurable: true
  65606. });
  65607. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65608. /**
  65609. * Gets if `setParticles()` computes the particle textures or not.
  65610. * Default value : true. The SPS is faster when it's set to false.
  65611. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65612. */
  65613. get: function () {
  65614. return this._computeParticleTexture;
  65615. },
  65616. set: function (val) {
  65617. this._computeParticleTexture = val;
  65618. },
  65619. enumerable: true,
  65620. configurable: true
  65621. });
  65622. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65623. /**
  65624. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65625. * Default value : false. The SPS is faster when it's set to false.
  65626. * Note : the particle custom vertex positions aren't stored values.
  65627. */
  65628. get: function () {
  65629. return this._computeParticleVertex;
  65630. },
  65631. /**
  65632. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65633. * Default value : false. The SPS is faster when it's set to false.
  65634. * Note : the particle custom vertex positions aren't stored values.
  65635. */
  65636. set: function (val) {
  65637. this._computeParticleVertex = val;
  65638. },
  65639. enumerable: true,
  65640. configurable: true
  65641. });
  65642. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65643. /**
  65644. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65645. */
  65646. get: function () {
  65647. return this._computeBoundingBox;
  65648. },
  65649. /**
  65650. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65651. */
  65652. set: function (val) {
  65653. this._computeBoundingBox = val;
  65654. },
  65655. enumerable: true,
  65656. configurable: true
  65657. });
  65658. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65659. /**
  65660. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65661. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65662. * Default : `true`
  65663. */
  65664. get: function () {
  65665. return this._depthSortParticles;
  65666. },
  65667. /**
  65668. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65669. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65670. * Default : `true`
  65671. */
  65672. set: function (val) {
  65673. this._depthSortParticles = val;
  65674. },
  65675. enumerable: true,
  65676. configurable: true
  65677. });
  65678. // =======================================================================
  65679. // Particle behavior logic
  65680. // these following methods may be overwritten by the user to fit his needs
  65681. /**
  65682. * This function does nothing. It may be overwritten to set all the particle first values.
  65683. * The SPS doesn't call this function, you may have to call it by your own.
  65684. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65685. */
  65686. SolidParticleSystem.prototype.initParticles = function () {
  65687. };
  65688. /**
  65689. * This function does nothing. It may be overwritten to recycle a particle.
  65690. * The SPS doesn't call this function, you may have to call it by your own.
  65691. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65692. * @param particle The particle to recycle
  65693. * @returns the recycled particle
  65694. */
  65695. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65696. return particle;
  65697. };
  65698. /**
  65699. * Updates a particle : this function should be overwritten by the user.
  65700. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65701. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65702. * @example : just set a particle position or velocity and recycle conditions
  65703. * @param particle The particle to update
  65704. * @returns the updated particle
  65705. */
  65706. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65707. return particle;
  65708. };
  65709. /**
  65710. * Updates a vertex of a particle : it can be overwritten by the user.
  65711. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65712. * @param particle the current particle
  65713. * @param vertex the current index of the current particle
  65714. * @param pt the index of the current vertex in the particle shape
  65715. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65716. * @example : just set a vertex particle position
  65717. * @returns the updated vertex
  65718. */
  65719. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65720. return vertex;
  65721. };
  65722. /**
  65723. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65724. * This does nothing and may be overwritten by the user.
  65725. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65726. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65727. * @param update the boolean update value actually passed to setParticles()
  65728. */
  65729. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65730. };
  65731. /**
  65732. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65733. * This will be passed three parameters.
  65734. * This does nothing and may be overwritten by the user.
  65735. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65736. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65737. * @param update the boolean update value actually passed to setParticles()
  65738. */
  65739. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65740. };
  65741. return SolidParticleSystem;
  65742. }());
  65743. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65744. })(BABYLON || (BABYLON = {}));
  65745. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65746. var BABYLON;
  65747. (function (BABYLON) {
  65748. /**
  65749. * Class containing static functions to help procedurally build meshes
  65750. */
  65751. var MeshBuilder = /** @class */ (function () {
  65752. function MeshBuilder() {
  65753. }
  65754. MeshBuilder.updateSideOrientation = function (orientation) {
  65755. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65756. return BABYLON.Mesh.DOUBLESIDE;
  65757. }
  65758. if (orientation === undefined || orientation === null) {
  65759. return BABYLON.Mesh.FRONTSIDE;
  65760. }
  65761. return orientation;
  65762. };
  65763. /**
  65764. * Creates a box mesh
  65765. * * The parameter `size` sets the size (float) of each box side (default 1)
  65766. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65767. * * 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)
  65768. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65769. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65770. * * 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
  65771. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65772. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65773. * @param name defines the name of the mesh
  65774. * @param options defines the options used to create the mesh
  65775. * @param scene defines the hosting scene
  65776. * @returns the box mesh
  65777. */
  65778. MeshBuilder.CreateBox = function (name, options, scene) {
  65779. if (scene === void 0) { scene = null; }
  65780. var box = new BABYLON.Mesh(name, scene);
  65781. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65782. box._originalBuilderSideOrientation = options.sideOrientation;
  65783. var vertexData = BABYLON.VertexData.CreateBox(options);
  65784. vertexData.applyToMesh(box, options.updatable);
  65785. return box;
  65786. };
  65787. /**
  65788. * Creates a sphere mesh
  65789. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65790. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)
  65791. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65792. * * 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
  65793. * * 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)
  65794. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65795. * * 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
  65796. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65797. * @param name defines the name of the mesh
  65798. * @param options defines the options used to create the mesh
  65799. * @param scene defines the hosting scene
  65800. * @returns the sphere mesh
  65801. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65802. */
  65803. MeshBuilder.CreateSphere = function (name, options, scene) {
  65804. var sphere = new BABYLON.Mesh(name, scene);
  65805. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65806. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65807. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65808. vertexData.applyToMesh(sphere, options.updatable);
  65809. return sphere;
  65810. };
  65811. /**
  65812. * Creates a plane polygonal mesh. By default, this is a disc
  65813. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65814. * * 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
  65815. * * 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
  65816. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65817. * * 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
  65818. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65819. * @param name defines the name of the mesh
  65820. * @param options defines the options used to create the mesh
  65821. * @param scene defines the hosting scene
  65822. * @returns the plane polygonal mesh
  65823. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65824. */
  65825. MeshBuilder.CreateDisc = function (name, options, scene) {
  65826. if (scene === void 0) { scene = null; }
  65827. var disc = new BABYLON.Mesh(name, scene);
  65828. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65829. disc._originalBuilderSideOrientation = options.sideOrientation;
  65830. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65831. vertexData.applyToMesh(disc, options.updatable);
  65832. return disc;
  65833. };
  65834. /**
  65835. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65836. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65837. * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)
  65838. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65839. * * 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
  65840. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65841. * * 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
  65842. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65843. * @param name defines the name of the mesh
  65844. * @param options defines the options used to create the mesh
  65845. * @param scene defines the hosting scene
  65846. * @returns the icosahedron mesh
  65847. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65848. */
  65849. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65850. var sphere = new BABYLON.Mesh(name, scene);
  65851. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65852. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65853. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65854. vertexData.applyToMesh(sphere, options.updatable);
  65855. return sphere;
  65856. };
  65857. ;
  65858. /**
  65859. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65860. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65861. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65862. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65863. * * 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
  65864. * * 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
  65865. * * 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
  65866. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65867. * * 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
  65868. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65869. * * 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
  65870. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65871. * * 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
  65872. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65873. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65874. * @param name defines the name of the mesh
  65875. * @param options defines the options used to create the mesh
  65876. * @param scene defines the hosting scene
  65877. * @returns the ribbon mesh
  65878. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65879. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65880. */
  65881. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65882. if (scene === void 0) { scene = null; }
  65883. var pathArray = options.pathArray;
  65884. var closeArray = options.closeArray;
  65885. var closePath = options.closePath;
  65886. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65887. var instance = options.instance;
  65888. var updatable = options.updatable;
  65889. if (instance) { // existing ribbon instance update
  65890. // positionFunction : ribbon case
  65891. // only pathArray and sideOrientation parameters are taken into account for positions update
  65892. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65893. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65894. var positionFunction = function (positions) {
  65895. var minlg = pathArray[0].length;
  65896. var i = 0;
  65897. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65898. for (var si = 1; si <= ns; si++) {
  65899. for (var p = 0; p < pathArray.length; p++) {
  65900. var path = pathArray[p];
  65901. var l = path.length;
  65902. minlg = (minlg < l) ? minlg : l;
  65903. var j = 0;
  65904. while (j < minlg) {
  65905. positions[i] = path[j].x;
  65906. positions[i + 1] = path[j].y;
  65907. positions[i + 2] = path[j].z;
  65908. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65909. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65910. }
  65911. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65912. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65913. }
  65914. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65915. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65916. }
  65917. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65918. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65919. }
  65920. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65921. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65922. }
  65923. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65924. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65925. }
  65926. j++;
  65927. i += 3;
  65928. }
  65929. if (instance._closePath) {
  65930. positions[i] = path[0].x;
  65931. positions[i + 1] = path[0].y;
  65932. positions[i + 2] = path[0].z;
  65933. i += 3;
  65934. }
  65935. }
  65936. }
  65937. };
  65938. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65939. positionFunction(positions);
  65940. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65941. instance._boundingInfo.update(instance._worldMatrix);
  65942. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65943. if (options.colors) {
  65944. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65945. for (var c = 0; c < options.colors.length; c++) {
  65946. colors[c * 4] = options.colors[c].r;
  65947. colors[c * 4 + 1] = options.colors[c].g;
  65948. colors[c * 4 + 2] = options.colors[c].b;
  65949. colors[c * 4 + 3] = options.colors[c].a;
  65950. }
  65951. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65952. }
  65953. if (options.uvs) {
  65954. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65955. for (var i = 0; i < options.uvs.length; i++) {
  65956. uvs[i * 2] = options.uvs[i].x;
  65957. uvs[i * 2 + 1] = options.uvs[i].y;
  65958. }
  65959. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65960. }
  65961. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65962. var indices = instance.getIndices();
  65963. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65964. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65965. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65966. if (instance._closePath) {
  65967. var indexFirst = 0;
  65968. var indexLast = 0;
  65969. for (var p = 0; p < pathArray.length; p++) {
  65970. indexFirst = instance._idx[p] * 3;
  65971. if (p + 1 < pathArray.length) {
  65972. indexLast = (instance._idx[p + 1] - 1) * 3;
  65973. }
  65974. else {
  65975. indexLast = normals.length - 3;
  65976. }
  65977. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65978. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65979. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65980. normals[indexLast] = normals[indexFirst];
  65981. normals[indexLast + 1] = normals[indexFirst + 1];
  65982. normals[indexLast + 2] = normals[indexFirst + 2];
  65983. }
  65984. }
  65985. if (!(instance.areNormalsFrozen)) {
  65986. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65987. }
  65988. }
  65989. return instance;
  65990. }
  65991. else { // new ribbon creation
  65992. var ribbon = new BABYLON.Mesh(name, scene);
  65993. ribbon._originalBuilderSideOrientation = sideOrientation;
  65994. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65995. if (closePath) {
  65996. ribbon._idx = vertexData._idx;
  65997. }
  65998. ribbon._closePath = closePath;
  65999. ribbon._closeArray = closeArray;
  66000. vertexData.applyToMesh(ribbon, updatable);
  66001. return ribbon;
  66002. }
  66003. };
  66004. /**
  66005. * Creates a cylinder or a cone mesh
  66006. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  66007. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  66008. * * 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.
  66009. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  66010. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  66011. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  66012. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  66013. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  66014. * * 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).
  66015. * * 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
  66016. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  66017. * * 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
  66018. * * 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.
  66019. * * If `enclose` is false, a ring surface is one element.
  66020. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  66021. * * 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
  66022. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66023. * * 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
  66024. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66025. * @param name defines the name of the mesh
  66026. * @param options defines the options used to create the mesh
  66027. * @param scene defines the hosting scene
  66028. * @returns the cylinder mesh
  66029. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66030. */
  66031. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66032. var cylinder = new BABYLON.Mesh(name, scene);
  66033. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66034. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66035. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66036. vertexData.applyToMesh(cylinder, options.updatable);
  66037. return cylinder;
  66038. };
  66039. /**
  66040. * Creates a torus mesh
  66041. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66042. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66043. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66044. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66045. * * 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
  66046. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66047. * @param name defines the name of the mesh
  66048. * @param options defines the options used to create the mesh
  66049. * @param scene defines the hosting scene
  66050. * @returns the torus mesh
  66051. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66052. */
  66053. MeshBuilder.CreateTorus = function (name, options, scene) {
  66054. var torus = new BABYLON.Mesh(name, scene);
  66055. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66056. torus._originalBuilderSideOrientation = options.sideOrientation;
  66057. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66058. vertexData.applyToMesh(torus, options.updatable);
  66059. return torus;
  66060. };
  66061. /**
  66062. * Creates a torus knot mesh
  66063. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66064. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66065. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66066. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66067. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66068. * * 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
  66069. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66070. * @param name defines the name of the mesh
  66071. * @param options defines the options used to create the mesh
  66072. * @param scene defines the hosting scene
  66073. * @returns the torus knot mesh
  66074. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66075. */
  66076. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66077. var torusKnot = new BABYLON.Mesh(name, scene);
  66078. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66079. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66080. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66081. vertexData.applyToMesh(torusKnot, options.updatable);
  66082. return torusKnot;
  66083. };
  66084. /**
  66085. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66086. * * 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
  66087. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66088. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66089. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66090. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66091. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66092. * * 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
  66093. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66094. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66095. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66096. * @param name defines the name of the new line system
  66097. * @param options defines the options used to create the line system
  66098. * @param scene defines the hosting scene
  66099. * @returns a new line system mesh
  66100. */
  66101. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66102. var instance = options.instance;
  66103. var lines = options.lines;
  66104. var colors = options.colors;
  66105. if (instance) { // lines update
  66106. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66107. var vertexColor;
  66108. var lineColors;
  66109. if (colors) {
  66110. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66111. }
  66112. var i = 0;
  66113. var c = 0;
  66114. for (var l = 0; l < lines.length; l++) {
  66115. var points = lines[l];
  66116. for (var p = 0; p < points.length; p++) {
  66117. positions[i] = points[p].x;
  66118. positions[i + 1] = points[p].y;
  66119. positions[i + 2] = points[p].z;
  66120. if (colors && vertexColor) {
  66121. lineColors = colors[l];
  66122. vertexColor[c] = lineColors[p].r;
  66123. vertexColor[c + 1] = lineColors[p].g;
  66124. vertexColor[c + 2] = lineColors[p].b;
  66125. vertexColor[c + 3] = lineColors[p].a;
  66126. c += 4;
  66127. }
  66128. i += 3;
  66129. }
  66130. }
  66131. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66132. if (colors && vertexColor) {
  66133. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  66134. }
  66135. return instance;
  66136. }
  66137. // line system creation
  66138. var useVertexColor = (colors) ? true : false;
  66139. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  66140. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  66141. vertexData.applyToMesh(lineSystem, options.updatable);
  66142. return lineSystem;
  66143. };
  66144. /**
  66145. * Creates a line mesh
  66146. * 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
  66147. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66148. * * The parameter `points` is an array successive Vector3
  66149. * * 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
  66150. * * The optional parameter `colors` is an array of successive Color4, one per line point
  66151. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  66152. * * When updating an instance, remember that only point positions can change, not the number of points
  66153. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66154. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  66155. * @param name defines the name of the new line system
  66156. * @param options defines the options used to create the line system
  66157. * @param scene defines the hosting scene
  66158. * @returns a new line mesh
  66159. */
  66160. MeshBuilder.CreateLines = function (name, options, scene) {
  66161. if (scene === void 0) { scene = null; }
  66162. var colors = (options.colors) ? [options.colors] : null;
  66163. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  66164. return lines;
  66165. };
  66166. /**
  66167. * Creates a dashed line mesh
  66168. * * 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
  66169. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66170. * * The parameter `points` is an array successive Vector3
  66171. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  66172. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  66173. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  66174. * * 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
  66175. * * When updating an instance, remember that only point positions can change, not the number of points
  66176. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66177. * @param name defines the name of the mesh
  66178. * @param options defines the options used to create the mesh
  66179. * @param scene defines the hosting scene
  66180. * @returns the dashed line mesh
  66181. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  66182. */
  66183. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  66184. if (scene === void 0) { scene = null; }
  66185. var points = options.points;
  66186. var instance = options.instance;
  66187. var gapSize = options.gapSize || 1;
  66188. var dashSize = options.dashSize || 3;
  66189. if (instance) { // dashed lines update
  66190. var positionFunction = function (positions) {
  66191. var curvect = BABYLON.Vector3.Zero();
  66192. var nbSeg = positions.length / 6;
  66193. var lg = 0;
  66194. var nb = 0;
  66195. var shft = 0;
  66196. var dashshft = 0;
  66197. var curshft = 0;
  66198. var p = 0;
  66199. var i = 0;
  66200. var j = 0;
  66201. for (i = 0; i < points.length - 1; i++) {
  66202. points[i + 1].subtractToRef(points[i], curvect);
  66203. lg += curvect.length();
  66204. }
  66205. shft = lg / nbSeg;
  66206. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  66207. for (i = 0; i < points.length - 1; i++) {
  66208. points[i + 1].subtractToRef(points[i], curvect);
  66209. nb = Math.floor(curvect.length() / shft);
  66210. curvect.normalize();
  66211. j = 0;
  66212. while (j < nb && p < positions.length) {
  66213. curshft = shft * j;
  66214. positions[p] = points[i].x + curshft * curvect.x;
  66215. positions[p + 1] = points[i].y + curshft * curvect.y;
  66216. positions[p + 2] = points[i].z + curshft * curvect.z;
  66217. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  66218. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  66219. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  66220. p += 6;
  66221. j++;
  66222. }
  66223. }
  66224. while (p < positions.length) {
  66225. positions[p] = points[i].x;
  66226. positions[p + 1] = points[i].y;
  66227. positions[p + 2] = points[i].z;
  66228. p += 3;
  66229. }
  66230. };
  66231. instance.updateMeshPositions(positionFunction, false);
  66232. return instance;
  66233. }
  66234. // dashed lines creation
  66235. var dashedLines = new BABYLON.LinesMesh(name, scene);
  66236. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  66237. vertexData.applyToMesh(dashedLines, options.updatable);
  66238. dashedLines.dashSize = dashSize;
  66239. dashedLines.gapSize = gapSize;
  66240. return dashedLines;
  66241. };
  66242. /**
  66243. * 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.
  66244. * * 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.
  66245. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66246. * * 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.
  66247. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  66248. * * 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
  66249. * * 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
  66250. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  66251. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66252. * * 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
  66253. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  66254. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66255. * @param name defines the name of the mesh
  66256. * @param options defines the options used to create the mesh
  66257. * @param scene defines the hosting scene
  66258. * @returns the extruded shape mesh
  66259. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66260. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66261. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66262. */
  66263. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  66264. if (scene === void 0) { scene = null; }
  66265. var path = options.path;
  66266. var shape = options.shape;
  66267. var scale = options.scale || 1;
  66268. var rotation = options.rotation || 0;
  66269. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66270. var updatable = options.updatable;
  66271. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66272. var instance = options.instance || null;
  66273. var invertUV = options.invertUV || false;
  66274. 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);
  66275. };
  66276. /**
  66277. * Creates an custom extruded shape mesh.
  66278. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  66279. * * 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.
  66280. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66281. * * 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
  66282. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  66283. * * 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
  66284. * * It must returns a float value that will be the scale value applied to the shape on each path point
  66285. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  66286. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  66287. * * 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
  66288. * * 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
  66289. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  66290. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66291. * * 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
  66292. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66293. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66294. * @param name defines the name of the mesh
  66295. * @param options defines the options used to create the mesh
  66296. * @param scene defines the hosting scene
  66297. * @returns the custom extruded shape mesh
  66298. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  66299. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66300. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66301. */
  66302. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  66303. var path = options.path;
  66304. var shape = options.shape;
  66305. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66306. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66307. var ribbonCloseArray = options.ribbonCloseArray || false;
  66308. var ribbonClosePath = options.ribbonClosePath || false;
  66309. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66310. var updatable = options.updatable;
  66311. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66312. var instance = options.instance;
  66313. var invertUV = options.invertUV || false;
  66314. 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);
  66315. };
  66316. /**
  66317. * Creates lathe mesh.
  66318. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66319. * * 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
  66320. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66321. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66322. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66323. * * 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
  66324. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66325. * * 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
  66326. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66327. * * 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
  66328. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66329. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66330. * @param name defines the name of the mesh
  66331. * @param options defines the options used to create the mesh
  66332. * @param scene defines the hosting scene
  66333. * @returns the lathe mesh
  66334. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66335. */
  66336. MeshBuilder.CreateLathe = function (name, options, scene) {
  66337. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66338. var closed = (options.closed === undefined) ? true : options.closed;
  66339. var shape = options.shape;
  66340. var radius = options.radius || 1;
  66341. var tessellation = options.tessellation || 64;
  66342. var clip = options.clip || 0;
  66343. var updatable = options.updatable;
  66344. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66345. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66346. var pi2 = Math.PI * 2;
  66347. var paths = new Array();
  66348. var invertUV = options.invertUV || false;
  66349. var i = 0;
  66350. var p = 0;
  66351. var step = pi2 / tessellation * arc;
  66352. var rotated;
  66353. var path = new Array();
  66354. for (i = 0; i <= tessellation - clip; i++) {
  66355. var path = [];
  66356. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66357. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66358. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66359. }
  66360. for (p = 0; p < shape.length; p++) {
  66361. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66362. path.push(rotated);
  66363. }
  66364. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66365. 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));
  66366. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66367. }
  66368. paths.push(path);
  66369. }
  66370. // lathe ribbon
  66371. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66372. return lathe;
  66373. };
  66374. /**
  66375. * Creates a plane mesh
  66376. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66377. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66378. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66379. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66380. * * 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
  66381. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66382. * @param name defines the name of the mesh
  66383. * @param options defines the options used to create the mesh
  66384. * @param scene defines the hosting scene
  66385. * @returns the plane mesh
  66386. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66387. */
  66388. MeshBuilder.CreatePlane = function (name, options, scene) {
  66389. var plane = new BABYLON.Mesh(name, scene);
  66390. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66391. plane._originalBuilderSideOrientation = options.sideOrientation;
  66392. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66393. vertexData.applyToMesh(plane, options.updatable);
  66394. if (options.sourcePlane) {
  66395. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66396. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66397. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66398. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66399. plane.rotate(vectorProduct, product);
  66400. }
  66401. }
  66402. return plane;
  66403. };
  66404. /**
  66405. * Creates a ground mesh
  66406. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66407. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66408. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66409. * @param name defines the name of the mesh
  66410. * @param options defines the options used to create the mesh
  66411. * @param scene defines the hosting scene
  66412. * @returns the ground mesh
  66413. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66414. */
  66415. MeshBuilder.CreateGround = function (name, options, scene) {
  66416. var ground = new BABYLON.GroundMesh(name, scene);
  66417. ground._setReady(false);
  66418. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66419. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66420. ground._width = options.width || 1;
  66421. ground._height = options.height || 1;
  66422. ground._maxX = ground._width / 2;
  66423. ground._maxZ = ground._height / 2;
  66424. ground._minX = -ground._maxX;
  66425. ground._minZ = -ground._maxZ;
  66426. var vertexData = BABYLON.VertexData.CreateGround(options);
  66427. vertexData.applyToMesh(ground, options.updatable);
  66428. ground._setReady(true);
  66429. return ground;
  66430. };
  66431. /**
  66432. * Creates a tiled ground mesh
  66433. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66434. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66435. * * 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
  66436. * * 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
  66437. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66438. * @param name defines the name of the mesh
  66439. * @param options defines the options used to create the mesh
  66440. * @param scene defines the hosting scene
  66441. * @returns the tiled ground mesh
  66442. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66443. */
  66444. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66445. var tiledGround = new BABYLON.Mesh(name, scene);
  66446. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66447. vertexData.applyToMesh(tiledGround, options.updatable);
  66448. return tiledGround;
  66449. };
  66450. /**
  66451. * Creates a ground mesh from a height map
  66452. * * The parameter `url` sets the URL of the height map image resource.
  66453. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66454. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66455. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66456. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66457. * * 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.
  66458. * * 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).
  66459. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66460. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66461. * @param name defines the name of the mesh
  66462. * @param url defines the url to the height map
  66463. * @param options defines the options used to create the mesh
  66464. * @param scene defines the hosting scene
  66465. * @returns the ground mesh
  66466. * @see http://doc.babylonjs.com/babylon101/height_map
  66467. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66468. */
  66469. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66470. var width = options.width || 10.0;
  66471. var height = options.height || 10.0;
  66472. var subdivisions = options.subdivisions || 1 | 0;
  66473. var minHeight = options.minHeight || 0.0;
  66474. var maxHeight = options.maxHeight || 1.0;
  66475. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66476. var alphaFilter = options.alphaFilter || 0.0;
  66477. var updatable = options.updatable;
  66478. var onReady = options.onReady;
  66479. var ground = new BABYLON.GroundMesh(name, scene);
  66480. ground._subdivisionsX = subdivisions;
  66481. ground._subdivisionsY = subdivisions;
  66482. ground._width = width;
  66483. ground._height = height;
  66484. ground._maxX = ground._width / 2.0;
  66485. ground._maxZ = ground._height / 2.0;
  66486. ground._minX = -ground._maxX;
  66487. ground._minZ = -ground._maxZ;
  66488. ground._setReady(false);
  66489. var onload = function (img) {
  66490. // Getting height map data
  66491. var canvas = document.createElement("canvas");
  66492. var context = canvas.getContext("2d");
  66493. if (!context) {
  66494. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66495. }
  66496. if (scene.isDisposed) {
  66497. return;
  66498. }
  66499. var bufferWidth = img.width;
  66500. var bufferHeight = img.height;
  66501. canvas.width = bufferWidth;
  66502. canvas.height = bufferHeight;
  66503. context.drawImage(img, 0, 0);
  66504. // Create VertexData from map data
  66505. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66506. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66507. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66508. width: width, height: height,
  66509. subdivisions: subdivisions,
  66510. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66511. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66512. alphaFilter: alphaFilter
  66513. });
  66514. vertexData.applyToMesh(ground, updatable);
  66515. //execute ready callback, if set
  66516. if (onReady) {
  66517. onReady(ground);
  66518. }
  66519. ground._setReady(true);
  66520. };
  66521. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66522. return ground;
  66523. };
  66524. /**
  66525. * Creates a polygon mesh
  66526. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66527. * * 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
  66528. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66529. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66530. * * 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)
  66531. * * Remember you can only change the shape positions, not their number when updating a polygon
  66532. * @param name defines the name of the mesh
  66533. * @param options defines the options used to create the mesh
  66534. * @param scene defines the hosting scene
  66535. * @returns the polygon mesh
  66536. */
  66537. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66538. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66539. var shape = options.shape;
  66540. var holes = options.holes || [];
  66541. var depth = options.depth || 0;
  66542. var contours = [];
  66543. var hole = [];
  66544. for (var i = 0; i < shape.length; i++) {
  66545. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66546. }
  66547. var epsilon = 0.00000001;
  66548. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66549. contours.pop();
  66550. }
  66551. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66552. for (var hNb = 0; hNb < holes.length; hNb++) {
  66553. hole = [];
  66554. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66555. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66556. }
  66557. polygonTriangulation.addHole(hole);
  66558. }
  66559. var polygon = polygonTriangulation.build(options.updatable, depth);
  66560. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66561. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66562. vertexData.applyToMesh(polygon, options.updatable);
  66563. return polygon;
  66564. };
  66565. ;
  66566. /**
  66567. * Creates an extruded polygon mesh, with depth in the Y direction.
  66568. * * 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)
  66569. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66570. * @param name defines the name of the mesh
  66571. * @param options defines the options used to create the mesh
  66572. * @param scene defines the hosting scene
  66573. * @returns the polygon mesh
  66574. */
  66575. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66576. return MeshBuilder.CreatePolygon(name, options, scene);
  66577. };
  66578. ;
  66579. /**
  66580. * Creates a tube mesh.
  66581. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66582. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66583. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66584. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66585. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66586. * * 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)
  66587. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66588. * * 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
  66589. * * 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
  66590. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66591. * * 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
  66592. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66593. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66594. * @param name defines the name of the mesh
  66595. * @param options defines the options used to create the mesh
  66596. * @param scene defines the hosting scene
  66597. * @returns the tube mesh
  66598. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66599. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66600. */
  66601. MeshBuilder.CreateTube = function (name, options, scene) {
  66602. var path = options.path;
  66603. var instance = options.instance;
  66604. var radius = 1.0;
  66605. if (instance) {
  66606. radius = instance.radius;
  66607. }
  66608. if (options.radius !== undefined) {
  66609. radius = options.radius;
  66610. }
  66611. ;
  66612. var tessellation = options.tessellation || 64 | 0;
  66613. var radiusFunction = options.radiusFunction || null;
  66614. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66615. var invertUV = options.invertUV || false;
  66616. var updatable = options.updatable;
  66617. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66618. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66619. // tube geometry
  66620. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66621. var tangents = path3D.getTangents();
  66622. var normals = path3D.getNormals();
  66623. var distances = path3D.getDistances();
  66624. var pi2 = Math.PI * 2;
  66625. var step = pi2 / tessellation * arc;
  66626. var returnRadius = function () { return radius; };
  66627. var radiusFunctionFinal = radiusFunction || returnRadius;
  66628. var circlePath;
  66629. var rad;
  66630. var normal;
  66631. var rotated;
  66632. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66633. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66634. for (var i = 0; i < path.length; i++) {
  66635. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66636. circlePath = Array(); // current circle array
  66637. normal = normals[i]; // current normal
  66638. for (var t = 0; t < tessellation; t++) {
  66639. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66640. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66641. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66642. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66643. circlePath[t] = rotated;
  66644. }
  66645. circlePaths[index] = circlePath;
  66646. index++;
  66647. }
  66648. // cap
  66649. var capPath = function (nbPoints, pathIndex) {
  66650. var pointCap = Array();
  66651. for (var i = 0; i < nbPoints; i++) {
  66652. pointCap.push(path[pathIndex]);
  66653. }
  66654. return pointCap;
  66655. };
  66656. switch (cap) {
  66657. case BABYLON.Mesh.NO_CAP:
  66658. break;
  66659. case BABYLON.Mesh.CAP_START:
  66660. circlePaths[0] = capPath(tessellation, 0);
  66661. circlePaths[1] = circlePaths[2].slice(0);
  66662. break;
  66663. case BABYLON.Mesh.CAP_END:
  66664. circlePaths[index] = circlePaths[index - 1].slice(0);
  66665. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66666. break;
  66667. case BABYLON.Mesh.CAP_ALL:
  66668. circlePaths[0] = capPath(tessellation, 0);
  66669. circlePaths[1] = circlePaths[2].slice(0);
  66670. circlePaths[index] = circlePaths[index - 1].slice(0);
  66671. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66672. break;
  66673. default:
  66674. break;
  66675. }
  66676. return circlePaths;
  66677. };
  66678. var path3D;
  66679. var pathArray;
  66680. if (instance) { // tube update
  66681. var arc = options.arc || instance.arc;
  66682. path3D = (instance.path3D).update(path);
  66683. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66684. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66685. instance.path3D = path3D;
  66686. instance.pathArray = pathArray;
  66687. instance.arc = arc;
  66688. instance.radius = radius;
  66689. return instance;
  66690. }
  66691. // tube creation
  66692. path3D = new BABYLON.Path3D(path);
  66693. var newPathArray = new Array();
  66694. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66695. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66696. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66697. tube.pathArray = pathArray;
  66698. tube.path3D = path3D;
  66699. tube.tessellation = tessellation;
  66700. tube.cap = cap;
  66701. tube.arc = options.arc;
  66702. tube.radius = radius;
  66703. return tube;
  66704. };
  66705. /**
  66706. * Creates a polyhedron mesh
  66707. * * 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
  66708. * * The parameter `size` (positive float, default 1) sets the polygon size
  66709. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66710. * * 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`
  66711. * * 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
  66712. * * 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)`)
  66713. * * 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
  66714. * * 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
  66715. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66716. * * 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
  66717. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66718. * @param name defines the name of the mesh
  66719. * @param options defines the options used to create the mesh
  66720. * @param scene defines the hosting scene
  66721. * @returns the polyhedron mesh
  66722. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66723. */
  66724. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66725. var polyhedron = new BABYLON.Mesh(name, scene);
  66726. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66727. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66728. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66729. vertexData.applyToMesh(polyhedron, options.updatable);
  66730. return polyhedron;
  66731. };
  66732. /**
  66733. * Creates a decal mesh.
  66734. * 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
  66735. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66736. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66737. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66738. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66739. * @param name defines the name of the mesh
  66740. * @param sourceMesh defines the mesh where the decal must be applied
  66741. * @param options defines the options used to create the mesh
  66742. * @param scene defines the hosting scene
  66743. * @returns the decal mesh
  66744. * @see http://doc.babylonjs.com/how_to/decals
  66745. */
  66746. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66747. var indices = sourceMesh.getIndices();
  66748. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66749. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66750. var position = options.position || BABYLON.Vector3.Zero();
  66751. var normal = options.normal || BABYLON.Vector3.Up();
  66752. var size = options.size || BABYLON.Vector3.One();
  66753. var angle = options.angle || 0;
  66754. // Getting correct rotation
  66755. if (!normal) {
  66756. var target = new BABYLON.Vector3(0, 0, 1);
  66757. var camera = sourceMesh.getScene().activeCamera;
  66758. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66759. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66760. }
  66761. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66762. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66763. var pitch = Math.atan2(normal.y, len);
  66764. // Matrix
  66765. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66766. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66767. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66768. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66769. var vertexData = new BABYLON.VertexData();
  66770. vertexData.indices = [];
  66771. vertexData.positions = [];
  66772. vertexData.normals = [];
  66773. vertexData.uvs = [];
  66774. var currentVertexDataIndex = 0;
  66775. var extractDecalVector3 = function (indexId) {
  66776. var result = new BABYLON.PositionNormalVertex();
  66777. if (!indices || !positions || !normals) {
  66778. return result;
  66779. }
  66780. var vertexId = indices[indexId];
  66781. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66782. // Send vector to decal local world
  66783. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66784. // Get normal
  66785. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66786. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66787. return result;
  66788. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66789. var clip = function (vertices, axis) {
  66790. if (vertices.length === 0) {
  66791. return vertices;
  66792. }
  66793. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66794. var clipVertices = function (v0, v1) {
  66795. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66796. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66797. };
  66798. var result = new Array();
  66799. for (var index = 0; index < vertices.length; index += 3) {
  66800. var v1Out;
  66801. var v2Out;
  66802. var v3Out;
  66803. var total = 0;
  66804. var nV1 = null;
  66805. var nV2 = null;
  66806. var nV3 = null;
  66807. var nV4 = null;
  66808. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66809. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66810. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66811. v1Out = d1 > 0;
  66812. v2Out = d2 > 0;
  66813. v3Out = d3 > 0;
  66814. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66815. switch (total) {
  66816. case 0:
  66817. result.push(vertices[index]);
  66818. result.push(vertices[index + 1]);
  66819. result.push(vertices[index + 2]);
  66820. break;
  66821. case 1:
  66822. if (v1Out) {
  66823. nV1 = vertices[index + 1];
  66824. nV2 = vertices[index + 2];
  66825. nV3 = clipVertices(vertices[index], nV1);
  66826. nV4 = clipVertices(vertices[index], nV2);
  66827. }
  66828. if (v2Out) {
  66829. nV1 = vertices[index];
  66830. nV2 = vertices[index + 2];
  66831. nV3 = clipVertices(vertices[index + 1], nV1);
  66832. nV4 = clipVertices(vertices[index + 1], nV2);
  66833. result.push(nV3);
  66834. result.push(nV2.clone());
  66835. result.push(nV1.clone());
  66836. result.push(nV2.clone());
  66837. result.push(nV3.clone());
  66838. result.push(nV4);
  66839. break;
  66840. }
  66841. if (v3Out) {
  66842. nV1 = vertices[index];
  66843. nV2 = vertices[index + 1];
  66844. nV3 = clipVertices(vertices[index + 2], nV1);
  66845. nV4 = clipVertices(vertices[index + 2], nV2);
  66846. }
  66847. if (nV1 && nV2 && nV3 && nV4) {
  66848. result.push(nV1.clone());
  66849. result.push(nV2.clone());
  66850. result.push(nV3);
  66851. result.push(nV4);
  66852. result.push(nV3.clone());
  66853. result.push(nV2.clone());
  66854. }
  66855. break;
  66856. case 2:
  66857. if (!v1Out) {
  66858. nV1 = vertices[index].clone();
  66859. nV2 = clipVertices(nV1, vertices[index + 1]);
  66860. nV3 = clipVertices(nV1, vertices[index + 2]);
  66861. result.push(nV1);
  66862. result.push(nV2);
  66863. result.push(nV3);
  66864. }
  66865. if (!v2Out) {
  66866. nV1 = vertices[index + 1].clone();
  66867. nV2 = clipVertices(nV1, vertices[index + 2]);
  66868. nV3 = clipVertices(nV1, vertices[index]);
  66869. result.push(nV1);
  66870. result.push(nV2);
  66871. result.push(nV3);
  66872. }
  66873. if (!v3Out) {
  66874. nV1 = vertices[index + 2].clone();
  66875. nV2 = clipVertices(nV1, vertices[index]);
  66876. nV3 = clipVertices(nV1, vertices[index + 1]);
  66877. result.push(nV1);
  66878. result.push(nV2);
  66879. result.push(nV3);
  66880. }
  66881. break;
  66882. case 3:
  66883. break;
  66884. }
  66885. }
  66886. return result;
  66887. };
  66888. for (var index = 0; index < indices.length; index += 3) {
  66889. var faceVertices = new Array();
  66890. faceVertices.push(extractDecalVector3(index));
  66891. faceVertices.push(extractDecalVector3(index + 1));
  66892. faceVertices.push(extractDecalVector3(index + 2));
  66893. // Clip
  66894. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66895. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66896. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66897. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66898. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66899. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66900. if (faceVertices.length === 0) {
  66901. continue;
  66902. }
  66903. // Add UVs and get back to world
  66904. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66905. var vertex = faceVertices[vIndex];
  66906. //TODO check for Int32Array | Uint32Array | Uint16Array
  66907. vertexData.indices.push(currentVertexDataIndex);
  66908. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66909. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66910. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66911. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66912. currentVertexDataIndex++;
  66913. }
  66914. }
  66915. // Return mesh
  66916. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66917. vertexData.applyToMesh(decal);
  66918. decal.position = position.clone();
  66919. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66920. return decal;
  66921. };
  66922. // Privates
  66923. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66924. // extrusion geometry
  66925. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66926. var tangents = path3D.getTangents();
  66927. var normals = path3D.getNormals();
  66928. var binormals = path3D.getBinormals();
  66929. var distances = path3D.getDistances();
  66930. var angle = 0;
  66931. var returnScale = function () { return scale !== null ? scale : 1; };
  66932. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66933. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66934. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66935. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66936. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66937. for (var i = 0; i < curve.length; i++) {
  66938. var shapePath = new Array();
  66939. var angleStep = rotate(i, distances[i]);
  66940. var scaleRatio = scl(i, distances[i]);
  66941. for (var p = 0; p < shape.length; p++) {
  66942. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66943. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66944. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66945. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66946. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66947. shapePath[p] = rotated;
  66948. }
  66949. shapePaths[index] = shapePath;
  66950. angle += angleStep;
  66951. index++;
  66952. }
  66953. // cap
  66954. var capPath = function (shapePath) {
  66955. var pointCap = Array();
  66956. var barycenter = BABYLON.Vector3.Zero();
  66957. var i;
  66958. for (i = 0; i < shapePath.length; i++) {
  66959. barycenter.addInPlace(shapePath[i]);
  66960. }
  66961. barycenter.scaleInPlace(1.0 / shapePath.length);
  66962. for (i = 0; i < shapePath.length; i++) {
  66963. pointCap.push(barycenter);
  66964. }
  66965. return pointCap;
  66966. };
  66967. switch (cap) {
  66968. case BABYLON.Mesh.NO_CAP:
  66969. break;
  66970. case BABYLON.Mesh.CAP_START:
  66971. shapePaths[0] = capPath(shapePaths[2]);
  66972. shapePaths[1] = shapePaths[2];
  66973. break;
  66974. case BABYLON.Mesh.CAP_END:
  66975. shapePaths[index] = shapePaths[index - 1];
  66976. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66977. break;
  66978. case BABYLON.Mesh.CAP_ALL:
  66979. shapePaths[0] = capPath(shapePaths[2]);
  66980. shapePaths[1] = shapePaths[2];
  66981. shapePaths[index] = shapePaths[index - 1];
  66982. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66983. break;
  66984. default:
  66985. break;
  66986. }
  66987. return shapePaths;
  66988. };
  66989. var path3D;
  66990. var pathArray;
  66991. if (instance) { // instance update
  66992. path3D = (instance.path3D).update(curve);
  66993. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66994. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66995. return instance;
  66996. }
  66997. // extruded shape creation
  66998. path3D = new BABYLON.Path3D(curve);
  66999. var newShapePaths = new Array();
  67000. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67001. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  67002. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  67003. extrudedGeneric.pathArray = pathArray;
  67004. extrudedGeneric.path3D = path3D;
  67005. extrudedGeneric.cap = cap;
  67006. return extrudedGeneric;
  67007. };
  67008. return MeshBuilder;
  67009. }());
  67010. BABYLON.MeshBuilder = MeshBuilder;
  67011. })(BABYLON || (BABYLON = {}));
  67012. //# sourceMappingURL=babylon.meshBuilder.js.map
  67013. var BABYLON;
  67014. (function (BABYLON) {
  67015. /**
  67016. * Draco compression (https://google.github.io/draco/)
  67017. *
  67018. * This class wraps the Draco module.
  67019. *
  67020. * **Encoder**
  67021. *
  67022. * The encoder is not currently implemented.
  67023. *
  67024. * **Decoder**
  67025. *
  67026. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  67027. *
  67028. * To update the configuration, use the following code:
  67029. * ```javascript
  67030. * BABYLON.DracoCompression.Configuration = {
  67031. * decoder: {
  67032. * wasmUrl: "<url to the WebAssembly library>",
  67033. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67034. * fallbackUrl: "<url to the fallback JavaScript library>",
  67035. * }
  67036. * };
  67037. * ```
  67038. *
  67039. * 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.
  67040. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67041. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67042. *
  67043. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67044. * ```javascript
  67045. * var dracoCompression = new BABYLON.DracoCompression();
  67046. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67047. * [BABYLON.VertexBuffer.PositionKind]: 0
  67048. * });
  67049. * ```
  67050. *
  67051. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67052. */
  67053. var DracoCompression = /** @class */ (function () {
  67054. /**
  67055. * Constructor
  67056. */
  67057. function DracoCompression() {
  67058. }
  67059. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67060. /**
  67061. * Returns true if the decoder is available.
  67062. */
  67063. get: function () {
  67064. if (typeof DracoDecoderModule !== "undefined") {
  67065. return true;
  67066. }
  67067. var decoder = DracoCompression.Configuration.decoder;
  67068. if (decoder) {
  67069. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67070. return true;
  67071. }
  67072. if (decoder.fallbackUrl) {
  67073. return true;
  67074. }
  67075. }
  67076. return false;
  67077. },
  67078. enumerable: true,
  67079. configurable: true
  67080. });
  67081. /**
  67082. * Stop all async operations and release resources.
  67083. */
  67084. DracoCompression.prototype.dispose = function () {
  67085. };
  67086. /**
  67087. * Decode Draco compressed mesh data to vertex data.
  67088. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67089. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67090. * @returns A promise that resolves with the decoded vertex data
  67091. */
  67092. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67093. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67094. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67095. var module = wrappedModule.module;
  67096. var vertexData = new BABYLON.VertexData();
  67097. var buffer = new module.DecoderBuffer();
  67098. buffer.Init(dataView, dataView.byteLength);
  67099. var decoder = new module.Decoder();
  67100. var geometry;
  67101. var status;
  67102. try {
  67103. var type = decoder.GetEncodedGeometryType(buffer);
  67104. switch (type) {
  67105. case module.TRIANGULAR_MESH:
  67106. geometry = new module.Mesh();
  67107. status = decoder.DecodeBufferToMesh(buffer, geometry);
  67108. break;
  67109. case module.POINT_CLOUD:
  67110. geometry = new module.PointCloud();
  67111. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  67112. break;
  67113. default:
  67114. throw new Error("Invalid geometry type " + type);
  67115. }
  67116. if (!status.ok() || !geometry.ptr) {
  67117. throw new Error(status.error_msg());
  67118. }
  67119. var numPoints = geometry.num_points();
  67120. if (type === module.TRIANGULAR_MESH) {
  67121. var numFaces = geometry.num_faces();
  67122. var faceIndices = new module.DracoInt32Array();
  67123. try {
  67124. var indices = new Uint32Array(numFaces * 3);
  67125. for (var i = 0; i < numFaces; i++) {
  67126. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  67127. var offset = i * 3;
  67128. indices[offset + 0] = faceIndices.GetValue(0);
  67129. indices[offset + 1] = faceIndices.GetValue(1);
  67130. indices[offset + 2] = faceIndices.GetValue(2);
  67131. }
  67132. vertexData.indices = indices;
  67133. }
  67134. finally {
  67135. module.destroy(faceIndices);
  67136. }
  67137. }
  67138. for (var kind in attributes) {
  67139. var uniqueId = attributes[kind];
  67140. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  67141. var dracoData = new module.DracoFloat32Array();
  67142. try {
  67143. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  67144. var babylonData = new Float32Array(numPoints * attribute.num_components());
  67145. for (var i = 0; i < babylonData.length; i++) {
  67146. babylonData[i] = dracoData.GetValue(i);
  67147. }
  67148. vertexData.set(babylonData, kind);
  67149. }
  67150. finally {
  67151. module.destroy(dracoData);
  67152. }
  67153. }
  67154. }
  67155. finally {
  67156. if (geometry) {
  67157. module.destroy(geometry);
  67158. }
  67159. module.destroy(decoder);
  67160. module.destroy(buffer);
  67161. }
  67162. return vertexData;
  67163. });
  67164. };
  67165. DracoCompression._GetDecoderModule = function () {
  67166. if (!DracoCompression._DecoderModulePromise) {
  67167. var promise = null;
  67168. var config_1 = {};
  67169. if (typeof DracoDecoderModule !== "undefined") {
  67170. promise = Promise.resolve();
  67171. }
  67172. else {
  67173. var decoder = DracoCompression.Configuration.decoder;
  67174. if (decoder) {
  67175. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67176. promise = Promise.all([
  67177. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  67178. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  67179. config_1.wasmBinary = data;
  67180. })
  67181. ]);
  67182. }
  67183. else if (decoder.fallbackUrl) {
  67184. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  67185. }
  67186. }
  67187. }
  67188. if (!promise) {
  67189. throw new Error("Draco decoder module is not available");
  67190. }
  67191. DracoCompression._DecoderModulePromise = promise.then(function () {
  67192. return new Promise(function (resolve) {
  67193. config_1.onModuleLoaded = function (decoderModule) {
  67194. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  67195. resolve({ module: decoderModule });
  67196. };
  67197. DracoDecoderModule(config_1);
  67198. });
  67199. });
  67200. }
  67201. return DracoCompression._DecoderModulePromise;
  67202. };
  67203. DracoCompression._LoadScriptAsync = function (url) {
  67204. return new Promise(function (resolve, reject) {
  67205. BABYLON.Tools.LoadScript(url, function () {
  67206. resolve();
  67207. }, function (message) {
  67208. reject(new Error(message));
  67209. });
  67210. });
  67211. };
  67212. DracoCompression._LoadFileAsync = function (url) {
  67213. return new Promise(function (resolve, reject) {
  67214. BABYLON.Tools.LoadFile(url, function (data) {
  67215. resolve(data);
  67216. }, undefined, undefined, true, function (request, exception) {
  67217. reject(exception);
  67218. });
  67219. });
  67220. };
  67221. /**
  67222. * The configuration. Defaults to the following urls:
  67223. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  67224. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  67225. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67226. */
  67227. DracoCompression.Configuration = {
  67228. decoder: {
  67229. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  67230. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  67231. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67232. }
  67233. };
  67234. return DracoCompression;
  67235. }());
  67236. BABYLON.DracoCompression = DracoCompression;
  67237. })(BABYLON || (BABYLON = {}));
  67238. //# sourceMappingURL=babylon.dracoCompression.js.map
  67239. var BABYLON;
  67240. (function (BABYLON) {
  67241. // Sets the default audio engine to Babylon JS.
  67242. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  67243. /**
  67244. * This represents the default audio engine used in babylon.
  67245. * It is responsible to play, synchronize and analyse sounds throughout the application.
  67246. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67247. */
  67248. var AudioEngine = /** @class */ (function () {
  67249. /**
  67250. * Instantiates a new audio engine.
  67251. *
  67252. * There should be only one per page as some browsers restrict the number
  67253. * of audio contexts you can create.
  67254. * @param engine defines the hosting engine
  67255. */
  67256. function AudioEngine(engine) {
  67257. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  67258. var _this = this;
  67259. this._audioContext = null;
  67260. this._audioContextInitialized = false;
  67261. this._muteButton = null;
  67262. /**
  67263. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  67264. */
  67265. this.canUseWebAudio = false;
  67266. /**
  67267. * Defines if Babylon should emit a warning if WebAudio is not supported.
  67268. * @ignoreNaming
  67269. */
  67270. this.WarnedWebAudioUnsupported = false;
  67271. /**
  67272. * Gets whether or not mp3 are supported by your browser.
  67273. */
  67274. this.isMP3supported = false;
  67275. /**
  67276. * Gets whether or not ogg are supported by your browser.
  67277. */
  67278. this.isOGGsupported = false;
  67279. /**
  67280. * Gets whether audio has been unlocked on the device.
  67281. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  67282. * a user interaction has happened.
  67283. */
  67284. this.unlocked = true;
  67285. /**
  67286. * Defines if the audio engine relies on a custom unlocked button.
  67287. * In this case, the embedded button will not be displayed.
  67288. */
  67289. this.useCustomUnlockedButton = false;
  67290. /**
  67291. * Event raised when audio has been unlocked on the browser.
  67292. */
  67293. this.onAudioUnlockedObservable = new BABYLON.Observable();
  67294. /**
  67295. * Event raised when audio has been locked on the browser.
  67296. */
  67297. this.onAudioLockedObservable = new BABYLON.Observable();
  67298. this._tryToRun = false;
  67299. this._onResize = function () {
  67300. _this._moveButtonToTopLeft();
  67301. };
  67302. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  67303. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  67304. this.canUseWebAudio = true;
  67305. }
  67306. var audioElem = document.createElement('audio');
  67307. this._engine = engine;
  67308. try {
  67309. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67310. this.isMP3supported = true;
  67311. }
  67312. }
  67313. catch (e) {
  67314. // protect error during capability check.
  67315. }
  67316. try {
  67317. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67318. this.isOGGsupported = true;
  67319. }
  67320. }
  67321. catch (e) {
  67322. // protect error during capability check.
  67323. }
  67324. }
  67325. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67326. /**
  67327. * Gets the current AudioContext if available.
  67328. */
  67329. get: function () {
  67330. if (!this._audioContextInitialized) {
  67331. this._initializeAudioContext();
  67332. }
  67333. else {
  67334. if (!this.unlocked && !this._muteButton) {
  67335. this._displayMuteButton();
  67336. }
  67337. }
  67338. return this._audioContext;
  67339. },
  67340. enumerable: true,
  67341. configurable: true
  67342. });
  67343. /**
  67344. * Flags the audio engine in Locked state.
  67345. * This happens due to new browser policies preventing audio to autoplay.
  67346. */
  67347. AudioEngine.prototype.lock = function () {
  67348. this._triggerSuspendedState();
  67349. };
  67350. /**
  67351. * Unlocks the audio engine once a user action has been done on the dom.
  67352. * This is helpful to resume play once browser policies have been satisfied.
  67353. */
  67354. AudioEngine.prototype.unlock = function () {
  67355. this._triggerRunningState();
  67356. };
  67357. AudioEngine.prototype._resumeAudioContext = function () {
  67358. var result;
  67359. if (this._audioContext.resume) {
  67360. result = this._audioContext.resume();
  67361. }
  67362. return result || Promise.resolve();
  67363. };
  67364. AudioEngine.prototype._initializeAudioContext = function () {
  67365. var _this = this;
  67366. try {
  67367. if (this.canUseWebAudio) {
  67368. this._audioContext = new AudioContext();
  67369. // create a global volume gain node
  67370. this.masterGain = this._audioContext.createGain();
  67371. this.masterGain.gain.value = 1;
  67372. this.masterGain.connect(this._audioContext.destination);
  67373. this._audioContextInitialized = true;
  67374. if (this._audioContext.state === "running") {
  67375. // Do not wait for the promise to unlock.
  67376. this._triggerRunningState();
  67377. }
  67378. else {
  67379. if (this._audioContext && this._audioContext.resume) {
  67380. this._resumeAudioContext().then(function () {
  67381. _this._triggerRunningState();
  67382. }).catch(function () {
  67383. // Can not resume automatically
  67384. // Needs user action
  67385. _this.lock();
  67386. });
  67387. }
  67388. }
  67389. }
  67390. }
  67391. catch (e) {
  67392. this.canUseWebAudio = false;
  67393. BABYLON.Tools.Error("Web Audio: " + e.message);
  67394. }
  67395. };
  67396. AudioEngine.prototype._triggerRunningState = function () {
  67397. var _this = this;
  67398. if (this._tryToRun) {
  67399. return;
  67400. }
  67401. this._tryToRun = true;
  67402. this._resumeAudioContext()
  67403. .then(function () {
  67404. _this._tryToRun = false;
  67405. _this.unlocked = true;
  67406. if (_this._muteButton) {
  67407. _this._hideMuteButton();
  67408. }
  67409. // Notify users that the audio stack is unlocked/unmuted
  67410. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67411. }).catch(function () {
  67412. _this._tryToRun = false;
  67413. _this.unlocked = false;
  67414. });
  67415. };
  67416. AudioEngine.prototype._triggerSuspendedState = function () {
  67417. this.unlocked = false;
  67418. this.onAudioLockedObservable.notifyObservers(this);
  67419. this._displayMuteButton();
  67420. };
  67421. AudioEngine.prototype._displayMuteButton = function () {
  67422. var _this = this;
  67423. if (this.useCustomUnlockedButton) {
  67424. return;
  67425. }
  67426. this._canvas = this._engine.getRenderingCanvas();
  67427. this._muteButton = document.createElement("BUTTON");
  67428. this._muteButton.className = "babylonUnmuteIcon";
  67429. this._muteButton.id = "babylonUnmuteIconBtn";
  67430. this._muteButton.title = "Unmute";
  67431. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  67432. var style = document.createElement('style');
  67433. style.appendChild(document.createTextNode(css));
  67434. document.getElementsByTagName('head')[0].appendChild(style);
  67435. document.body.appendChild(this._muteButton);
  67436. this._moveButtonToTopLeft();
  67437. this._muteButton.addEventListener('mousedown', function () {
  67438. _this._triggerRunningState();
  67439. }, true);
  67440. this._muteButton.addEventListener('touchend', function () {
  67441. _this._triggerRunningState();
  67442. }, true);
  67443. this._muteButton.addEventListener('click', function () {
  67444. _this._triggerRunningState();
  67445. }, true);
  67446. window.addEventListener("resize", this._onResize);
  67447. };
  67448. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67449. if (this._canvas && this._muteButton) {
  67450. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67451. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67452. }
  67453. };
  67454. AudioEngine.prototype._hideMuteButton = function () {
  67455. if (this._muteButton) {
  67456. document.body.removeChild(this._muteButton);
  67457. this._muteButton = null;
  67458. }
  67459. };
  67460. /**
  67461. * Destroy and release the resources associated with the audio ccontext.
  67462. */
  67463. AudioEngine.prototype.dispose = function () {
  67464. if (this.canUseWebAudio && this._audioContextInitialized) {
  67465. if (this._connectedAnalyser && this._audioContext) {
  67466. this._connectedAnalyser.stopDebugCanvas();
  67467. this._connectedAnalyser.dispose();
  67468. this.masterGain.disconnect();
  67469. this.masterGain.connect(this._audioContext.destination);
  67470. this._connectedAnalyser = null;
  67471. }
  67472. this.masterGain.gain.value = 1;
  67473. }
  67474. this.WarnedWebAudioUnsupported = false;
  67475. this._hideMuteButton();
  67476. window.removeEventListener("resize", this._onResize);
  67477. this.onAudioUnlockedObservable.clear();
  67478. this.onAudioLockedObservable.clear();
  67479. };
  67480. /**
  67481. * Gets the global volume sets on the master gain.
  67482. * @returns the global volume if set or -1 otherwise
  67483. */
  67484. AudioEngine.prototype.getGlobalVolume = function () {
  67485. if (this.canUseWebAudio && this._audioContextInitialized) {
  67486. return this.masterGain.gain.value;
  67487. }
  67488. else {
  67489. return -1;
  67490. }
  67491. };
  67492. /**
  67493. * Sets the global volume of your experience (sets on the master gain).
  67494. * @param newVolume Defines the new global volume of the application
  67495. */
  67496. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67497. if (this.canUseWebAudio && this._audioContextInitialized) {
  67498. this.masterGain.gain.value = newVolume;
  67499. }
  67500. };
  67501. /**
  67502. * Connect the audio engine to an audio analyser allowing some amazing
  67503. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67504. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67505. * @param analyser The analyser to connect to the engine
  67506. */
  67507. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67508. if (this._connectedAnalyser) {
  67509. this._connectedAnalyser.stopDebugCanvas();
  67510. }
  67511. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67512. this._connectedAnalyser = analyser;
  67513. this.masterGain.disconnect();
  67514. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67515. }
  67516. };
  67517. return AudioEngine;
  67518. }());
  67519. BABYLON.AudioEngine = AudioEngine;
  67520. })(BABYLON || (BABYLON = {}));
  67521. //# sourceMappingURL=babylon.audioEngine.js.map
  67522. var BABYLON;
  67523. (function (BABYLON) {
  67524. /**
  67525. * Defines a sound that can be played in the application.
  67526. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67527. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67528. */
  67529. var Sound = /** @class */ (function () {
  67530. /**
  67531. * Create a sound and attach it to a scene
  67532. * @param name Name of your sound
  67533. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67534. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67535. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67536. */
  67537. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67538. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67539. var _this = this;
  67540. /**
  67541. * Does the sound autoplay once loaded.
  67542. */
  67543. this.autoplay = false;
  67544. /**
  67545. * Does the sound loop after it finishes playing once.
  67546. */
  67547. this.loop = false;
  67548. /**
  67549. * Does the sound use a custom attenuation curve to simulate the falloff
  67550. * happening when the source gets further away from the camera.
  67551. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67552. */
  67553. this.useCustomAttenuation = false;
  67554. /**
  67555. * Is this sound currently played.
  67556. */
  67557. this.isPlaying = false;
  67558. /**
  67559. * Is this sound currently paused.
  67560. */
  67561. this.isPaused = false;
  67562. /**
  67563. * Does this sound enables spatial sound.
  67564. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67565. */
  67566. this.spatialSound = false;
  67567. /**
  67568. * Define the reference distance the sound should be heard perfectly.
  67569. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67570. */
  67571. this.refDistance = 1;
  67572. /**
  67573. * Define the roll off factor of spatial sounds.
  67574. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67575. */
  67576. this.rolloffFactor = 1;
  67577. /**
  67578. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67579. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67580. */
  67581. this.maxDistance = 100;
  67582. /**
  67583. * Define the distance attenuation model the sound will follow.
  67584. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67585. */
  67586. this.distanceModel = "linear";
  67587. /**
  67588. * Observable event when the current playing sound finishes.
  67589. */
  67590. this.onEndedObservable = new BABYLON.Observable();
  67591. this._panningModel = "equalpower";
  67592. this._playbackRate = 1;
  67593. this._streaming = false;
  67594. this._startTime = 0;
  67595. this._startOffset = 0;
  67596. this._position = BABYLON.Vector3.Zero();
  67597. /** @hidden */
  67598. this._positionInEmitterSpace = false;
  67599. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67600. this._volume = 1;
  67601. this._isReadyToPlay = false;
  67602. this._isDirectional = false;
  67603. // Used if you'd like to create a directional sound.
  67604. // If not set, the sound will be omnidirectional
  67605. this._coneInnerAngle = 360;
  67606. this._coneOuterAngle = 360;
  67607. this._coneOuterGain = 0;
  67608. this._isOutputConnected = false;
  67609. this._urlType = "Unknown";
  67610. this.name = name;
  67611. this._scene = scene;
  67612. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67613. if (!compo) {
  67614. compo = new BABYLON.AudioSceneComponent(scene);
  67615. scene._addComponent(compo);
  67616. }
  67617. this._readyToPlayCallback = readyToPlayCallback;
  67618. // Default custom attenuation function is a linear attenuation
  67619. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67620. if (currentDistance < maxDistance) {
  67621. return currentVolume * (1 - currentDistance / maxDistance);
  67622. }
  67623. else {
  67624. return 0;
  67625. }
  67626. };
  67627. if (options) {
  67628. this.autoplay = options.autoplay || false;
  67629. this.loop = options.loop || false;
  67630. // if volume === 0, we need another way to check this option
  67631. if (options.volume !== undefined) {
  67632. this._volume = options.volume;
  67633. }
  67634. this.spatialSound = options.spatialSound || false;
  67635. this.maxDistance = options.maxDistance || 100;
  67636. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67637. this.rolloffFactor = options.rolloffFactor || 1;
  67638. this.refDistance = options.refDistance || 1;
  67639. this.distanceModel = options.distanceModel || "linear";
  67640. this._playbackRate = options.playbackRate || 1;
  67641. this._streaming = options.streaming || false;
  67642. }
  67643. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67644. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67645. this._soundGain.gain.value = this._volume;
  67646. this._inputAudioNode = this._soundGain;
  67647. this._outputAudioNode = this._soundGain;
  67648. if (this.spatialSound) {
  67649. this._createSpatialParameters();
  67650. }
  67651. this._scene.mainSoundTrack.AddSound(this);
  67652. var validParameter = true;
  67653. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67654. if (urlOrArrayBuffer) {
  67655. try {
  67656. if (typeof (urlOrArrayBuffer) === "string") {
  67657. this._urlType = "String";
  67658. }
  67659. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67660. this._urlType = "ArrayBuffer";
  67661. }
  67662. else if (urlOrArrayBuffer instanceof MediaStream) {
  67663. this._urlType = "MediaStream";
  67664. }
  67665. else if (Array.isArray(urlOrArrayBuffer)) {
  67666. this._urlType = "Array";
  67667. }
  67668. var urls = [];
  67669. var codecSupportedFound = false;
  67670. switch (this._urlType) {
  67671. case "MediaStream":
  67672. this._streaming = true;
  67673. this._isReadyToPlay = true;
  67674. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67675. if (this.autoplay) {
  67676. this.play();
  67677. }
  67678. if (this._readyToPlayCallback) {
  67679. this._readyToPlayCallback();
  67680. }
  67681. break;
  67682. case "ArrayBuffer":
  67683. if (urlOrArrayBuffer.byteLength > 0) {
  67684. codecSupportedFound = true;
  67685. this._soundLoaded(urlOrArrayBuffer);
  67686. }
  67687. break;
  67688. case "String":
  67689. urls.push(urlOrArrayBuffer);
  67690. case "Array":
  67691. if (urls.length === 0)
  67692. urls = urlOrArrayBuffer;
  67693. // If we found a supported format, we load it immediately and stop the loop
  67694. for (var i = 0; i < urls.length; i++) {
  67695. var url = urls[i];
  67696. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67697. codecSupportedFound = true;
  67698. }
  67699. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67700. codecSupportedFound = true;
  67701. }
  67702. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67703. codecSupportedFound = true;
  67704. }
  67705. if (url.indexOf("blob:") !== -1) {
  67706. codecSupportedFound = true;
  67707. }
  67708. if (codecSupportedFound) {
  67709. // Loading sound using XHR2
  67710. if (!this._streaming) {
  67711. this._scene._loadFile(url, function (data) {
  67712. _this._soundLoaded(data);
  67713. }, undefined, true, true, function (exception) {
  67714. if (exception) {
  67715. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67716. }
  67717. BABYLON.Tools.Error("Sound creation aborted.");
  67718. _this._scene.mainSoundTrack.RemoveSound(_this);
  67719. });
  67720. }
  67721. // Streaming sound using HTML5 Audio tag
  67722. else {
  67723. this._htmlAudioElement = new Audio(url);
  67724. this._htmlAudioElement.controls = false;
  67725. this._htmlAudioElement.loop = this.loop;
  67726. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67727. this._htmlAudioElement.preload = "auto";
  67728. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67729. _this._isReadyToPlay = true;
  67730. if (_this.autoplay) {
  67731. _this.play();
  67732. }
  67733. if (_this._readyToPlayCallback) {
  67734. _this._readyToPlayCallback();
  67735. }
  67736. });
  67737. document.body.appendChild(this._htmlAudioElement);
  67738. this._htmlAudioElement.load();
  67739. }
  67740. break;
  67741. }
  67742. }
  67743. break;
  67744. default:
  67745. validParameter = false;
  67746. break;
  67747. }
  67748. if (!validParameter) {
  67749. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67750. }
  67751. else {
  67752. if (!codecSupportedFound) {
  67753. this._isReadyToPlay = true;
  67754. // Simulating a ready to play event to avoid breaking code path
  67755. if (this._readyToPlayCallback) {
  67756. window.setTimeout(function () {
  67757. if (_this._readyToPlayCallback) {
  67758. _this._readyToPlayCallback();
  67759. }
  67760. }, 1000);
  67761. }
  67762. }
  67763. }
  67764. }
  67765. catch (ex) {
  67766. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67767. this._scene.mainSoundTrack.RemoveSound(this);
  67768. }
  67769. }
  67770. }
  67771. else {
  67772. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67773. this._scene.mainSoundTrack.AddSound(this);
  67774. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67775. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67776. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67777. }
  67778. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67779. if (this._readyToPlayCallback) {
  67780. window.setTimeout(function () {
  67781. if (_this._readyToPlayCallback) {
  67782. _this._readyToPlayCallback();
  67783. }
  67784. }, 1000);
  67785. }
  67786. }
  67787. }
  67788. /**
  67789. * Release the sound and its associated resources
  67790. */
  67791. Sound.prototype.dispose = function () {
  67792. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67793. if (this.isPlaying) {
  67794. this.stop();
  67795. }
  67796. this._isReadyToPlay = false;
  67797. if (this.soundTrackId === -1) {
  67798. this._scene.mainSoundTrack.RemoveSound(this);
  67799. }
  67800. else if (this._scene.soundTracks) {
  67801. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67802. }
  67803. if (this._soundGain) {
  67804. this._soundGain.disconnect();
  67805. this._soundGain = null;
  67806. }
  67807. if (this._soundPanner) {
  67808. this._soundPanner.disconnect();
  67809. this._soundPanner = null;
  67810. }
  67811. if (this._soundSource) {
  67812. this._soundSource.disconnect();
  67813. this._soundSource = null;
  67814. }
  67815. this._audioBuffer = null;
  67816. if (this._htmlAudioElement) {
  67817. this._htmlAudioElement.pause();
  67818. this._htmlAudioElement.src = "";
  67819. document.body.removeChild(this._htmlAudioElement);
  67820. }
  67821. if (this._streamingSource) {
  67822. this._streamingSource.disconnect();
  67823. }
  67824. if (this._connectedMesh && this._registerFunc) {
  67825. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67826. this._connectedMesh = null;
  67827. }
  67828. }
  67829. };
  67830. /**
  67831. * Gets if the sounds is ready to be played or not.
  67832. * @returns true if ready, otherwise false
  67833. */
  67834. Sound.prototype.isReady = function () {
  67835. return this._isReadyToPlay;
  67836. };
  67837. Sound.prototype._soundLoaded = function (audioData) {
  67838. var _this = this;
  67839. if (!BABYLON.Engine.audioEngine.audioContext) {
  67840. return;
  67841. }
  67842. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67843. _this._audioBuffer = buffer;
  67844. _this._isReadyToPlay = true;
  67845. if (_this.autoplay) {
  67846. _this.play();
  67847. }
  67848. if (_this._readyToPlayCallback) {
  67849. _this._readyToPlayCallback();
  67850. }
  67851. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67852. };
  67853. /**
  67854. * Sets the data of the sound from an audiobuffer
  67855. * @param audioBuffer The audioBuffer containing the data
  67856. */
  67857. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67858. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67859. this._audioBuffer = audioBuffer;
  67860. this._isReadyToPlay = true;
  67861. }
  67862. };
  67863. /**
  67864. * Updates the current sounds options such as maxdistance, loop...
  67865. * @param options A JSON object containing values named as the object properties
  67866. */
  67867. Sound.prototype.updateOptions = function (options) {
  67868. if (options) {
  67869. this.loop = options.loop || this.loop;
  67870. this.maxDistance = options.maxDistance || this.maxDistance;
  67871. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67872. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67873. this.refDistance = options.refDistance || this.refDistance;
  67874. this.distanceModel = options.distanceModel || this.distanceModel;
  67875. this._playbackRate = options.playbackRate || this._playbackRate;
  67876. this._updateSpatialParameters();
  67877. if (this.isPlaying) {
  67878. if (this._streaming && this._htmlAudioElement) {
  67879. this._htmlAudioElement.playbackRate = this._playbackRate;
  67880. }
  67881. else {
  67882. if (this._soundSource) {
  67883. this._soundSource.playbackRate.value = this._playbackRate;
  67884. }
  67885. }
  67886. }
  67887. }
  67888. };
  67889. Sound.prototype._createSpatialParameters = function () {
  67890. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67891. if (this._scene.headphone) {
  67892. this._panningModel = "HRTF";
  67893. }
  67894. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67895. this._updateSpatialParameters();
  67896. this._soundPanner.connect(this._outputAudioNode);
  67897. this._inputAudioNode = this._soundPanner;
  67898. }
  67899. };
  67900. Sound.prototype._updateSpatialParameters = function () {
  67901. if (this.spatialSound && this._soundPanner) {
  67902. if (this.useCustomAttenuation) {
  67903. // Tricks to disable in a way embedded Web Audio attenuation
  67904. this._soundPanner.distanceModel = "linear";
  67905. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67906. this._soundPanner.refDistance = 1;
  67907. this._soundPanner.rolloffFactor = 1;
  67908. this._soundPanner.panningModel = this._panningModel;
  67909. }
  67910. else {
  67911. this._soundPanner.distanceModel = this.distanceModel;
  67912. this._soundPanner.maxDistance = this.maxDistance;
  67913. this._soundPanner.refDistance = this.refDistance;
  67914. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67915. this._soundPanner.panningModel = this._panningModel;
  67916. }
  67917. }
  67918. };
  67919. /**
  67920. * Switch the panning model to HRTF:
  67921. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  67922. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67923. */
  67924. Sound.prototype.switchPanningModelToHRTF = function () {
  67925. this._panningModel = "HRTF";
  67926. this._switchPanningModel();
  67927. };
  67928. /**
  67929. * Switch the panning model to Equal Power:
  67930. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  67931. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67932. */
  67933. Sound.prototype.switchPanningModelToEqualPower = function () {
  67934. this._panningModel = "equalpower";
  67935. this._switchPanningModel();
  67936. };
  67937. Sound.prototype._switchPanningModel = function () {
  67938. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67939. this._soundPanner.panningModel = this._panningModel;
  67940. }
  67941. };
  67942. /**
  67943. * Connect this sound to a sound track audio node like gain...
  67944. * @param soundTrackAudioNode the sound track audio node to connect to
  67945. */
  67946. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67948. if (this._isOutputConnected) {
  67949. this._outputAudioNode.disconnect();
  67950. }
  67951. this._outputAudioNode.connect(soundTrackAudioNode);
  67952. this._isOutputConnected = true;
  67953. }
  67954. };
  67955. /**
  67956. * Transform this sound into a directional source
  67957. * @param coneInnerAngle Size of the inner cone in degree
  67958. * @param coneOuterAngle Size of the outer cone in degree
  67959. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67960. */
  67961. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67962. if (coneOuterAngle < coneInnerAngle) {
  67963. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67964. return;
  67965. }
  67966. this._coneInnerAngle = coneInnerAngle;
  67967. this._coneOuterAngle = coneOuterAngle;
  67968. this._coneOuterGain = coneOuterGain;
  67969. this._isDirectional = true;
  67970. if (this.isPlaying && this.loop) {
  67971. this.stop();
  67972. this.play();
  67973. }
  67974. };
  67975. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67976. /**
  67977. * Gets or sets the inner angle for the directional cone.
  67978. */
  67979. get: function () {
  67980. return this._coneInnerAngle;
  67981. },
  67982. /**
  67983. * Gets or sets the inner angle for the directional cone.
  67984. */
  67985. set: function (value) {
  67986. if (value != this._coneInnerAngle) {
  67987. if (this._coneOuterAngle < value) {
  67988. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67989. return;
  67990. }
  67991. this._coneInnerAngle = value;
  67992. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67993. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67994. }
  67995. }
  67996. },
  67997. enumerable: true,
  67998. configurable: true
  67999. });
  68000. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  68001. /**
  68002. * Gets or sets the outer angle for the directional cone.
  68003. */
  68004. get: function () {
  68005. return this._coneOuterAngle;
  68006. },
  68007. /**
  68008. * Gets or sets the outer angle for the directional cone.
  68009. */
  68010. set: function (value) {
  68011. if (value != this._coneOuterAngle) {
  68012. if (value < this._coneInnerAngle) {
  68013. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68014. return;
  68015. }
  68016. this._coneOuterAngle = value;
  68017. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68018. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68019. }
  68020. }
  68021. },
  68022. enumerable: true,
  68023. configurable: true
  68024. });
  68025. /**
  68026. * Sets the position of the emitter if spatial sound is enabled
  68027. * @param newPosition Defines the new posisiton
  68028. */
  68029. Sound.prototype.setPosition = function (newPosition) {
  68030. this._position = newPosition;
  68031. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68032. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68033. }
  68034. };
  68035. /**
  68036. * Sets the local direction of the emitter if spatial sound is enabled
  68037. * @param newLocalDirection Defines the new local direction
  68038. */
  68039. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68040. this._localDirection = newLocalDirection;
  68041. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68042. this._updateDirection();
  68043. }
  68044. };
  68045. Sound.prototype._updateDirection = function () {
  68046. if (!this._connectedMesh || !this._soundPanner) {
  68047. return;
  68048. }
  68049. var mat = this._connectedMesh.getWorldMatrix();
  68050. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68051. direction.normalize();
  68052. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68053. };
  68054. /** @hidden */
  68055. Sound.prototype.updateDistanceFromListener = function () {
  68056. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68057. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68058. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68059. }
  68060. };
  68061. /**
  68062. * Sets a new custom attenuation function for the sound.
  68063. * @param callback Defines the function used for the attenuation
  68064. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68065. */
  68066. Sound.prototype.setAttenuationFunction = function (callback) {
  68067. this._customAttenuationFunction = callback;
  68068. };
  68069. /**
  68070. * Play the sound
  68071. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68072. * @param offset (optional) Start the sound setting it at a specific time
  68073. */
  68074. Sound.prototype.play = function (time, offset) {
  68075. var _this = this;
  68076. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68077. try {
  68078. if (this._startOffset < 0) {
  68079. time = -this._startOffset;
  68080. this._startOffset = 0;
  68081. }
  68082. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68083. if (!this._soundSource || !this._streamingSource) {
  68084. if (this.spatialSound && this._soundPanner) {
  68085. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68086. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68087. }
  68088. if (this._isDirectional) {
  68089. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68090. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68091. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68092. if (this._connectedMesh) {
  68093. this._updateDirection();
  68094. }
  68095. else {
  68096. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68097. }
  68098. }
  68099. }
  68100. }
  68101. if (this._streaming) {
  68102. if (!this._streamingSource) {
  68103. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  68104. this._htmlAudioElement.onended = function () { _this._onended(); };
  68105. this._htmlAudioElement.playbackRate = this._playbackRate;
  68106. }
  68107. this._streamingSource.disconnect();
  68108. this._streamingSource.connect(this._inputAudioNode);
  68109. if (this._htmlAudioElement) {
  68110. // required to manage properly the new suspended default state of Chrome
  68111. // When the option 'streaming: true' is used, we need first to wait for
  68112. // the audio engine to be unlocked by a user gesture before trying to play
  68113. // an HTML Audio elememt
  68114. var tryToPlay = function () {
  68115. if (BABYLON.Engine.audioEngine.unlocked) {
  68116. var playPromise = _this._htmlAudioElement.play();
  68117. // In browsers that don’t yet support this functionality,
  68118. // playPromise won’t be defined.
  68119. if (playPromise !== undefined) {
  68120. playPromise.catch(function (error) {
  68121. // Automatic playback failed.
  68122. // Waiting for the audio engine to be unlocked by user click on unmute
  68123. BABYLON.Engine.audioEngine.lock();
  68124. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68125. });
  68126. }
  68127. }
  68128. else {
  68129. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68130. }
  68131. };
  68132. tryToPlay();
  68133. }
  68134. }
  68135. else {
  68136. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  68137. this._soundSource.buffer = this._audioBuffer;
  68138. this._soundSource.connect(this._inputAudioNode);
  68139. this._soundSource.loop = this.loop;
  68140. this._soundSource.playbackRate.value = this._playbackRate;
  68141. this._soundSource.onended = function () { _this._onended(); };
  68142. if (this._soundSource.buffer) {
  68143. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  68144. }
  68145. }
  68146. this._startTime = startTime;
  68147. this.isPlaying = true;
  68148. this.isPaused = false;
  68149. }
  68150. catch (ex) {
  68151. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  68152. }
  68153. }
  68154. };
  68155. Sound.prototype._onended = function () {
  68156. this.isPlaying = false;
  68157. if (this.onended) {
  68158. this.onended();
  68159. }
  68160. this.onEndedObservable.notifyObservers(this);
  68161. };
  68162. /**
  68163. * Stop the sound
  68164. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  68165. */
  68166. Sound.prototype.stop = function (time) {
  68167. if (this.isPlaying) {
  68168. if (this._streaming) {
  68169. if (this._htmlAudioElement) {
  68170. this._htmlAudioElement.pause();
  68171. // Test needed for Firefox or it will generate an Invalid State Error
  68172. if (this._htmlAudioElement.currentTime > 0) {
  68173. this._htmlAudioElement.currentTime = 0;
  68174. }
  68175. }
  68176. else {
  68177. this._streamingSource.disconnect();
  68178. }
  68179. }
  68180. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  68181. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68182. this._soundSource.stop(stopTime);
  68183. this._soundSource.onended = function () { };
  68184. if (!this.isPaused) {
  68185. this._startOffset = 0;
  68186. }
  68187. }
  68188. this.isPlaying = false;
  68189. }
  68190. };
  68191. /**
  68192. * Put the sound in pause
  68193. */
  68194. Sound.prototype.pause = function () {
  68195. if (this.isPlaying) {
  68196. this.isPaused = true;
  68197. if (this._streaming) {
  68198. if (this._htmlAudioElement) {
  68199. this._htmlAudioElement.pause();
  68200. }
  68201. else {
  68202. this._streamingSource.disconnect();
  68203. }
  68204. }
  68205. else if (BABYLON.Engine.audioEngine.audioContext) {
  68206. this.stop(0);
  68207. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  68208. }
  68209. }
  68210. };
  68211. /**
  68212. * Sets a dedicated volume for this sounds
  68213. * @param newVolume Define the new volume of the sound
  68214. * @param time Define in how long the sound should be at this value
  68215. */
  68216. Sound.prototype.setVolume = function (newVolume, time) {
  68217. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  68218. if (time && BABYLON.Engine.audioEngine.audioContext) {
  68219. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  68220. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  68221. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  68222. }
  68223. else {
  68224. this._soundGain.gain.value = newVolume;
  68225. }
  68226. }
  68227. this._volume = newVolume;
  68228. };
  68229. /**
  68230. * Set the sound play back rate
  68231. * @param newPlaybackRate Define the playback rate the sound should be played at
  68232. */
  68233. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  68234. this._playbackRate = newPlaybackRate;
  68235. if (this.isPlaying) {
  68236. if (this._streaming && this._htmlAudioElement) {
  68237. this._htmlAudioElement.playbackRate = this._playbackRate;
  68238. }
  68239. else if (this._soundSource) {
  68240. this._soundSource.playbackRate.value = this._playbackRate;
  68241. }
  68242. }
  68243. };
  68244. /**
  68245. * Gets the volume of the sound.
  68246. * @returns the volume of the sound
  68247. */
  68248. Sound.prototype.getVolume = function () {
  68249. return this._volume;
  68250. };
  68251. /**
  68252. * Attach the sound to a dedicated mesh
  68253. * @param meshToConnectTo The mesh to connect the sound with
  68254. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68255. */
  68256. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  68257. var _this = this;
  68258. if (this._connectedMesh && this._registerFunc) {
  68259. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68260. this._registerFunc = null;
  68261. }
  68262. this._connectedMesh = meshToConnectTo;
  68263. if (!this.spatialSound) {
  68264. this.spatialSound = true;
  68265. this._createSpatialParameters();
  68266. if (this.isPlaying && this.loop) {
  68267. this.stop();
  68268. this.play();
  68269. }
  68270. }
  68271. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  68272. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  68273. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  68274. };
  68275. /**
  68276. * Detach the sound from the previously attached mesh
  68277. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68278. */
  68279. Sound.prototype.detachFromMesh = function () {
  68280. if (this._connectedMesh && this._registerFunc) {
  68281. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68282. this._registerFunc = null;
  68283. this._connectedMesh = null;
  68284. }
  68285. };
  68286. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  68287. if (!node.getBoundingInfo) {
  68288. return;
  68289. }
  68290. var mesh = node;
  68291. if (this._positionInEmitterSpace) {
  68292. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  68293. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  68294. }
  68295. else {
  68296. var boundingInfo = mesh.getBoundingInfo();
  68297. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  68298. }
  68299. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  68300. this._updateDirection();
  68301. }
  68302. };
  68303. /**
  68304. * Clone the current sound in the scene.
  68305. * @returns the new sound clone
  68306. */
  68307. Sound.prototype.clone = function () {
  68308. var _this = this;
  68309. if (!this._streaming) {
  68310. var setBufferAndRun = function () {
  68311. if (_this._isReadyToPlay) {
  68312. clonedSound._audioBuffer = _this.getAudioBuffer();
  68313. clonedSound._isReadyToPlay = true;
  68314. if (clonedSound.autoplay) {
  68315. clonedSound.play();
  68316. }
  68317. }
  68318. else {
  68319. window.setTimeout(setBufferAndRun, 300);
  68320. }
  68321. };
  68322. var currentOptions = {
  68323. autoplay: this.autoplay, loop: this.loop,
  68324. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68325. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68326. refDistance: this.refDistance, distanceModel: this.distanceModel
  68327. };
  68328. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68329. if (this.useCustomAttenuation) {
  68330. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68331. }
  68332. clonedSound.setPosition(this._position);
  68333. clonedSound.setPlaybackRate(this._playbackRate);
  68334. setBufferAndRun();
  68335. return clonedSound;
  68336. }
  68337. // Can't clone a streaming sound
  68338. else {
  68339. return null;
  68340. }
  68341. };
  68342. /**
  68343. * Gets the current underlying audio buffer containing the data
  68344. * @returns the audio buffer
  68345. */
  68346. Sound.prototype.getAudioBuffer = function () {
  68347. return this._audioBuffer;
  68348. };
  68349. /**
  68350. * Serializes the Sound in a JSON representation
  68351. * @returns the JSON representation of the sound
  68352. */
  68353. Sound.prototype.serialize = function () {
  68354. var serializationObject = {
  68355. name: this.name,
  68356. url: this.name,
  68357. autoplay: this.autoplay,
  68358. loop: this.loop,
  68359. volume: this._volume,
  68360. spatialSound: this.spatialSound,
  68361. maxDistance: this.maxDistance,
  68362. rolloffFactor: this.rolloffFactor,
  68363. refDistance: this.refDistance,
  68364. distanceModel: this.distanceModel,
  68365. playbackRate: this._playbackRate,
  68366. panningModel: this._panningModel,
  68367. soundTrackId: this.soundTrackId
  68368. };
  68369. if (this.spatialSound) {
  68370. if (this._connectedMesh)
  68371. serializationObject.connectedMeshId = this._connectedMesh.id;
  68372. serializationObject.position = this._position.asArray();
  68373. serializationObject.refDistance = this.refDistance;
  68374. serializationObject.distanceModel = this.distanceModel;
  68375. serializationObject.isDirectional = this._isDirectional;
  68376. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68377. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68378. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68379. serializationObject.coneOuterGain = this._coneOuterGain;
  68380. }
  68381. return serializationObject;
  68382. };
  68383. /**
  68384. * Parse a JSON representation of a sound to innstantiate in a given scene
  68385. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68386. * @param scene Define the scene the new parsed sound should be created in
  68387. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68388. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68389. * @returns the newly parsed sound
  68390. */
  68391. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68392. var soundName = parsedSound.name;
  68393. var soundUrl;
  68394. if (parsedSound.url) {
  68395. soundUrl = rootUrl + parsedSound.url;
  68396. }
  68397. else {
  68398. soundUrl = rootUrl + soundName;
  68399. }
  68400. var options = {
  68401. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68402. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68403. rolloffFactor: parsedSound.rolloffFactor,
  68404. refDistance: parsedSound.refDistance,
  68405. distanceModel: parsedSound.distanceModel,
  68406. playbackRate: parsedSound.playbackRate
  68407. };
  68408. var newSound;
  68409. if (!sourceSound) {
  68410. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68411. scene._addPendingData(newSound);
  68412. }
  68413. else {
  68414. var setBufferAndRun = function () {
  68415. if (sourceSound._isReadyToPlay) {
  68416. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68417. newSound._isReadyToPlay = true;
  68418. if (newSound.autoplay) {
  68419. newSound.play();
  68420. }
  68421. }
  68422. else {
  68423. window.setTimeout(setBufferAndRun, 300);
  68424. }
  68425. };
  68426. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68427. setBufferAndRun();
  68428. }
  68429. if (parsedSound.position) {
  68430. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68431. newSound.setPosition(soundPosition);
  68432. }
  68433. if (parsedSound.isDirectional) {
  68434. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68435. if (parsedSound.localDirectionToMesh) {
  68436. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68437. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68438. }
  68439. }
  68440. if (parsedSound.connectedMeshId) {
  68441. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68442. if (connectedMesh) {
  68443. newSound.attachToMesh(connectedMesh);
  68444. }
  68445. }
  68446. return newSound;
  68447. };
  68448. return Sound;
  68449. }());
  68450. BABYLON.Sound = Sound;
  68451. })(BABYLON || (BABYLON = {}));
  68452. //# sourceMappingURL=babylon.sound.js.map
  68453. var BABYLON;
  68454. (function (BABYLON) {
  68455. /**
  68456. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68457. * It will be also used in a future release to apply effects on a specific track.
  68458. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68459. */
  68460. var SoundTrack = /** @class */ (function () {
  68461. /**
  68462. * Creates a new sound track.
  68463. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68464. * @param scene Define the scene the sound track belongs to
  68465. * @param options
  68466. */
  68467. function SoundTrack(scene, options) {
  68468. if (options === void 0) { options = {}; }
  68469. /**
  68470. * The unique identifier of the sound track in the scene.
  68471. */
  68472. this.id = -1;
  68473. this._isMainTrack = false;
  68474. this._isInitialized = false;
  68475. this._scene = scene;
  68476. this.soundCollection = new Array();
  68477. this._options = options;
  68478. if (!this._isMainTrack && this._scene.soundTracks) {
  68479. this._scene.soundTracks.push(this);
  68480. this.id = this._scene.soundTracks.length - 1;
  68481. }
  68482. }
  68483. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68484. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68485. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68486. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68487. if (this._options) {
  68488. if (this._options.volume) {
  68489. this._outputAudioNode.gain.value = this._options.volume;
  68490. }
  68491. if (this._options.mainTrack) {
  68492. this._isMainTrack = this._options.mainTrack;
  68493. }
  68494. }
  68495. this._isInitialized = true;
  68496. }
  68497. };
  68498. /**
  68499. * Release the sound track and its associated resources
  68500. */
  68501. SoundTrack.prototype.dispose = function () {
  68502. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68503. if (this._connectedAnalyser) {
  68504. this._connectedAnalyser.stopDebugCanvas();
  68505. }
  68506. while (this.soundCollection.length) {
  68507. this.soundCollection[0].dispose();
  68508. }
  68509. if (this._outputAudioNode) {
  68510. this._outputAudioNode.disconnect();
  68511. }
  68512. this._outputAudioNode = null;
  68513. }
  68514. };
  68515. /**
  68516. * Adds a sound to this sound track
  68517. * @param sound define the cound to add
  68518. * @ignoreNaming
  68519. */
  68520. SoundTrack.prototype.AddSound = function (sound) {
  68521. if (!this._isInitialized) {
  68522. this._initializeSoundTrackAudioGraph();
  68523. }
  68524. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68525. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68526. }
  68527. if (sound.soundTrackId) {
  68528. if (sound.soundTrackId === -1) {
  68529. this._scene.mainSoundTrack.RemoveSound(sound);
  68530. }
  68531. else if (this._scene.soundTracks) {
  68532. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68533. }
  68534. }
  68535. this.soundCollection.push(sound);
  68536. sound.soundTrackId = this.id;
  68537. };
  68538. /**
  68539. * Removes a sound to this sound track
  68540. * @param sound define the cound to remove
  68541. * @ignoreNaming
  68542. */
  68543. SoundTrack.prototype.RemoveSound = function (sound) {
  68544. var index = this.soundCollection.indexOf(sound);
  68545. if (index !== -1) {
  68546. this.soundCollection.splice(index, 1);
  68547. }
  68548. };
  68549. /**
  68550. * Set a global volume for the full sound track.
  68551. * @param newVolume Define the new volume of the sound track
  68552. */
  68553. SoundTrack.prototype.setVolume = function (newVolume) {
  68554. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68555. this._outputAudioNode.gain.value = newVolume;
  68556. }
  68557. };
  68558. /**
  68559. * Switch the panning model to HRTF:
  68560. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68561. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68562. */
  68563. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68564. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68565. for (var i = 0; i < this.soundCollection.length; i++) {
  68566. this.soundCollection[i].switchPanningModelToHRTF();
  68567. }
  68568. }
  68569. };
  68570. /**
  68571. * Switch the panning model to Equal Power:
  68572. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68573. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68574. */
  68575. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68576. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68577. for (var i = 0; i < this.soundCollection.length; i++) {
  68578. this.soundCollection[i].switchPanningModelToEqualPower();
  68579. }
  68580. }
  68581. };
  68582. /**
  68583. * Connect the sound track to an audio analyser allowing some amazing
  68584. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68585. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68586. * @param analyser The analyser to connect to the engine
  68587. */
  68588. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68589. if (this._connectedAnalyser) {
  68590. this._connectedAnalyser.stopDebugCanvas();
  68591. }
  68592. this._connectedAnalyser = analyser;
  68593. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68594. this._outputAudioNode.disconnect();
  68595. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68596. }
  68597. };
  68598. return SoundTrack;
  68599. }());
  68600. BABYLON.SoundTrack = SoundTrack;
  68601. })(BABYLON || (BABYLON = {}));
  68602. //# sourceMappingURL=babylon.soundtrack.js.map
  68603. var BABYLON;
  68604. (function (BABYLON) {
  68605. /**
  68606. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68607. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68608. */
  68609. var Analyser = /** @class */ (function () {
  68610. /**
  68611. * Creates a new analyser
  68612. * @param scene defines hosting scene
  68613. */
  68614. function Analyser(scene) {
  68615. /**
  68616. * Gets or sets the smoothing
  68617. * @ignorenaming
  68618. */
  68619. this.SMOOTHING = 0.75;
  68620. /**
  68621. * Gets or sets the FFT table size
  68622. * @ignorenaming
  68623. */
  68624. this.FFT_SIZE = 512;
  68625. /**
  68626. * Gets or sets the bar graph amplitude
  68627. * @ignorenaming
  68628. */
  68629. this.BARGRAPHAMPLITUDE = 256;
  68630. /**
  68631. * Gets or sets the position of the debug canvas
  68632. * @ignorenaming
  68633. */
  68634. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68635. /**
  68636. * Gets or sets the debug canvas size
  68637. * @ignorenaming
  68638. */
  68639. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68640. this._scene = scene;
  68641. this._audioEngine = BABYLON.Engine.audioEngine;
  68642. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68643. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68644. this._webAudioAnalyser.minDecibels = -140;
  68645. this._webAudioAnalyser.maxDecibels = 0;
  68646. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68647. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68648. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68649. }
  68650. }
  68651. /**
  68652. * Get the number of data values you will have to play with for the visualization
  68653. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68654. * @returns a number
  68655. */
  68656. Analyser.prototype.getFrequencyBinCount = function () {
  68657. if (this._audioEngine.canUseWebAudio) {
  68658. return this._webAudioAnalyser.frequencyBinCount;
  68659. }
  68660. else {
  68661. return 0;
  68662. }
  68663. };
  68664. /**
  68665. * Gets the current frequency data as a byte array
  68666. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68667. * @returns a Uint8Array
  68668. */
  68669. Analyser.prototype.getByteFrequencyData = function () {
  68670. if (this._audioEngine.canUseWebAudio) {
  68671. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68672. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68673. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68674. }
  68675. return this._byteFreqs;
  68676. };
  68677. /**
  68678. * Gets the current waveform as a byte array
  68679. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68680. * @returns a Uint8Array
  68681. */
  68682. Analyser.prototype.getByteTimeDomainData = function () {
  68683. if (this._audioEngine.canUseWebAudio) {
  68684. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68685. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68686. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68687. }
  68688. return this._byteTime;
  68689. };
  68690. /**
  68691. * Gets the current frequency data as a float array
  68692. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68693. * @returns a Float32Array
  68694. */
  68695. Analyser.prototype.getFloatFrequencyData = function () {
  68696. if (this._audioEngine.canUseWebAudio) {
  68697. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68698. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68699. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68700. }
  68701. return this._floatFreqs;
  68702. };
  68703. /**
  68704. * Renders the debug canvas
  68705. */
  68706. Analyser.prototype.drawDebugCanvas = function () {
  68707. var _this = this;
  68708. if (this._audioEngine.canUseWebAudio) {
  68709. if (!this._debugCanvas) {
  68710. this._debugCanvas = document.createElement("canvas");
  68711. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68712. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68713. this._debugCanvas.style.position = "absolute";
  68714. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68715. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68716. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68717. document.body.appendChild(this._debugCanvas);
  68718. this._registerFunc = function () {
  68719. _this.drawDebugCanvas();
  68720. };
  68721. this._scene.registerBeforeRender(this._registerFunc);
  68722. }
  68723. if (this._registerFunc && this._debugCanvasContext) {
  68724. var workingArray = this.getByteFrequencyData();
  68725. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68726. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68727. // Draw the frequency domain chart.
  68728. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68729. var value = workingArray[i];
  68730. var percent = value / this.BARGRAPHAMPLITUDE;
  68731. var height = this.DEBUGCANVASSIZE.height * percent;
  68732. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68733. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68734. var hue = i / this.getFrequencyBinCount() * 360;
  68735. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68736. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68737. }
  68738. }
  68739. }
  68740. };
  68741. /**
  68742. * Stops rendering the debug canvas and removes it
  68743. */
  68744. Analyser.prototype.stopDebugCanvas = function () {
  68745. if (this._debugCanvas) {
  68746. if (this._registerFunc) {
  68747. this._scene.unregisterBeforeRender(this._registerFunc);
  68748. this._registerFunc = null;
  68749. }
  68750. document.body.removeChild(this._debugCanvas);
  68751. this._debugCanvas = null;
  68752. this._debugCanvasContext = null;
  68753. }
  68754. };
  68755. /**
  68756. * Connects two audio nodes
  68757. * @param inputAudioNode defines first node to connect
  68758. * @param outputAudioNode defines second node to connect
  68759. */
  68760. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68761. if (this._audioEngine.canUseWebAudio) {
  68762. inputAudioNode.connect(this._webAudioAnalyser);
  68763. this._webAudioAnalyser.connect(outputAudioNode);
  68764. }
  68765. };
  68766. /**
  68767. * Releases all associated resources
  68768. */
  68769. Analyser.prototype.dispose = function () {
  68770. if (this._audioEngine.canUseWebAudio) {
  68771. this._webAudioAnalyser.disconnect();
  68772. }
  68773. };
  68774. return Analyser;
  68775. }());
  68776. BABYLON.Analyser = Analyser;
  68777. })(BABYLON || (BABYLON = {}));
  68778. //# sourceMappingURL=babylon.analyser.js.map
  68779. var BABYLON;
  68780. (function (BABYLON) {
  68781. /**
  68782. * Wraps one or more Sound objects and selects one with random weight for playback.
  68783. */
  68784. var WeightedSound = /** @class */ (function () {
  68785. /**
  68786. * Creates a new WeightedSound from the list of sounds given.
  68787. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68788. * @param sounds Array of Sounds that will be selected from.
  68789. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68790. */
  68791. function WeightedSound(loop, sounds, weights) {
  68792. var _this = this;
  68793. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68794. this.loop = false;
  68795. this._coneInnerAngle = 360;
  68796. this._coneOuterAngle = 360;
  68797. this._volume = 1;
  68798. /** A Sound is currently playing. */
  68799. this.isPlaying = false;
  68800. /** A Sound is currently paused. */
  68801. this.isPaused = false;
  68802. this._sounds = [];
  68803. this._weights = [];
  68804. if (sounds.length !== weights.length) {
  68805. throw new Error('Sounds length does not equal weights length');
  68806. }
  68807. this.loop = loop;
  68808. this._weights = weights;
  68809. // Normalize the weights
  68810. var weightSum = 0;
  68811. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68812. var weight = weights_1[_i];
  68813. weightSum += weight;
  68814. }
  68815. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68816. for (var i = 0; i < this._weights.length; i++) {
  68817. this._weights[i] *= invWeightSum;
  68818. }
  68819. this._sounds = sounds;
  68820. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68821. var sound = _b[_a];
  68822. sound.onEndedObservable.add(function () { _this._onended(); });
  68823. }
  68824. }
  68825. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68826. /**
  68827. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68828. */
  68829. get: function () {
  68830. return this._coneInnerAngle;
  68831. },
  68832. /**
  68833. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68834. */
  68835. set: function (value) {
  68836. if (value !== this._coneInnerAngle) {
  68837. if (this._coneOuterAngle < value) {
  68838. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68839. return;
  68840. }
  68841. this._coneInnerAngle = value;
  68842. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68843. var sound = _a[_i];
  68844. sound.directionalConeInnerAngle = value;
  68845. }
  68846. }
  68847. },
  68848. enumerable: true,
  68849. configurable: true
  68850. });
  68851. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68852. /**
  68853. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68854. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68855. */
  68856. get: function () {
  68857. return this._coneOuterAngle;
  68858. },
  68859. /**
  68860. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68861. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68862. */
  68863. set: function (value) {
  68864. if (value !== this._coneOuterAngle) {
  68865. if (value < this._coneInnerAngle) {
  68866. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68867. return;
  68868. }
  68869. this._coneOuterAngle = value;
  68870. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68871. var sound = _a[_i];
  68872. sound.directionalConeOuterAngle = value;
  68873. }
  68874. }
  68875. },
  68876. enumerable: true,
  68877. configurable: true
  68878. });
  68879. Object.defineProperty(WeightedSound.prototype, "volume", {
  68880. /**
  68881. * Playback volume.
  68882. */
  68883. get: function () {
  68884. return this._volume;
  68885. },
  68886. /**
  68887. * Playback volume.
  68888. */
  68889. set: function (value) {
  68890. if (value !== this._volume) {
  68891. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68892. var sound = _a[_i];
  68893. sound.setVolume(value);
  68894. }
  68895. }
  68896. },
  68897. enumerable: true,
  68898. configurable: true
  68899. });
  68900. WeightedSound.prototype._onended = function () {
  68901. if (this._currentIndex !== undefined) {
  68902. this._sounds[this._currentIndex].autoplay = false;
  68903. }
  68904. if (this.loop && this.isPlaying) {
  68905. this.play();
  68906. }
  68907. else {
  68908. this.isPlaying = false;
  68909. }
  68910. };
  68911. /**
  68912. * Suspend playback
  68913. */
  68914. WeightedSound.prototype.pause = function () {
  68915. this.isPaused = true;
  68916. if (this._currentIndex !== undefined) {
  68917. this._sounds[this._currentIndex].pause();
  68918. }
  68919. };
  68920. /**
  68921. * Stop playback
  68922. */
  68923. WeightedSound.prototype.stop = function () {
  68924. this.isPlaying = false;
  68925. if (this._currentIndex !== undefined) {
  68926. this._sounds[this._currentIndex].stop();
  68927. }
  68928. };
  68929. /**
  68930. * Start playback.
  68931. * @param startOffset Position the clip head at a specific time in seconds.
  68932. */
  68933. WeightedSound.prototype.play = function (startOffset) {
  68934. if (!this.isPaused) {
  68935. this.stop();
  68936. var randomValue = Math.random();
  68937. var total = 0;
  68938. for (var i = 0; i < this._weights.length; i++) {
  68939. total += this._weights[i];
  68940. if (randomValue <= total) {
  68941. this._currentIndex = i;
  68942. break;
  68943. }
  68944. }
  68945. }
  68946. var sound = this._sounds[this._currentIndex];
  68947. if (sound.isReady()) {
  68948. sound.play(0, this.isPaused ? undefined : startOffset);
  68949. }
  68950. else {
  68951. sound.autoplay = true;
  68952. }
  68953. this.isPlaying = true;
  68954. this.isPaused = false;
  68955. };
  68956. return WeightedSound;
  68957. }());
  68958. BABYLON.WeightedSound = WeightedSound;
  68959. })(BABYLON || (BABYLON = {}));
  68960. //# sourceMappingURL=babylon.weightedsound.js.map
  68961. var BABYLON;
  68962. (function (BABYLON) {
  68963. // Adds the parser to the scene parsers.
  68964. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68965. // TODO: add sound
  68966. var loadedSounds = [];
  68967. var loadedSound;
  68968. container.sounds = container.sounds || [];
  68969. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68970. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68971. var parsedSound = parsedData.sounds[index];
  68972. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68973. if (!parsedSound.url)
  68974. parsedSound.url = parsedSound.name;
  68975. if (!loadedSounds[parsedSound.url]) {
  68976. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68977. loadedSounds[parsedSound.url] = loadedSound;
  68978. container.sounds.push(loadedSound);
  68979. }
  68980. else {
  68981. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68982. }
  68983. }
  68984. else {
  68985. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68986. }
  68987. }
  68988. }
  68989. loadedSounds = [];
  68990. });
  68991. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68992. get: function () {
  68993. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68994. if (!compo) {
  68995. compo = new AudioSceneComponent(this);
  68996. this._addComponent(compo);
  68997. }
  68998. if (!this._mainSoundTrack) {
  68999. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  69000. }
  69001. return this._mainSoundTrack;
  69002. },
  69003. enumerable: true,
  69004. configurable: true
  69005. });
  69006. BABYLON.Scene.prototype.getSoundByName = function (name) {
  69007. var index;
  69008. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  69009. if (this.mainSoundTrack.soundCollection[index].name === name) {
  69010. return this.mainSoundTrack.soundCollection[index];
  69011. }
  69012. }
  69013. if (this.soundTracks) {
  69014. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  69015. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  69016. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  69017. return this.soundTracks[sdIndex].soundCollection[index];
  69018. }
  69019. }
  69020. }
  69021. }
  69022. return null;
  69023. };
  69024. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  69025. get: function () {
  69026. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69027. if (!compo) {
  69028. compo = new AudioSceneComponent(this);
  69029. this._addComponent(compo);
  69030. }
  69031. return compo.audioEnabled;
  69032. },
  69033. set: function (value) {
  69034. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69035. if (!compo) {
  69036. compo = new AudioSceneComponent(this);
  69037. this._addComponent(compo);
  69038. }
  69039. if (value) {
  69040. compo.enableAudio();
  69041. }
  69042. else {
  69043. compo.disableAudio();
  69044. }
  69045. },
  69046. enumerable: true,
  69047. configurable: true
  69048. });
  69049. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69050. get: function () {
  69051. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69052. if (!compo) {
  69053. compo = new AudioSceneComponent(this);
  69054. this._addComponent(compo);
  69055. }
  69056. return compo.headphone;
  69057. },
  69058. set: function (value) {
  69059. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69060. if (!compo) {
  69061. compo = new AudioSceneComponent(this);
  69062. this._addComponent(compo);
  69063. }
  69064. if (value) {
  69065. compo.switchAudioModeForHeadphones();
  69066. }
  69067. else {
  69068. compo.switchAudioModeForNormalSpeakers();
  69069. }
  69070. },
  69071. enumerable: true,
  69072. configurable: true
  69073. });
  69074. /**
  69075. * Defines the sound scene component responsible to manage any sounds
  69076. * in a given scene.
  69077. */
  69078. var AudioSceneComponent = /** @class */ (function () {
  69079. /**
  69080. * Creates a new instance of the component for the given scene
  69081. * @param scene Defines the scene to register the component in
  69082. */
  69083. function AudioSceneComponent(scene) {
  69084. /**
  69085. * The component name helpfull to identify the component in the list of scene components.
  69086. */
  69087. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69088. this._audioEnabled = true;
  69089. this._headphone = false;
  69090. this.scene = scene;
  69091. scene.soundTracks = new Array();
  69092. scene.sounds = new Array();
  69093. }
  69094. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69095. /**
  69096. * Gets whether audio is enabled or not.
  69097. * Please use related enable/disable method to switch state.
  69098. */
  69099. get: function () {
  69100. return this._audioEnabled;
  69101. },
  69102. enumerable: true,
  69103. configurable: true
  69104. });
  69105. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  69106. /**
  69107. * Gets whether audio is outputing to headphone or not.
  69108. * Please use the according Switch methods to change output.
  69109. */
  69110. get: function () {
  69111. return this._headphone;
  69112. },
  69113. enumerable: true,
  69114. configurable: true
  69115. });
  69116. /**
  69117. * Registers the component in a given scene
  69118. */
  69119. AudioSceneComponent.prototype.register = function () {
  69120. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  69121. };
  69122. /**
  69123. * Rebuilds the elements related to this component in case of
  69124. * context lost for instance.
  69125. */
  69126. AudioSceneComponent.prototype.rebuild = function () {
  69127. // Nothing to do here. (Not rendering related)
  69128. };
  69129. /**
  69130. * Serializes the component data to the specified json object
  69131. * @param serializationObject The object to serialize to
  69132. */
  69133. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  69134. serializationObject.sounds = [];
  69135. if (this.scene.soundTracks) {
  69136. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  69137. var soundtrack = this.scene.soundTracks[index];
  69138. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69139. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69140. }
  69141. }
  69142. }
  69143. };
  69144. /**
  69145. * Adds all the element from the container to the scene
  69146. * @param container the container holding the elements
  69147. */
  69148. AudioSceneComponent.prototype.addFromContainer = function (container) {
  69149. var _this = this;
  69150. if (!container.sounds) {
  69151. return;
  69152. }
  69153. container.sounds.forEach(function (sound) {
  69154. sound.play();
  69155. sound.autoplay = true;
  69156. _this.scene.mainSoundTrack.AddSound(sound);
  69157. });
  69158. };
  69159. /**
  69160. * Removes all the elements in the container from the scene
  69161. * @param container contains the elements to remove
  69162. */
  69163. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  69164. var _this = this;
  69165. if (!container.sounds) {
  69166. return;
  69167. }
  69168. container.sounds.forEach(function (sound) {
  69169. sound.stop();
  69170. sound.autoplay = false;
  69171. _this.scene.mainSoundTrack.RemoveSound(sound);
  69172. });
  69173. };
  69174. /**
  69175. * Disposes the component and the associated ressources.
  69176. */
  69177. AudioSceneComponent.prototype.dispose = function () {
  69178. var scene = this.scene;
  69179. if (scene._mainSoundTrack) {
  69180. scene.mainSoundTrack.dispose();
  69181. }
  69182. if (scene.soundTracks) {
  69183. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  69184. scene.soundTracks[scIndex].dispose();
  69185. }
  69186. }
  69187. };
  69188. /**
  69189. * Disables audio in the associated scene.
  69190. */
  69191. AudioSceneComponent.prototype.disableAudio = function () {
  69192. var scene = this.scene;
  69193. this._audioEnabled = false;
  69194. var i;
  69195. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69196. scene.mainSoundTrack.soundCollection[i].pause();
  69197. }
  69198. if (scene.soundTracks) {
  69199. for (i = 0; i < scene.soundTracks.length; i++) {
  69200. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69201. scene.soundTracks[i].soundCollection[j].pause();
  69202. }
  69203. }
  69204. }
  69205. };
  69206. /**
  69207. * Enables audio in the associated scene.
  69208. */
  69209. AudioSceneComponent.prototype.enableAudio = function () {
  69210. var scene = this.scene;
  69211. this._audioEnabled = true;
  69212. var i;
  69213. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69214. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  69215. scene.mainSoundTrack.soundCollection[i].play();
  69216. }
  69217. }
  69218. if (scene.soundTracks) {
  69219. for (i = 0; i < scene.soundTracks.length; i++) {
  69220. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69221. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  69222. scene.soundTracks[i].soundCollection[j].play();
  69223. }
  69224. }
  69225. }
  69226. }
  69227. };
  69228. /**
  69229. * Switch audio to headphone output.
  69230. */
  69231. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  69232. var scene = this.scene;
  69233. this._headphone = true;
  69234. scene.mainSoundTrack.switchPanningModelToHRTF();
  69235. if (scene.soundTracks) {
  69236. for (var i = 0; i < scene.soundTracks.length; i++) {
  69237. scene.soundTracks[i].switchPanningModelToHRTF();
  69238. }
  69239. }
  69240. };
  69241. /**
  69242. * Switch audio to normal speakers.
  69243. */
  69244. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  69245. var scene = this.scene;
  69246. this._headphone = false;
  69247. scene.mainSoundTrack.switchPanningModelToEqualPower();
  69248. if (scene.soundTracks) {
  69249. for (var i = 0; i < scene.soundTracks.length; i++) {
  69250. scene.soundTracks[i].switchPanningModelToEqualPower();
  69251. }
  69252. }
  69253. };
  69254. AudioSceneComponent.prototype._afterRender = function () {
  69255. var scene = this.scene;
  69256. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  69257. return;
  69258. }
  69259. var listeningCamera;
  69260. var audioEngine = BABYLON.Engine.audioEngine;
  69261. if (scene.activeCameras.length > 0) {
  69262. listeningCamera = scene.activeCameras[0];
  69263. }
  69264. else {
  69265. listeningCamera = scene.activeCamera;
  69266. }
  69267. if (listeningCamera && audioEngine.audioContext) {
  69268. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  69269. // for VR cameras
  69270. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  69271. listeningCamera = listeningCamera.rigCameras[0];
  69272. }
  69273. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  69274. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  69275. cameraDirection.normalize();
  69276. // To avoid some errors on GearVR
  69277. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  69278. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  69279. }
  69280. var i;
  69281. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69282. var sound = scene.mainSoundTrack.soundCollection[i];
  69283. if (sound.useCustomAttenuation) {
  69284. sound.updateDistanceFromListener();
  69285. }
  69286. }
  69287. if (scene.soundTracks) {
  69288. for (i = 0; i < scene.soundTracks.length; i++) {
  69289. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69290. sound = scene.soundTracks[i].soundCollection[j];
  69291. if (sound.useCustomAttenuation) {
  69292. sound.updateDistanceFromListener();
  69293. }
  69294. }
  69295. }
  69296. }
  69297. }
  69298. };
  69299. return AudioSceneComponent;
  69300. }());
  69301. BABYLON.AudioSceneComponent = AudioSceneComponent;
  69302. })(BABYLON || (BABYLON = {}));
  69303. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  69304. var BABYLON;
  69305. (function (BABYLON) {
  69306. /**
  69307. * This defines an action helpful to play a defined sound on a triggered action.
  69308. */
  69309. var PlaySoundAction = /** @class */ (function (_super) {
  69310. __extends(PlaySoundAction, _super);
  69311. /**
  69312. * Instantiate the action
  69313. * @param triggerOptions defines the trigger options
  69314. * @param sound defines the sound to play
  69315. * @param condition defines the trigger related conditions
  69316. */
  69317. function PlaySoundAction(triggerOptions, sound, condition) {
  69318. var _this = _super.call(this, triggerOptions, condition) || this;
  69319. _this._sound = sound;
  69320. return _this;
  69321. }
  69322. /** @hidden */
  69323. PlaySoundAction.prototype._prepare = function () {
  69324. };
  69325. /**
  69326. * Execute the action and play the sound.
  69327. */
  69328. PlaySoundAction.prototype.execute = function () {
  69329. if (this._sound !== undefined)
  69330. this._sound.play();
  69331. };
  69332. /**
  69333. * Serializes the actions and its related information.
  69334. * @param parent defines the object to serialize in
  69335. * @returns the serialized object
  69336. */
  69337. PlaySoundAction.prototype.serialize = function (parent) {
  69338. return _super.prototype._serialize.call(this, {
  69339. name: "PlaySoundAction",
  69340. properties: [{ name: "sound", value: this._sound.name }]
  69341. }, parent);
  69342. };
  69343. return PlaySoundAction;
  69344. }(BABYLON.Action));
  69345. BABYLON.PlaySoundAction = PlaySoundAction;
  69346. /**
  69347. * This defines an action helpful to stop a defined sound on a triggered action.
  69348. */
  69349. var StopSoundAction = /** @class */ (function (_super) {
  69350. __extends(StopSoundAction, _super);
  69351. /**
  69352. * Instantiate the action
  69353. * @param triggerOptions defines the trigger options
  69354. * @param sound defines the sound to stop
  69355. * @param condition defines the trigger related conditions
  69356. */
  69357. function StopSoundAction(triggerOptions, sound, condition) {
  69358. var _this = _super.call(this, triggerOptions, condition) || this;
  69359. _this._sound = sound;
  69360. return _this;
  69361. }
  69362. /** @hidden */
  69363. StopSoundAction.prototype._prepare = function () {
  69364. };
  69365. /**
  69366. * Execute the action and stop the sound.
  69367. */
  69368. StopSoundAction.prototype.execute = function () {
  69369. if (this._sound !== undefined)
  69370. this._sound.stop();
  69371. };
  69372. /**
  69373. * Serializes the actions and its related information.
  69374. * @param parent defines the object to serialize in
  69375. * @returns the serialized object
  69376. */
  69377. StopSoundAction.prototype.serialize = function (parent) {
  69378. return _super.prototype._serialize.call(this, {
  69379. name: "StopSoundAction",
  69380. properties: [{ name: "sound", value: this._sound.name }]
  69381. }, parent);
  69382. };
  69383. return StopSoundAction;
  69384. }(BABYLON.Action));
  69385. BABYLON.StopSoundAction = StopSoundAction;
  69386. })(BABYLON || (BABYLON = {}));
  69387. //# sourceMappingURL=babylon.directAudioActions.js.map
  69388. var BABYLON;
  69389. (function (BABYLON) {
  69390. var CubeTexture = /** @class */ (function (_super) {
  69391. __extends(CubeTexture, _super);
  69392. /**
  69393. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69394. * as prefiltered data.
  69395. * @param rootUrl defines the url of the texture or the root name of the six images
  69396. * @param scene defines the scene the texture is attached to
  69397. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69398. * @param noMipmap defines if mipmaps should be created or not
  69399. * @param files defines the six files to load for the different faces
  69400. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69401. * @param onError defines a callback triggered in case of error during load
  69402. * @param format defines the internal format to use for the texture once loaded
  69403. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69404. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69405. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69406. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69407. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69408. * @return the cube texture
  69409. */
  69410. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69411. if (extensions === void 0) { extensions = null; }
  69412. if (noMipmap === void 0) { noMipmap = false; }
  69413. if (files === void 0) { files = null; }
  69414. if (onLoad === void 0) { onLoad = null; }
  69415. if (onError === void 0) { onError = null; }
  69416. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69417. if (prefiltered === void 0) { prefiltered = false; }
  69418. if (forcedExtension === void 0) { forcedExtension = null; }
  69419. if (createPolynomials === void 0) { createPolynomials = false; }
  69420. if (lodScale === void 0) { lodScale = 0.8; }
  69421. if (lodOffset === void 0) { lodOffset = 0; }
  69422. var _this = _super.call(this, scene) || this;
  69423. /**
  69424. * Gets or sets the center of the bounding box associated with the cube texture
  69425. * It must define where the camera used to render the texture was set
  69426. */
  69427. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69428. _this._rotationY = 0;
  69429. /** @hidden */
  69430. _this._prefiltered = false;
  69431. _this.name = rootUrl;
  69432. _this.url = rootUrl;
  69433. _this._noMipmap = noMipmap;
  69434. _this.hasAlpha = false;
  69435. _this._format = format;
  69436. _this.isCube = true;
  69437. _this._textureMatrix = BABYLON.Matrix.Identity();
  69438. _this._createPolynomials = createPolynomials;
  69439. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69440. if (!rootUrl && !files) {
  69441. return _this;
  69442. }
  69443. var lastDot = rootUrl.lastIndexOf(".");
  69444. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69445. var isDDS = (extension === ".dds");
  69446. var isEnv = (extension === ".env");
  69447. if (isEnv) {
  69448. _this.gammaSpace = false;
  69449. _this._prefiltered = false;
  69450. }
  69451. else {
  69452. _this._prefiltered = prefiltered;
  69453. if (prefiltered) {
  69454. _this.gammaSpace = false;
  69455. }
  69456. }
  69457. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69458. if (!files) {
  69459. if (!isEnv && !isDDS && !extensions) {
  69460. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69461. }
  69462. files = [];
  69463. if (extensions) {
  69464. for (var index = 0; index < extensions.length; index++) {
  69465. files.push(rootUrl + extensions[index]);
  69466. }
  69467. }
  69468. }
  69469. _this._files = files;
  69470. if (!_this._texture) {
  69471. if (!scene.useDelayedTextureLoading) {
  69472. if (prefiltered) {
  69473. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69474. }
  69475. else {
  69476. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69477. }
  69478. }
  69479. else {
  69480. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69481. }
  69482. }
  69483. else if (onLoad) {
  69484. if (_this._texture.isReady) {
  69485. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69486. }
  69487. else {
  69488. _this._texture.onLoadedObservable.add(onLoad);
  69489. }
  69490. }
  69491. return _this;
  69492. }
  69493. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69494. get: function () {
  69495. return this._boundingBoxSize;
  69496. },
  69497. /**
  69498. * Gets or sets the size of the bounding box associated with the cube texture
  69499. * When defined, the cubemap will switch to local mode
  69500. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69501. * @example https://www.babylonjs-playground.com/#RNASML
  69502. */
  69503. set: function (value) {
  69504. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69505. return;
  69506. }
  69507. this._boundingBoxSize = value;
  69508. var scene = this.getScene();
  69509. if (scene) {
  69510. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69511. }
  69512. },
  69513. enumerable: true,
  69514. configurable: true
  69515. });
  69516. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69517. /**
  69518. * Gets texture matrix rotation angle around Y axis radians.
  69519. */
  69520. get: function () {
  69521. return this._rotationY;
  69522. },
  69523. /**
  69524. * Sets texture matrix rotation angle around Y axis in radians.
  69525. */
  69526. set: function (value) {
  69527. this._rotationY = value;
  69528. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69529. },
  69530. enumerable: true,
  69531. configurable: true
  69532. });
  69533. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69534. var rootUrlKey = "";
  69535. files.forEach(function (url) { return rootUrlKey += url; });
  69536. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69537. };
  69538. /**
  69539. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69540. * @param url defines the url of the prefiltered texture
  69541. * @param scene defines the scene the texture is attached to
  69542. * @param forcedExtension defines the extension of the file if different from the url
  69543. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69544. * @return the prefiltered texture
  69545. */
  69546. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69547. if (forcedExtension === void 0) { forcedExtension = null; }
  69548. if (createPolynomials === void 0) { createPolynomials = true; }
  69549. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69550. };
  69551. // Methods
  69552. CubeTexture.prototype.delayLoad = function () {
  69553. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69554. return;
  69555. }
  69556. var scene = this.getScene();
  69557. if (!scene) {
  69558. return;
  69559. }
  69560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69561. this._texture = this._getFromCache(this.url, this._noMipmap);
  69562. if (!this._texture) {
  69563. if (this._prefiltered) {
  69564. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69565. }
  69566. else {
  69567. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69568. }
  69569. }
  69570. };
  69571. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69572. return this._textureMatrix;
  69573. };
  69574. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69575. this._textureMatrix = value;
  69576. };
  69577. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69578. var texture = BABYLON.SerializationHelper.Parse(function () {
  69579. var prefiltered = false;
  69580. if (parsedTexture.prefiltered) {
  69581. prefiltered = parsedTexture.prefiltered;
  69582. }
  69583. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69584. }, parsedTexture, scene);
  69585. // Local Cubemaps
  69586. if (parsedTexture.boundingBoxPosition) {
  69587. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69588. }
  69589. if (parsedTexture.boundingBoxSize) {
  69590. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69591. }
  69592. // Animations
  69593. if (parsedTexture.animations) {
  69594. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69595. var parsedAnimation = parsedTexture.animations[animationIndex];
  69596. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69597. }
  69598. }
  69599. return texture;
  69600. };
  69601. CubeTexture.prototype.clone = function () {
  69602. var _this = this;
  69603. return BABYLON.SerializationHelper.Clone(function () {
  69604. var scene = _this.getScene();
  69605. if (!scene) {
  69606. return _this;
  69607. }
  69608. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69609. }, this);
  69610. };
  69611. __decorate([
  69612. BABYLON.serialize("rotationY")
  69613. ], CubeTexture.prototype, "rotationY", null);
  69614. return CubeTexture;
  69615. }(BABYLON.BaseTexture));
  69616. BABYLON.CubeTexture = CubeTexture;
  69617. })(BABYLON || (BABYLON = {}));
  69618. //# sourceMappingURL=babylon.cubeTexture.js.map
  69619. var BABYLON;
  69620. (function (BABYLON) {
  69621. /**
  69622. * Raw cube texture where the raw buffers are passed in
  69623. */
  69624. var RawCubeTexture = /** @class */ (function (_super) {
  69625. __extends(RawCubeTexture, _super);
  69626. /**
  69627. * Creates a cube texture where the raw buffers are passed in.
  69628. * @param scene defines the scene the texture is attached to
  69629. * @param data defines the array of data to use to create each face
  69630. * @param size defines the size of the textures
  69631. * @param format defines the format of the data
  69632. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69633. * @param generateMipMaps defines if the engine should generate the mip levels
  69634. * @param invertY defines if data must be stored with Y axis inverted
  69635. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69636. * @param compression defines the compression used (null by default)
  69637. */
  69638. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69640. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69641. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69642. if (invertY === void 0) { invertY = false; }
  69643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69644. if (compression === void 0) { compression = null; }
  69645. var _this = _super.call(this, "", scene) || this;
  69646. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69647. return _this;
  69648. }
  69649. /**
  69650. * Updates the raw cube texture.
  69651. * @param data defines the data to store
  69652. * @param format defines the data format
  69653. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69654. * @param invertY defines if data must be stored with Y axis inverted
  69655. * @param compression defines the compression used (null by default)
  69656. * @param level defines which level of the texture to update
  69657. */
  69658. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69659. if (compression === void 0) { compression = null; }
  69660. if (level === void 0) { level = 0; }
  69661. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69662. };
  69663. /**
  69664. * Updates a raw cube texture with RGBD encoded data.
  69665. * @param data defines the array of data [mipmap][face] to use to create each face
  69666. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69667. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69668. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69669. * @returns a promsie that resolves when the operation is complete
  69670. */
  69671. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69672. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69673. if (lodScale === void 0) { lodScale = 0.8; }
  69674. if (lodOffset === void 0) { lodOffset = 0; }
  69675. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69676. };
  69677. /**
  69678. * Clones the raw cube texture.
  69679. * @return a new cube texture
  69680. */
  69681. RawCubeTexture.prototype.clone = function () {
  69682. var _this = this;
  69683. return BABYLON.SerializationHelper.Clone(function () {
  69684. var scene = _this.getScene();
  69685. var internalTexture = _this._texture;
  69686. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69687. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69688. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69689. }
  69690. return texture;
  69691. }, this);
  69692. };
  69693. /** @hidden */
  69694. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69695. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69696. internalTexture._bufferViewArrayArray = data;
  69697. internalTexture._lodGenerationScale = lodScale;
  69698. internalTexture._lodGenerationOffset = lodOffset;
  69699. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69700. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69701. internalTexture.isReady = true;
  69702. });
  69703. };
  69704. return RawCubeTexture;
  69705. }(BABYLON.CubeTexture));
  69706. BABYLON.RawCubeTexture = RawCubeTexture;
  69707. })(BABYLON || (BABYLON = {}));
  69708. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69709. var BABYLON;
  69710. (function (BABYLON) {
  69711. var RenderTargetTexture = /** @class */ (function (_super) {
  69712. __extends(RenderTargetTexture, _super);
  69713. /**
  69714. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69715. * or used a shadow, depth texture...
  69716. * @param name The friendly name of the texture
  69717. * @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)
  69718. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69719. * @param generateMipMaps True if mip maps need to be generated after render.
  69720. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69721. * @param type The type of the buffer in the RTT (int, half float, float...)
  69722. * @param isCube True if a cube texture needs to be created
  69723. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69724. * @param generateDepthBuffer True to generate a depth buffer
  69725. * @param generateStencilBuffer True to generate a stencil buffer
  69726. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69727. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69728. */
  69729. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69730. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69731. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69732. if (isCube === void 0) { isCube = false; }
  69733. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69734. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69735. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69736. if (isMulti === void 0) { isMulti = false; }
  69737. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69738. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69739. _this.isCube = isCube;
  69740. _this.renderParticles = true;
  69741. _this.renderSprites = false;
  69742. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69743. _this.ignoreCameraViewport = false;
  69744. // Events
  69745. /**
  69746. * An event triggered when the texture is unbind.
  69747. */
  69748. _this.onBeforeBindObservable = new BABYLON.Observable();
  69749. /**
  69750. * An event triggered when the texture is unbind.
  69751. */
  69752. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69753. /**
  69754. * An event triggered before rendering the texture
  69755. */
  69756. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69757. /**
  69758. * An event triggered after rendering the texture
  69759. */
  69760. _this.onAfterRenderObservable = new BABYLON.Observable();
  69761. /**
  69762. * An event triggered after the texture clear
  69763. */
  69764. _this.onClearObservable = new BABYLON.Observable();
  69765. _this._currentRefreshId = -1;
  69766. _this._refreshRate = 1;
  69767. _this._samples = 1;
  69768. /**
  69769. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69770. * It must define where the camera used to render the texture is set
  69771. */
  69772. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69773. scene = _this.getScene();
  69774. if (!scene) {
  69775. return _this;
  69776. }
  69777. _this.renderList = new Array();
  69778. _this._engine = scene.getEngine();
  69779. _this.name = name;
  69780. _this.isRenderTarget = true;
  69781. _this._initialSizeParameter = size;
  69782. _this._processSizeParameter(size);
  69783. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69784. });
  69785. _this._generateMipMaps = generateMipMaps ? true : false;
  69786. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69787. // Rendering groups
  69788. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69789. _this._renderingManager._useSceneAutoClearSetup = true;
  69790. if (isMulti) {
  69791. return _this;
  69792. }
  69793. _this._renderTargetOptions = {
  69794. generateMipMaps: generateMipMaps,
  69795. type: type,
  69796. format: format,
  69797. samplingMode: samplingMode,
  69798. generateDepthBuffer: generateDepthBuffer,
  69799. generateStencilBuffer: generateStencilBuffer
  69800. };
  69801. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69802. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69803. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69804. }
  69805. if (isCube) {
  69806. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69807. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69808. _this._textureMatrix = BABYLON.Matrix.Identity();
  69809. }
  69810. else {
  69811. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69812. }
  69813. return _this;
  69814. }
  69815. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69816. get: function () {
  69817. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69818. },
  69819. enumerable: true,
  69820. configurable: true
  69821. });
  69822. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69823. get: function () {
  69824. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69825. },
  69826. enumerable: true,
  69827. configurable: true
  69828. });
  69829. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69830. get: function () {
  69831. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69832. },
  69833. enumerable: true,
  69834. configurable: true
  69835. });
  69836. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69837. /**
  69838. * Use this list to define the list of mesh you want to render.
  69839. */
  69840. get: function () {
  69841. return this._renderList;
  69842. },
  69843. set: function (value) {
  69844. this._renderList = value;
  69845. if (this._renderList) {
  69846. this._hookArray(this._renderList);
  69847. }
  69848. },
  69849. enumerable: true,
  69850. configurable: true
  69851. });
  69852. RenderTargetTexture.prototype._hookArray = function (array) {
  69853. var _this = this;
  69854. var oldPush = array.push;
  69855. array.push = function () {
  69856. var items = [];
  69857. for (var _i = 0; _i < arguments.length; _i++) {
  69858. items[_i] = arguments[_i];
  69859. }
  69860. var result = oldPush.apply(array, items);
  69861. _this.getScene().meshes.forEach(function (mesh) {
  69862. mesh._markSubMeshesAsLightDirty();
  69863. });
  69864. return result;
  69865. };
  69866. var oldSplice = array.splice;
  69867. array.splice = function (index, deleteCount) {
  69868. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69869. _this.getScene().meshes.forEach(function (mesh) {
  69870. mesh._markSubMeshesAsLightDirty();
  69871. });
  69872. return deleted;
  69873. };
  69874. };
  69875. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69876. set: function (callback) {
  69877. if (this._onAfterUnbindObserver) {
  69878. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69879. }
  69880. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69881. },
  69882. enumerable: true,
  69883. configurable: true
  69884. });
  69885. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69886. set: function (callback) {
  69887. if (this._onBeforeRenderObserver) {
  69888. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69889. }
  69890. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69896. set: function (callback) {
  69897. if (this._onAfterRenderObserver) {
  69898. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69899. }
  69900. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69901. },
  69902. enumerable: true,
  69903. configurable: true
  69904. });
  69905. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69906. set: function (callback) {
  69907. if (this._onClearObserver) {
  69908. this.onClearObservable.remove(this._onClearObserver);
  69909. }
  69910. this._onClearObserver = this.onClearObservable.add(callback);
  69911. },
  69912. enumerable: true,
  69913. configurable: true
  69914. });
  69915. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69916. get: function () {
  69917. return this._renderTargetOptions;
  69918. },
  69919. enumerable: true,
  69920. configurable: true
  69921. });
  69922. RenderTargetTexture.prototype._onRatioRescale = function () {
  69923. if (this._sizeRatio) {
  69924. this.resize(this._initialSizeParameter);
  69925. }
  69926. };
  69927. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69928. get: function () {
  69929. return this._boundingBoxSize;
  69930. },
  69931. /**
  69932. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69933. * When defined, the cubemap will switch to local mode
  69934. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69935. * @example https://www.babylonjs-playground.com/#RNASML
  69936. */
  69937. set: function (value) {
  69938. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69939. return;
  69940. }
  69941. this._boundingBoxSize = value;
  69942. var scene = this.getScene();
  69943. if (scene) {
  69944. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69945. }
  69946. },
  69947. enumerable: true,
  69948. configurable: true
  69949. });
  69950. /**
  69951. * Creates a depth stencil texture.
  69952. * This is only available in WebGL 2 or with the depth texture extension available.
  69953. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69954. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69955. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69956. */
  69957. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69958. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69959. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69960. if (generateStencil === void 0) { generateStencil = false; }
  69961. if (!this.getScene()) {
  69962. return;
  69963. }
  69964. var engine = this.getScene().getEngine();
  69965. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69966. bilinearFiltering: bilinearFiltering,
  69967. comparisonFunction: comparisonFunction,
  69968. generateStencil: generateStencil,
  69969. isCube: this.isCube
  69970. });
  69971. engine.setFrameBufferDepthStencilTexture(this);
  69972. };
  69973. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69974. if (size.ratio) {
  69975. this._sizeRatio = size.ratio;
  69976. this._size = {
  69977. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69978. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69979. };
  69980. }
  69981. else {
  69982. this._size = size;
  69983. }
  69984. };
  69985. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69986. get: function () {
  69987. return this._samples;
  69988. },
  69989. set: function (value) {
  69990. if (this._samples === value) {
  69991. return;
  69992. }
  69993. var scene = this.getScene();
  69994. if (!scene) {
  69995. return;
  69996. }
  69997. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69998. },
  69999. enumerable: true,
  70000. configurable: true
  70001. });
  70002. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  70003. this._currentRefreshId = -1;
  70004. };
  70005. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  70006. get: function () {
  70007. return this._refreshRate;
  70008. },
  70009. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70010. set: function (value) {
  70011. this._refreshRate = value;
  70012. this.resetRefreshCounter();
  70013. },
  70014. enumerable: true,
  70015. configurable: true
  70016. });
  70017. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  70018. if (!this._postProcessManager) {
  70019. var scene = this.getScene();
  70020. if (!scene) {
  70021. return;
  70022. }
  70023. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  70024. this._postProcesses = new Array();
  70025. }
  70026. this._postProcesses.push(postProcess);
  70027. this._postProcesses[0].autoClear = false;
  70028. };
  70029. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70030. if (!this._postProcesses) {
  70031. return;
  70032. }
  70033. if (dispose) {
  70034. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70035. var postProcess = _a[_i];
  70036. postProcess.dispose();
  70037. }
  70038. }
  70039. this._postProcesses = [];
  70040. };
  70041. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70042. if (!this._postProcesses) {
  70043. return;
  70044. }
  70045. var index = this._postProcesses.indexOf(postProcess);
  70046. if (index === -1) {
  70047. return;
  70048. }
  70049. this._postProcesses.splice(index, 1);
  70050. if (this._postProcesses.length > 0) {
  70051. this._postProcesses[0].autoClear = false;
  70052. }
  70053. };
  70054. /** @hidden */
  70055. RenderTargetTexture.prototype._shouldRender = function () {
  70056. if (this._currentRefreshId === -1) { // At least render once
  70057. this._currentRefreshId = 1;
  70058. return true;
  70059. }
  70060. if (this.refreshRate === this._currentRefreshId) {
  70061. this._currentRefreshId = 1;
  70062. return true;
  70063. }
  70064. this._currentRefreshId++;
  70065. return false;
  70066. };
  70067. RenderTargetTexture.prototype.getRenderSize = function () {
  70068. if (this._size.width) {
  70069. return this._size.width;
  70070. }
  70071. return this._size;
  70072. };
  70073. RenderTargetTexture.prototype.getRenderWidth = function () {
  70074. if (this._size.width) {
  70075. return this._size.width;
  70076. }
  70077. return this._size;
  70078. };
  70079. RenderTargetTexture.prototype.getRenderHeight = function () {
  70080. if (this._size.width) {
  70081. return this._size.height;
  70082. }
  70083. return this._size;
  70084. };
  70085. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  70086. get: function () {
  70087. return true;
  70088. },
  70089. enumerable: true,
  70090. configurable: true
  70091. });
  70092. RenderTargetTexture.prototype.scale = function (ratio) {
  70093. var newSize = this.getRenderSize() * ratio;
  70094. this.resize(newSize);
  70095. };
  70096. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  70097. if (this.isCube) {
  70098. return this._textureMatrix;
  70099. }
  70100. return _super.prototype.getReflectionTextureMatrix.call(this);
  70101. };
  70102. RenderTargetTexture.prototype.resize = function (size) {
  70103. this.releaseInternalTexture();
  70104. var scene = this.getScene();
  70105. if (!scene) {
  70106. return;
  70107. }
  70108. this._processSizeParameter(size);
  70109. if (this.isCube) {
  70110. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  70111. }
  70112. else {
  70113. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  70114. }
  70115. };
  70116. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  70117. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  70118. if (dumpForDebug === void 0) { dumpForDebug = false; }
  70119. var scene = this.getScene();
  70120. if (!scene) {
  70121. return;
  70122. }
  70123. var engine = scene.getEngine();
  70124. if (this.useCameraPostProcesses !== undefined) {
  70125. useCameraPostProcess = this.useCameraPostProcesses;
  70126. }
  70127. if (this._waitingRenderList) {
  70128. this.renderList = [];
  70129. for (var index = 0; index < this._waitingRenderList.length; index++) {
  70130. var id = this._waitingRenderList[index];
  70131. var mesh_1 = scene.getMeshByID(id);
  70132. if (mesh_1) {
  70133. this.renderList.push(mesh_1);
  70134. }
  70135. }
  70136. delete this._waitingRenderList;
  70137. }
  70138. // Is predicate defined?
  70139. if (this.renderListPredicate) {
  70140. if (this.renderList) {
  70141. this.renderList.splice(0); // Clear previous renderList
  70142. }
  70143. else {
  70144. this.renderList = [];
  70145. }
  70146. var scene = this.getScene();
  70147. if (!scene) {
  70148. return;
  70149. }
  70150. var sceneMeshes = scene.meshes;
  70151. for (var index = 0; index < sceneMeshes.length; index++) {
  70152. var mesh = sceneMeshes[index];
  70153. if (this.renderListPredicate(mesh)) {
  70154. this.renderList.push(mesh);
  70155. }
  70156. }
  70157. }
  70158. this.onBeforeBindObservable.notifyObservers(this);
  70159. // Set custom projection.
  70160. // Needs to be before binding to prevent changing the aspect ratio.
  70161. var camera;
  70162. if (this.activeCamera) {
  70163. camera = this.activeCamera;
  70164. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70165. if (this.activeCamera !== scene.activeCamera) {
  70166. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  70167. }
  70168. }
  70169. else {
  70170. camera = scene.activeCamera;
  70171. if (camera) {
  70172. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70173. }
  70174. }
  70175. // Prepare renderingManager
  70176. this._renderingManager.reset();
  70177. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  70178. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  70179. var sceneRenderId = scene.getRenderId();
  70180. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  70181. var mesh = currentRenderList[meshIndex];
  70182. if (mesh) {
  70183. if (!mesh.isReady(this.refreshRate === 0)) {
  70184. this.resetRefreshCounter();
  70185. continue;
  70186. }
  70187. mesh._preActivateForIntermediateRendering(sceneRenderId);
  70188. var isMasked = void 0;
  70189. if (!this.renderList && camera) {
  70190. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  70191. }
  70192. else {
  70193. isMasked = false;
  70194. }
  70195. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  70196. mesh._activate(sceneRenderId);
  70197. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  70198. var subMesh = mesh.subMeshes[subIndex];
  70199. scene._activeIndices.addCount(subMesh.indexCount, false);
  70200. this._renderingManager.dispatch(subMesh, mesh);
  70201. }
  70202. }
  70203. }
  70204. }
  70205. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  70206. var particleSystem = scene.particleSystems[particleIndex];
  70207. var emitter = particleSystem.emitter;
  70208. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  70209. continue;
  70210. }
  70211. if (currentRenderList.indexOf(emitter) >= 0) {
  70212. this._renderingManager.dispatchParticles(particleSystem);
  70213. }
  70214. }
  70215. if (this.isCube) {
  70216. for (var face = 0; face < 6; face++) {
  70217. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70218. scene.incrementRenderId();
  70219. scene.resetCachedMaterial();
  70220. }
  70221. }
  70222. else {
  70223. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70224. }
  70225. this.onAfterUnbindObservable.notifyObservers(this);
  70226. if (scene.activeCamera) {
  70227. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  70228. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  70229. }
  70230. engine.setViewport(scene.activeCamera.viewport);
  70231. }
  70232. scene.resetCachedMaterial();
  70233. };
  70234. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  70235. var minimum = 128;
  70236. var x = renderDimension * scale;
  70237. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  70238. // Ensure we don't exceed the render dimension (while staying POT)
  70239. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  70240. };
  70241. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70242. var _this = this;
  70243. if (!this._texture) {
  70244. return;
  70245. }
  70246. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  70247. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70248. });
  70249. };
  70250. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  70251. var scene = this.getScene();
  70252. if (!scene) {
  70253. return;
  70254. }
  70255. var engine = scene.getEngine();
  70256. if (!this._texture) {
  70257. return;
  70258. }
  70259. // Bind
  70260. if (this._postProcessManager) {
  70261. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  70262. }
  70263. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  70264. if (this._texture) {
  70265. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  70266. }
  70267. }
  70268. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  70269. // Clear
  70270. if (this.onClearObservable.hasObservers()) {
  70271. this.onClearObservable.notifyObservers(engine);
  70272. }
  70273. else {
  70274. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  70275. }
  70276. if (!this._doNotChangeAspectRatio) {
  70277. scene.updateTransformMatrix(true);
  70278. }
  70279. // Render
  70280. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  70281. if (this._postProcessManager) {
  70282. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  70283. }
  70284. else if (useCameraPostProcess) {
  70285. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  70286. }
  70287. if (!this._doNotChangeAspectRatio) {
  70288. scene.updateTransformMatrix(true);
  70289. }
  70290. // Dump ?
  70291. if (dumpForDebug) {
  70292. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  70293. }
  70294. // Unbind
  70295. if (!this.isCube || faceIndex === 5) {
  70296. if (this.isCube) {
  70297. if (faceIndex === 5) {
  70298. engine.generateMipMapsForCubemap(this._texture);
  70299. }
  70300. }
  70301. this.unbindFrameBuffer(engine, faceIndex);
  70302. }
  70303. else {
  70304. this.onAfterRenderObservable.notifyObservers(faceIndex);
  70305. }
  70306. };
  70307. /**
  70308. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  70309. * This allowed control for front to back rendering or reversly depending of the special needs.
  70310. *
  70311. * @param renderingGroupId The rendering group id corresponding to its index
  70312. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  70313. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70314. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70315. */
  70316. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70317. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70318. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70319. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70320. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70321. };
  70322. /**
  70323. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70324. *
  70325. * @param renderingGroupId The rendering group id corresponding to its index
  70326. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70327. */
  70328. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70329. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70330. this._renderingManager._useSceneAutoClearSetup = false;
  70331. };
  70332. RenderTargetTexture.prototype.clone = function () {
  70333. var textureSize = this.getSize();
  70334. 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);
  70335. // Base texture
  70336. newTexture.hasAlpha = this.hasAlpha;
  70337. newTexture.level = this.level;
  70338. // RenderTarget Texture
  70339. newTexture.coordinatesMode = this.coordinatesMode;
  70340. if (this.renderList) {
  70341. newTexture.renderList = this.renderList.slice(0);
  70342. }
  70343. return newTexture;
  70344. };
  70345. RenderTargetTexture.prototype.serialize = function () {
  70346. if (!this.name) {
  70347. return null;
  70348. }
  70349. var serializationObject = _super.prototype.serialize.call(this);
  70350. serializationObject.renderTargetSize = this.getRenderSize();
  70351. serializationObject.renderList = [];
  70352. if (this.renderList) {
  70353. for (var index = 0; index < this.renderList.length; index++) {
  70354. serializationObject.renderList.push(this.renderList[index].id);
  70355. }
  70356. }
  70357. return serializationObject;
  70358. };
  70359. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70360. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70361. var objBuffer = this.getInternalTexture();
  70362. var scene = this.getScene();
  70363. if (objBuffer && scene) {
  70364. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70365. }
  70366. };
  70367. RenderTargetTexture.prototype.dispose = function () {
  70368. if (this._postProcessManager) {
  70369. this._postProcessManager.dispose();
  70370. this._postProcessManager = null;
  70371. }
  70372. this.clearPostProcesses(true);
  70373. if (this._resizeObserver) {
  70374. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70375. this._resizeObserver = null;
  70376. }
  70377. this.renderList = null;
  70378. // Remove from custom render targets
  70379. var scene = this.getScene();
  70380. if (!scene) {
  70381. return;
  70382. }
  70383. var index = scene.customRenderTargets.indexOf(this);
  70384. if (index >= 0) {
  70385. scene.customRenderTargets.splice(index, 1);
  70386. }
  70387. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70388. var camera = _a[_i];
  70389. index = camera.customRenderTargets.indexOf(this);
  70390. if (index >= 0) {
  70391. camera.customRenderTargets.splice(index, 1);
  70392. }
  70393. }
  70394. _super.prototype.dispose.call(this);
  70395. };
  70396. /** @hidden */
  70397. RenderTargetTexture.prototype._rebuild = function () {
  70398. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70399. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70400. }
  70401. if (this._postProcessManager) {
  70402. this._postProcessManager._rebuild();
  70403. }
  70404. };
  70405. /**
  70406. * Clear the info related to rendering groups preventing retention point in material dispose.
  70407. */
  70408. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70409. if (this._renderingManager) {
  70410. this._renderingManager.freeRenderingGroups();
  70411. }
  70412. };
  70413. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70414. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70415. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70416. return RenderTargetTexture;
  70417. }(BABYLON.Texture));
  70418. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70419. })(BABYLON || (BABYLON = {}));
  70420. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70421. var BABYLON;
  70422. (function (BABYLON) {
  70423. ;
  70424. var MultiRenderTarget = /** @class */ (function (_super) {
  70425. __extends(MultiRenderTarget, _super);
  70426. function MultiRenderTarget(name, size, count, scene, options) {
  70427. var _this = this;
  70428. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70429. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70430. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70431. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70432. _this._engine = scene.getEngine();
  70433. if (!_this.isSupported) {
  70434. _this.dispose();
  70435. return;
  70436. }
  70437. var types = [];
  70438. var samplingModes = [];
  70439. for (var i = 0; i < count; i++) {
  70440. if (options && options.types && options.types[i] !== undefined) {
  70441. types.push(options.types[i]);
  70442. }
  70443. else {
  70444. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70445. }
  70446. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70447. samplingModes.push(options.samplingModes[i]);
  70448. }
  70449. else {
  70450. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70451. }
  70452. }
  70453. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70454. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70455. _this._size = size;
  70456. _this._multiRenderTargetOptions = {
  70457. samplingModes: samplingModes,
  70458. generateMipMaps: generateMipMaps,
  70459. generateDepthBuffer: generateDepthBuffer,
  70460. generateStencilBuffer: generateStencilBuffer,
  70461. generateDepthTexture: generateDepthTexture,
  70462. types: types,
  70463. textureCount: count
  70464. };
  70465. _this._createInternalTextures();
  70466. _this._createTextures();
  70467. return _this;
  70468. }
  70469. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70470. get: function () {
  70471. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70472. },
  70473. enumerable: true,
  70474. configurable: true
  70475. });
  70476. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70477. get: function () {
  70478. return this._textures;
  70479. },
  70480. enumerable: true,
  70481. configurable: true
  70482. });
  70483. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70484. get: function () {
  70485. return this._textures[this._textures.length - 1];
  70486. },
  70487. enumerable: true,
  70488. configurable: true
  70489. });
  70490. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70491. set: function (wrap) {
  70492. if (this._textures) {
  70493. for (var i = 0; i < this._textures.length; i++) {
  70494. this._textures[i].wrapU = wrap;
  70495. }
  70496. }
  70497. },
  70498. enumerable: true,
  70499. configurable: true
  70500. });
  70501. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70502. set: function (wrap) {
  70503. if (this._textures) {
  70504. for (var i = 0; i < this._textures.length; i++) {
  70505. this._textures[i].wrapV = wrap;
  70506. }
  70507. }
  70508. },
  70509. enumerable: true,
  70510. configurable: true
  70511. });
  70512. /** @hidden */
  70513. MultiRenderTarget.prototype._rebuild = function () {
  70514. this.releaseInternalTextures();
  70515. this._createInternalTextures();
  70516. for (var i = 0; i < this._internalTextures.length; i++) {
  70517. var texture = this._textures[i];
  70518. texture._texture = this._internalTextures[i];
  70519. }
  70520. // Keeps references to frame buffer and stencil/depth buffer
  70521. this._texture = this._internalTextures[0];
  70522. };
  70523. MultiRenderTarget.prototype._createInternalTextures = function () {
  70524. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70525. };
  70526. MultiRenderTarget.prototype._createTextures = function () {
  70527. this._textures = [];
  70528. for (var i = 0; i < this._internalTextures.length; i++) {
  70529. var texture = new BABYLON.Texture(null, this.getScene());
  70530. texture._texture = this._internalTextures[i];
  70531. this._textures.push(texture);
  70532. }
  70533. // Keeps references to frame buffer and stencil/depth buffer
  70534. this._texture = this._internalTextures[0];
  70535. };
  70536. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70537. get: function () {
  70538. return this._samples;
  70539. },
  70540. set: function (value) {
  70541. if (this._samples === value) {
  70542. return;
  70543. }
  70544. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70545. },
  70546. enumerable: true,
  70547. configurable: true
  70548. });
  70549. MultiRenderTarget.prototype.resize = function (size) {
  70550. this.releaseInternalTextures();
  70551. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70552. this._createInternalTextures();
  70553. };
  70554. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70555. var _this = this;
  70556. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70557. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70558. });
  70559. };
  70560. MultiRenderTarget.prototype.dispose = function () {
  70561. this.releaseInternalTextures();
  70562. _super.prototype.dispose.call(this);
  70563. };
  70564. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70565. if (!this._internalTextures) {
  70566. return;
  70567. }
  70568. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70569. if (this._internalTextures[i] !== undefined) {
  70570. this._internalTextures[i].dispose();
  70571. this._internalTextures.splice(i, 1);
  70572. }
  70573. }
  70574. };
  70575. return MultiRenderTarget;
  70576. }(BABYLON.RenderTargetTexture));
  70577. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70578. })(BABYLON || (BABYLON = {}));
  70579. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70580. var BABYLON;
  70581. (function (BABYLON) {
  70582. var MirrorTexture = /** @class */ (function (_super) {
  70583. __extends(MirrorTexture, _super);
  70584. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70585. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70587. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70588. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70589. _this.scene = scene;
  70590. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70591. _this._transformMatrix = BABYLON.Matrix.Zero();
  70592. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70593. _this._adaptiveBlurKernel = 0;
  70594. _this._blurKernelX = 0;
  70595. _this._blurKernelY = 0;
  70596. _this._blurRatio = 1.0;
  70597. _this.ignoreCameraViewport = true;
  70598. _this._updateGammaSpace();
  70599. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70600. _this._updateGammaSpace;
  70601. });
  70602. _this.onBeforeRenderObservable.add(function () {
  70603. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70604. _this._savedViewMatrix = scene.getViewMatrix();
  70605. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70606. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70607. scene.clipPlane = _this.mirrorPlane;
  70608. scene.getEngine().cullBackFaces = false;
  70609. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70610. });
  70611. _this.onAfterRenderObservable.add(function () {
  70612. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70613. scene.getEngine().cullBackFaces = true;
  70614. scene._mirroredCameraPosition = null;
  70615. delete scene.clipPlane;
  70616. });
  70617. return _this;
  70618. }
  70619. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70620. get: function () {
  70621. return this._blurRatio;
  70622. },
  70623. set: function (value) {
  70624. if (this._blurRatio === value) {
  70625. return;
  70626. }
  70627. this._blurRatio = value;
  70628. this._preparePostProcesses();
  70629. },
  70630. enumerable: true,
  70631. configurable: true
  70632. });
  70633. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70634. set: function (value) {
  70635. this._adaptiveBlurKernel = value;
  70636. this._autoComputeBlurKernel();
  70637. },
  70638. enumerable: true,
  70639. configurable: true
  70640. });
  70641. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70642. set: function (value) {
  70643. this.blurKernelX = value;
  70644. this.blurKernelY = value;
  70645. },
  70646. enumerable: true,
  70647. configurable: true
  70648. });
  70649. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70650. get: function () {
  70651. return this._blurKernelX;
  70652. },
  70653. set: function (value) {
  70654. if (this._blurKernelX === value) {
  70655. return;
  70656. }
  70657. this._blurKernelX = value;
  70658. this._preparePostProcesses();
  70659. },
  70660. enumerable: true,
  70661. configurable: true
  70662. });
  70663. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70664. get: function () {
  70665. return this._blurKernelY;
  70666. },
  70667. set: function (value) {
  70668. if (this._blurKernelY === value) {
  70669. return;
  70670. }
  70671. this._blurKernelY = value;
  70672. this._preparePostProcesses();
  70673. },
  70674. enumerable: true,
  70675. configurable: true
  70676. });
  70677. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70678. var engine = this.getScene().getEngine();
  70679. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70680. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70681. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70682. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70683. };
  70684. MirrorTexture.prototype._onRatioRescale = function () {
  70685. if (this._sizeRatio) {
  70686. this.resize(this._initialSizeParameter);
  70687. if (!this._adaptiveBlurKernel) {
  70688. this._preparePostProcesses();
  70689. }
  70690. }
  70691. if (this._adaptiveBlurKernel) {
  70692. this._autoComputeBlurKernel();
  70693. }
  70694. };
  70695. MirrorTexture.prototype._updateGammaSpace = function () {
  70696. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70697. };
  70698. MirrorTexture.prototype._preparePostProcesses = function () {
  70699. this.clearPostProcesses(true);
  70700. if (this._blurKernelX && this._blurKernelY) {
  70701. var engine = this.getScene().getEngine();
  70702. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70703. 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);
  70704. this._blurX.autoClear = false;
  70705. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70706. this._blurX.inputTexture = this._texture;
  70707. }
  70708. else {
  70709. this._blurX.alwaysForcePOT = true;
  70710. }
  70711. 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);
  70712. this._blurY.autoClear = false;
  70713. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70714. this.addPostProcess(this._blurX);
  70715. this.addPostProcess(this._blurY);
  70716. }
  70717. else {
  70718. if (this._blurY) {
  70719. this.removePostProcess(this._blurY);
  70720. this._blurY.dispose();
  70721. this._blurY = null;
  70722. }
  70723. if (this._blurX) {
  70724. this.removePostProcess(this._blurX);
  70725. this._blurX.dispose();
  70726. this._blurX = null;
  70727. }
  70728. }
  70729. };
  70730. MirrorTexture.prototype.clone = function () {
  70731. var scene = this.getScene();
  70732. if (!scene) {
  70733. return this;
  70734. }
  70735. var textureSize = this.getSize();
  70736. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70737. // Base texture
  70738. newTexture.hasAlpha = this.hasAlpha;
  70739. newTexture.level = this.level;
  70740. // Mirror Texture
  70741. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70742. if (this.renderList) {
  70743. newTexture.renderList = this.renderList.slice(0);
  70744. }
  70745. return newTexture;
  70746. };
  70747. MirrorTexture.prototype.serialize = function () {
  70748. if (!this.name) {
  70749. return null;
  70750. }
  70751. var serializationObject = _super.prototype.serialize.call(this);
  70752. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70753. return serializationObject;
  70754. };
  70755. MirrorTexture.prototype.dispose = function () {
  70756. _super.prototype.dispose.call(this);
  70757. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70758. };
  70759. return MirrorTexture;
  70760. }(BABYLON.RenderTargetTexture));
  70761. BABYLON.MirrorTexture = MirrorTexture;
  70762. })(BABYLON || (BABYLON = {}));
  70763. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70764. var BABYLON;
  70765. (function (BABYLON) {
  70766. /**
  70767. * Creates a refraction texture used by refraction channel of the standard material.
  70768. * @param name the texture name
  70769. * @param size size of the underlying texture
  70770. * @param scene root scene
  70771. */
  70772. var RefractionTexture = /** @class */ (function (_super) {
  70773. __extends(RefractionTexture, _super);
  70774. function RefractionTexture(name, size, scene, generateMipMaps) {
  70775. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70776. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70777. _this.depth = 2.0;
  70778. _this.onBeforeRenderObservable.add(function () {
  70779. scene.clipPlane = _this.refractionPlane;
  70780. });
  70781. _this.onAfterRenderObservable.add(function () {
  70782. delete scene.clipPlane;
  70783. });
  70784. return _this;
  70785. }
  70786. RefractionTexture.prototype.clone = function () {
  70787. var scene = this.getScene();
  70788. if (!scene) {
  70789. return this;
  70790. }
  70791. var textureSize = this.getSize();
  70792. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70793. // Base texture
  70794. newTexture.hasAlpha = this.hasAlpha;
  70795. newTexture.level = this.level;
  70796. // Refraction Texture
  70797. newTexture.refractionPlane = this.refractionPlane.clone();
  70798. if (this.renderList) {
  70799. newTexture.renderList = this.renderList.slice(0);
  70800. }
  70801. newTexture.depth = this.depth;
  70802. return newTexture;
  70803. };
  70804. RefractionTexture.prototype.serialize = function () {
  70805. if (!this.name) {
  70806. return null;
  70807. }
  70808. var serializationObject = _super.prototype.serialize.call(this);
  70809. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70810. serializationObject.depth = this.depth;
  70811. return serializationObject;
  70812. };
  70813. return RefractionTexture;
  70814. }(BABYLON.RenderTargetTexture));
  70815. BABYLON.RefractionTexture = RefractionTexture;
  70816. })(BABYLON || (BABYLON = {}));
  70817. //# sourceMappingURL=babylon.refractionTexture.js.map
  70818. var BABYLON;
  70819. (function (BABYLON) {
  70820. /**
  70821. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70822. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70823. */
  70824. var DynamicTexture = /** @class */ (function (_super) {
  70825. __extends(DynamicTexture, _super);
  70826. /**
  70827. * Creates a {BABYLON.DynamicTexture}
  70828. * @param name defines the name of the texture
  70829. * @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
  70830. * @param scene defines the scene where you want the texture
  70831. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70832. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70833. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70834. */
  70835. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70836. if (scene === void 0) { scene = null; }
  70837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70838. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70839. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70840. _this.name = name;
  70841. _this._engine = _this.getScene().getEngine();
  70842. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70843. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70844. _this._generateMipMaps = generateMipMaps;
  70845. if (options.getContext) {
  70846. _this._canvas = options;
  70847. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70848. }
  70849. else {
  70850. _this._canvas = document.createElement("canvas");
  70851. if (options.width || options.width === 0) {
  70852. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70853. }
  70854. else {
  70855. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70856. }
  70857. }
  70858. var textureSize = _this.getSize();
  70859. _this._canvas.width = textureSize.width;
  70860. _this._canvas.height = textureSize.height;
  70861. _this._context = _this._canvas.getContext("2d");
  70862. return _this;
  70863. }
  70864. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70865. /**
  70866. * Gets the current state of canRescale
  70867. */
  70868. get: function () {
  70869. return true;
  70870. },
  70871. enumerable: true,
  70872. configurable: true
  70873. });
  70874. DynamicTexture.prototype._recreate = function (textureSize) {
  70875. this._canvas.width = textureSize.width;
  70876. this._canvas.height = textureSize.height;
  70877. this.releaseInternalTexture();
  70878. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70879. };
  70880. /**
  70881. * Scales the texture
  70882. * @param ratio the scale factor to apply to both width and height
  70883. */
  70884. DynamicTexture.prototype.scale = function (ratio) {
  70885. var textureSize = this.getSize();
  70886. textureSize.width *= ratio;
  70887. textureSize.height *= ratio;
  70888. this._recreate(textureSize);
  70889. };
  70890. /**
  70891. * Resizes the texture
  70892. * @param width the new width
  70893. * @param height the new height
  70894. */
  70895. DynamicTexture.prototype.scaleTo = function (width, height) {
  70896. var textureSize = this.getSize();
  70897. textureSize.width = width;
  70898. textureSize.height = height;
  70899. this._recreate(textureSize);
  70900. };
  70901. /**
  70902. * Gets the context of the canvas used by the texture
  70903. * @returns the canvas context of the dynamic texture
  70904. */
  70905. DynamicTexture.prototype.getContext = function () {
  70906. return this._context;
  70907. };
  70908. /**
  70909. * Clears the texture
  70910. */
  70911. DynamicTexture.prototype.clear = function () {
  70912. var size = this.getSize();
  70913. this._context.fillRect(0, 0, size.width, size.height);
  70914. };
  70915. /**
  70916. * Updates the texture
  70917. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70918. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70919. */
  70920. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70921. if (premulAlpha === void 0) { premulAlpha = false; }
  70922. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70923. };
  70924. /**
  70925. * Draws text onto the texture
  70926. * @param text defines the text to be drawn
  70927. * @param x defines the placement of the text from the left
  70928. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70929. * @param font defines the font to be used with font-style, font-size, font-name
  70930. * @param color defines the color used for the text
  70931. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70932. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70933. * @param update defines whether texture is immediately update (default is true)
  70934. */
  70935. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70936. if (update === void 0) { update = true; }
  70937. var size = this.getSize();
  70938. if (clearColor) {
  70939. this._context.fillStyle = clearColor;
  70940. this._context.fillRect(0, 0, size.width, size.height);
  70941. }
  70942. this._context.font = font;
  70943. if (x === null || x === undefined) {
  70944. var textSize = this._context.measureText(text);
  70945. x = (size.width - textSize.width) / 2;
  70946. }
  70947. if (y === null || y === undefined) {
  70948. var fontSize = parseInt((font.replace(/\D/g, '')));
  70949. y = (size.height / 2) + (fontSize / 3.65);
  70950. }
  70951. this._context.fillStyle = color;
  70952. this._context.fillText(text, x, y);
  70953. if (update) {
  70954. this.update(invertY);
  70955. }
  70956. };
  70957. /**
  70958. * Clones the texture
  70959. * @returns the clone of the texture.
  70960. */
  70961. DynamicTexture.prototype.clone = function () {
  70962. var scene = this.getScene();
  70963. if (!scene) {
  70964. return this;
  70965. }
  70966. var textureSize = this.getSize();
  70967. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70968. // Base texture
  70969. newTexture.hasAlpha = this.hasAlpha;
  70970. newTexture.level = this.level;
  70971. // Dynamic Texture
  70972. newTexture.wrapU = this.wrapU;
  70973. newTexture.wrapV = this.wrapV;
  70974. return newTexture;
  70975. };
  70976. /**
  70977. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70978. * @returns a serialized dynamic texture object
  70979. */
  70980. DynamicTexture.prototype.serialize = function () {
  70981. var scene = this.getScene();
  70982. if (scene && !scene.isReady()) {
  70983. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70984. }
  70985. var serializationObject = _super.prototype.serialize.call(this);
  70986. serializationObject.base64String = this._canvas.toDataURL();
  70987. serializationObject.invertY = this._invertY;
  70988. serializationObject.samplingMode = this.samplingMode;
  70989. return serializationObject;
  70990. };
  70991. /** @hidden */
  70992. DynamicTexture.prototype._rebuild = function () {
  70993. this.update();
  70994. };
  70995. return DynamicTexture;
  70996. }(BABYLON.Texture));
  70997. BABYLON.DynamicTexture = DynamicTexture;
  70998. })(BABYLON || (BABYLON = {}));
  70999. //# sourceMappingURL=babylon.dynamicTexture.js.map
  71000. var BABYLON;
  71001. (function (BABYLON) {
  71002. var VideoTexture = /** @class */ (function (_super) {
  71003. __extends(VideoTexture, _super);
  71004. /**
  71005. * Creates a video texture.
  71006. * Sample : https://doc.babylonjs.com/how_to/video_texture
  71007. * @param {string | null} name optional name, will detect from video source, if not defined
  71008. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  71009. * @param {BABYLON.Scene} scene is obviously the current scene.
  71010. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  71011. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  71012. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  71013. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  71014. */
  71015. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  71016. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71017. if (invertY === void 0) { invertY = false; }
  71018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71019. if (settings === void 0) { settings = {
  71020. autoPlay: true,
  71021. loop: true,
  71022. autoUpdateTexture: true,
  71023. }; }
  71024. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71025. _this._onUserActionRequestedObservable = null;
  71026. _this._stillImageCaptured = false;
  71027. _this._poster = false;
  71028. _this._createInternalTexture = function () {
  71029. if (_this._texture != null) {
  71030. if (_this._poster) {
  71031. _this._texture.dispose();
  71032. _this._poster = false;
  71033. }
  71034. else {
  71035. return;
  71036. }
  71037. }
  71038. if (!_this._engine.needPOTTextures ||
  71039. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71040. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71041. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71042. }
  71043. else {
  71044. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71045. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71046. _this._generateMipMaps = false;
  71047. }
  71048. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71049. if (!_this.video.autoplay) {
  71050. var oldHandler_1 = _this.video.onplaying;
  71051. var error_1 = false;
  71052. _this.video.onplaying = function () {
  71053. _this.video.onplaying = oldHandler_1;
  71054. _this._texture.isReady = true;
  71055. _this._updateInternalTexture();
  71056. if (!error_1) {
  71057. _this.video.pause();
  71058. }
  71059. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71060. _this.onLoadObservable.notifyObservers(_this);
  71061. }
  71062. };
  71063. var playing = _this.video.play();
  71064. if (playing) {
  71065. playing.then(function () {
  71066. // Everything is good.
  71067. })
  71068. .catch(function () {
  71069. error_1 = true;
  71070. // On Chrome for instance, new policies might prevent playing without user interaction.
  71071. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  71072. _this._onUserActionRequestedObservable.notifyObservers(_this);
  71073. }
  71074. });
  71075. }
  71076. else {
  71077. _this.video.onplaying = oldHandler_1;
  71078. _this._texture.isReady = true;
  71079. _this._updateInternalTexture();
  71080. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71081. _this.onLoadObservable.notifyObservers(_this);
  71082. }
  71083. }
  71084. }
  71085. else {
  71086. _this._texture.isReady = true;
  71087. _this._updateInternalTexture();
  71088. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71089. _this.onLoadObservable.notifyObservers(_this);
  71090. }
  71091. }
  71092. };
  71093. _this.reset = function () {
  71094. if (_this._texture == null) {
  71095. return;
  71096. }
  71097. if (!_this._poster) {
  71098. _this._texture.dispose();
  71099. _this._texture = null;
  71100. }
  71101. };
  71102. _this._updateInternalTexture = function (e) {
  71103. if (_this._texture == null || !_this._texture.isReady) {
  71104. return;
  71105. }
  71106. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  71107. return;
  71108. }
  71109. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  71110. };
  71111. _this._engine = _this.getScene().getEngine();
  71112. _this._generateMipMaps = generateMipMaps;
  71113. _this._samplingMode = samplingMode;
  71114. _this.autoUpdateTexture = settings.autoUpdateTexture;
  71115. _this.name = name || _this._getName(src);
  71116. _this.video = _this._getVideo(src);
  71117. if (settings.poster) {
  71118. _this.video.poster = settings.poster;
  71119. }
  71120. if (settings.autoPlay !== undefined) {
  71121. _this.video.autoplay = settings.autoPlay;
  71122. }
  71123. if (settings.loop !== undefined) {
  71124. _this.video.loop = settings.loop;
  71125. }
  71126. _this.video.setAttribute("playsinline", "");
  71127. _this.video.addEventListener("canplay", _this._createInternalTexture);
  71128. _this.video.addEventListener("paused", _this._updateInternalTexture);
  71129. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  71130. _this.video.addEventListener("emptied", _this.reset);
  71131. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  71132. _this._createInternalTexture();
  71133. }
  71134. if (settings.poster) {
  71135. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  71136. _this._poster = true;
  71137. }
  71138. return _this;
  71139. }
  71140. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  71141. get: function () {
  71142. if (!this._onUserActionRequestedObservable) {
  71143. this._onUserActionRequestedObservable = new BABYLON.Observable();
  71144. }
  71145. return this._onUserActionRequestedObservable;
  71146. },
  71147. enumerable: true,
  71148. configurable: true
  71149. });
  71150. VideoTexture.prototype._getName = function (src) {
  71151. if (src instanceof HTMLVideoElement) {
  71152. return src.currentSrc;
  71153. }
  71154. if (typeof src === "object") {
  71155. return src.toString();
  71156. }
  71157. return src;
  71158. };
  71159. ;
  71160. VideoTexture.prototype._getVideo = function (src) {
  71161. if (src instanceof HTMLVideoElement) {
  71162. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  71163. return src;
  71164. }
  71165. var video = document.createElement("video");
  71166. if (typeof src === "string") {
  71167. BABYLON.Tools.SetCorsBehavior(src, video);
  71168. video.src = src;
  71169. }
  71170. else {
  71171. BABYLON.Tools.SetCorsBehavior(src[0], video);
  71172. src.forEach(function (url) {
  71173. var source = document.createElement("source");
  71174. source.src = url;
  71175. video.appendChild(source);
  71176. });
  71177. }
  71178. return video;
  71179. };
  71180. ;
  71181. /**
  71182. * @hidden Internal method to initiate `update`.
  71183. */
  71184. VideoTexture.prototype._rebuild = function () {
  71185. this.update();
  71186. };
  71187. /**
  71188. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  71189. */
  71190. VideoTexture.prototype.update = function () {
  71191. if (!this.autoUpdateTexture) {
  71192. // Expecting user to call `updateTexture` manually
  71193. return;
  71194. }
  71195. this.updateTexture(true);
  71196. };
  71197. /**
  71198. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  71199. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  71200. */
  71201. VideoTexture.prototype.updateTexture = function (isVisible) {
  71202. if (!isVisible) {
  71203. return;
  71204. }
  71205. if (this.video.paused && this._stillImageCaptured) {
  71206. return;
  71207. }
  71208. this._stillImageCaptured = true;
  71209. this._updateInternalTexture();
  71210. };
  71211. /**
  71212. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  71213. * @param url New url.
  71214. */
  71215. VideoTexture.prototype.updateURL = function (url) {
  71216. this.video.src = url;
  71217. };
  71218. VideoTexture.prototype.dispose = function () {
  71219. _super.prototype.dispose.call(this);
  71220. if (this._onUserActionRequestedObservable) {
  71221. this._onUserActionRequestedObservable.clear();
  71222. this._onUserActionRequestedObservable = null;
  71223. }
  71224. this.video.removeEventListener("canplay", this._createInternalTexture);
  71225. this.video.removeEventListener("paused", this._updateInternalTexture);
  71226. this.video.removeEventListener("seeked", this._updateInternalTexture);
  71227. this.video.removeEventListener("emptied", this.reset);
  71228. this.video.pause();
  71229. };
  71230. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  71231. var video = document.createElement("video");
  71232. video.setAttribute('autoplay', '');
  71233. video.setAttribute('muted', '');
  71234. video.setAttribute('playsinline', '');
  71235. var constraintsDeviceId;
  71236. if (constraints && constraints.deviceId) {
  71237. constraintsDeviceId = {
  71238. exact: constraints.deviceId,
  71239. };
  71240. }
  71241. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  71242. if (navigator.mediaDevices) {
  71243. navigator.mediaDevices.getUserMedia({ video: constraints })
  71244. .then(function (stream) {
  71245. if (video.mozSrcObject !== undefined) {
  71246. // hack for Firefox < 19
  71247. video.mozSrcObject = stream;
  71248. }
  71249. else {
  71250. video.srcObject = stream;
  71251. }
  71252. var onPlaying = function () {
  71253. if (onReady) {
  71254. onReady(new VideoTexture("video", video, scene, true, true));
  71255. }
  71256. video.removeEventListener("playing", onPlaying);
  71257. };
  71258. video.addEventListener("playing", onPlaying);
  71259. video.play();
  71260. })
  71261. .catch(function (err) {
  71262. BABYLON.Tools.Error(err.name);
  71263. });
  71264. }
  71265. else {
  71266. navigator.getUserMedia =
  71267. navigator.getUserMedia ||
  71268. navigator.webkitGetUserMedia ||
  71269. navigator.mozGetUserMedia ||
  71270. navigator.msGetUserMedia;
  71271. if (navigator.getUserMedia) {
  71272. navigator.getUserMedia({
  71273. video: {
  71274. deviceId: constraintsDeviceId,
  71275. width: {
  71276. min: (constraints && constraints.minWidth) || 256,
  71277. max: (constraints && constraints.maxWidth) || 640,
  71278. },
  71279. height: {
  71280. min: (constraints && constraints.minHeight) || 256,
  71281. max: (constraints && constraints.maxHeight) || 480,
  71282. },
  71283. },
  71284. }, function (stream) {
  71285. if (video.mozSrcObject !== undefined) {
  71286. // hack for Firefox < 19
  71287. video.mozSrcObject = stream;
  71288. }
  71289. else {
  71290. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  71291. }
  71292. video.play();
  71293. if (onReady) {
  71294. onReady(new VideoTexture("video", video, scene, true, true));
  71295. }
  71296. }, function (e) {
  71297. BABYLON.Tools.Error(e.name);
  71298. });
  71299. }
  71300. }
  71301. };
  71302. return VideoTexture;
  71303. }(BABYLON.Texture));
  71304. BABYLON.VideoTexture = VideoTexture;
  71305. })(BABYLON || (BABYLON = {}));
  71306. //# sourceMappingURL=babylon.videoTexture.js.map
  71307. var BABYLON;
  71308. (function (BABYLON) {
  71309. var RawTexture = /** @class */ (function (_super) {
  71310. __extends(RawTexture, _super);
  71311. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  71312. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71313. if (invertY === void 0) { invertY = false; }
  71314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71315. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71316. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71317. _this.format = format;
  71318. _this._engine = scene.getEngine();
  71319. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71320. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71321. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71322. return _this;
  71323. }
  71324. RawTexture.prototype.update = function (data) {
  71325. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71326. };
  71327. // Statics
  71328. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71329. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71330. if (invertY === void 0) { invertY = false; }
  71331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71332. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71333. };
  71334. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71335. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71336. if (invertY === void 0) { invertY = false; }
  71337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71338. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71339. };
  71340. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71341. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71342. if (invertY === void 0) { invertY = false; }
  71343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71344. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71345. };
  71346. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71347. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71348. if (invertY === void 0) { invertY = false; }
  71349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71350. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71351. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71352. };
  71353. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71354. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71355. if (invertY === void 0) { invertY = false; }
  71356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71357. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71358. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71359. };
  71360. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71361. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71362. if (invertY === void 0) { invertY = false; }
  71363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71364. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71365. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71366. };
  71367. return RawTexture;
  71368. }(BABYLON.Texture));
  71369. BABYLON.RawTexture = RawTexture;
  71370. })(BABYLON || (BABYLON = {}));
  71371. //# sourceMappingURL=babylon.rawTexture.js.map
  71372. var BABYLON;
  71373. (function (BABYLON) {
  71374. /**
  71375. * Class used to store 3D textures containing user data
  71376. */
  71377. var RawTexture3D = /** @class */ (function (_super) {
  71378. __extends(RawTexture3D, _super);
  71379. /**
  71380. * Create a new RawTexture3D
  71381. * @param data defines the data of the texture
  71382. * @param width defines the width of the texture
  71383. * @param height defines the height of the texture
  71384. * @param depth defines the depth of the texture
  71385. * @param format defines the texture format to use
  71386. * @param scene defines the hosting scene
  71387. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71388. * @param invertY defines if texture must be stored with Y axis inverted
  71389. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71390. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71391. */
  71392. function RawTexture3D(data, width, height, depth,
  71393. /** Gets or sets the texture format to use */
  71394. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71395. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71396. if (invertY === void 0) { invertY = false; }
  71397. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71398. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71399. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71400. _this.format = format;
  71401. _this._engine = scene.getEngine();
  71402. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71403. _this.is3D = true;
  71404. return _this;
  71405. }
  71406. /**
  71407. * Update the texture with new data
  71408. * @param data defines the data to store in the texture
  71409. */
  71410. RawTexture3D.prototype.update = function (data) {
  71411. if (!this._texture) {
  71412. return;
  71413. }
  71414. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71415. };
  71416. return RawTexture3D;
  71417. }(BABYLON.Texture));
  71418. BABYLON.RawTexture3D = RawTexture3D;
  71419. })(BABYLON || (BABYLON = {}));
  71420. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71421. var BABYLON;
  71422. (function (BABYLON) {
  71423. /**
  71424. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71425. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71426. */
  71427. var PostProcessManager = /** @class */ (function () {
  71428. /**
  71429. * Creates a new instance PostProcess
  71430. * @param scene The scene that the post process is associated with.
  71431. */
  71432. function PostProcessManager(scene) {
  71433. this._vertexBuffers = {};
  71434. this._scene = scene;
  71435. }
  71436. PostProcessManager.prototype._prepareBuffers = function () {
  71437. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71438. return;
  71439. }
  71440. // VBO
  71441. var vertices = [];
  71442. vertices.push(1, 1);
  71443. vertices.push(-1, 1);
  71444. vertices.push(-1, -1);
  71445. vertices.push(1, -1);
  71446. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71447. this._buildIndexBuffer();
  71448. };
  71449. PostProcessManager.prototype._buildIndexBuffer = function () {
  71450. // Indices
  71451. var indices = [];
  71452. indices.push(0);
  71453. indices.push(1);
  71454. indices.push(2);
  71455. indices.push(0);
  71456. indices.push(2);
  71457. indices.push(3);
  71458. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71459. };
  71460. /**
  71461. * Rebuilds the vertex buffers of the manager.
  71462. * @hidden
  71463. */
  71464. PostProcessManager.prototype._rebuild = function () {
  71465. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71466. if (!vb) {
  71467. return;
  71468. }
  71469. vb._rebuild();
  71470. this._buildIndexBuffer();
  71471. };
  71472. // Methods
  71473. /**
  71474. * Prepares a frame to be run through a post process.
  71475. * @param sourceTexture The input texture to the post procesess. (default: null)
  71476. * @param postProcesses An array of post processes to be run. (default: null)
  71477. * @returns True if the post processes were able to be run.
  71478. * @hidden
  71479. */
  71480. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71481. if (sourceTexture === void 0) { sourceTexture = null; }
  71482. if (postProcesses === void 0) { postProcesses = null; }
  71483. var camera = this._scene.activeCamera;
  71484. if (!camera) {
  71485. return false;
  71486. }
  71487. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71488. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71489. return false;
  71490. }
  71491. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71492. return true;
  71493. };
  71494. /**
  71495. * Manually render a set of post processes to a texture.
  71496. * @param postProcesses An array of post processes to be run.
  71497. * @param targetTexture The target texture to render to.
  71498. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71499. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71500. * @param lodLevel defines which lod of the texture to render to
  71501. */
  71502. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71503. if (targetTexture === void 0) { targetTexture = null; }
  71504. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71505. if (faceIndex === void 0) { faceIndex = 0; }
  71506. if (lodLevel === void 0) { lodLevel = 0; }
  71507. var engine = this._scene.getEngine();
  71508. for (var index = 0; index < postProcesses.length; index++) {
  71509. if (index < postProcesses.length - 1) {
  71510. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71511. }
  71512. else {
  71513. if (targetTexture) {
  71514. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71515. }
  71516. else {
  71517. engine.restoreDefaultFramebuffer();
  71518. }
  71519. }
  71520. var pp = postProcesses[index];
  71521. var effect = pp.apply();
  71522. if (effect) {
  71523. pp.onBeforeRenderObservable.notifyObservers(effect);
  71524. // VBOs
  71525. this._prepareBuffers();
  71526. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71527. // Draw order
  71528. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71529. pp.onAfterRenderObservable.notifyObservers(effect);
  71530. }
  71531. }
  71532. // Restore depth buffer
  71533. engine.setDepthBuffer(true);
  71534. engine.setDepthWrite(true);
  71535. };
  71536. /**
  71537. * Finalize the result of the output of the postprocesses.
  71538. * @param doNotPresent If true the result will not be displayed to the screen.
  71539. * @param targetTexture The target texture to render to.
  71540. * @param faceIndex The index of the face to bind the target texture to.
  71541. * @param postProcesses The array of post processes to render.
  71542. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71543. * @hidden
  71544. */
  71545. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71546. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71547. var camera = this._scene.activeCamera;
  71548. if (!camera) {
  71549. return;
  71550. }
  71551. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71552. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71553. return;
  71554. }
  71555. var engine = this._scene.getEngine();
  71556. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71557. var pp = postProcesses[index];
  71558. if (index < len - 1) {
  71559. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71560. }
  71561. else {
  71562. if (targetTexture) {
  71563. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71564. pp._outputTexture = targetTexture;
  71565. }
  71566. else {
  71567. engine.restoreDefaultFramebuffer();
  71568. pp._outputTexture = null;
  71569. }
  71570. }
  71571. if (doNotPresent) {
  71572. break;
  71573. }
  71574. var effect = pp.apply();
  71575. if (effect) {
  71576. pp.onBeforeRenderObservable.notifyObservers(effect);
  71577. // VBOs
  71578. this._prepareBuffers();
  71579. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71580. // Draw order
  71581. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71582. pp.onAfterRenderObservable.notifyObservers(effect);
  71583. }
  71584. }
  71585. // Restore states
  71586. engine.setDepthBuffer(true);
  71587. engine.setDepthWrite(true);
  71588. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71589. };
  71590. /**
  71591. * Disposes of the post process manager.
  71592. */
  71593. PostProcessManager.prototype.dispose = function () {
  71594. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71595. if (buffer) {
  71596. buffer.dispose();
  71597. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71598. }
  71599. if (this._indexBuffer) {
  71600. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71601. this._indexBuffer = null;
  71602. }
  71603. };
  71604. return PostProcessManager;
  71605. }());
  71606. BABYLON.PostProcessManager = PostProcessManager;
  71607. })(BABYLON || (BABYLON = {}));
  71608. //# sourceMappingURL=babylon.postProcessManager.js.map
  71609. var BABYLON;
  71610. (function (BABYLON) {
  71611. /**
  71612. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71613. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71614. */
  71615. var PostProcess = /** @class */ (function () {
  71616. /**
  71617. * Creates a new instance PostProcess
  71618. * @param name The name of the PostProcess.
  71619. * @param fragmentUrl The url of the fragment shader to be used.
  71620. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71621. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71622. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71623. * @param camera The camera to apply the render pass to.
  71624. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71625. * @param engine The engine which the post process will be applied. (default: current engine)
  71626. * @param reusable If the post process can be reused on the same frame. (default: false)
  71627. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71628. * @param textureType Type of textures used when performing the post process. (default: 0)
  71629. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71630. * @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
  71631. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71632. */
  71633. function PostProcess(
  71634. /** Name of the PostProcess. */
  71635. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71637. if (defines === void 0) { defines = null; }
  71638. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71639. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71640. if (blockCompilation === void 0) { blockCompilation = false; }
  71641. this.name = name;
  71642. /**
  71643. * Width of the texture to apply the post process on
  71644. */
  71645. this.width = -1;
  71646. /**
  71647. * Height of the texture to apply the post process on
  71648. */
  71649. this.height = -1;
  71650. /**
  71651. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71652. * @hidden
  71653. */
  71654. this._outputTexture = null;
  71655. /**
  71656. * If the buffer needs to be cleared before applying the post process. (default: true)
  71657. * Should be set to false if shader will overwrite all previous pixels.
  71658. */
  71659. this.autoClear = true;
  71660. /**
  71661. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71662. */
  71663. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71664. /**
  71665. * Animations to be used for the post processing
  71666. */
  71667. this.animations = new Array();
  71668. /**
  71669. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71670. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71671. */
  71672. this.enablePixelPerfectMode = false;
  71673. /**
  71674. * Force the postprocess to be applied without taking in account viewport
  71675. */
  71676. this.forceFullscreenViewport = true;
  71677. /**
  71678. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71679. *
  71680. * | Value | Type | Description |
  71681. * | ----- | ----------------------------------- | ----------- |
  71682. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71683. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71684. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71685. *
  71686. */
  71687. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71688. /**
  71689. * Force textures to be a power of two (default: false)
  71690. */
  71691. this.alwaysForcePOT = false;
  71692. this._samples = 1;
  71693. /**
  71694. * Modify the scale of the post process to be the same as the viewport (default: false)
  71695. */
  71696. this.adaptScaleToCurrentViewport = false;
  71697. this._reusable = false;
  71698. /**
  71699. * Smart array of input and output textures for the post process.
  71700. * @hidden
  71701. */
  71702. this._textures = new BABYLON.SmartArray(2);
  71703. /**
  71704. * The index in _textures that corresponds to the output texture.
  71705. * @hidden
  71706. */
  71707. this._currentRenderTextureInd = 0;
  71708. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71709. this._texelSize = BABYLON.Vector2.Zero();
  71710. // Events
  71711. /**
  71712. * An event triggered when the postprocess is activated.
  71713. */
  71714. this.onActivateObservable = new BABYLON.Observable();
  71715. /**
  71716. * An event triggered when the postprocess changes its size.
  71717. */
  71718. this.onSizeChangedObservable = new BABYLON.Observable();
  71719. /**
  71720. * An event triggered when the postprocess applies its effect.
  71721. */
  71722. this.onApplyObservable = new BABYLON.Observable();
  71723. /**
  71724. * An event triggered before rendering the postprocess
  71725. */
  71726. this.onBeforeRenderObservable = new BABYLON.Observable();
  71727. /**
  71728. * An event triggered after rendering the postprocess
  71729. */
  71730. this.onAfterRenderObservable = new BABYLON.Observable();
  71731. if (camera != null) {
  71732. this._camera = camera;
  71733. this._scene = camera.getScene();
  71734. camera.attachPostProcess(this);
  71735. this._engine = this._scene.getEngine();
  71736. this._scene.postProcesses.push(this);
  71737. }
  71738. else if (engine) {
  71739. this._engine = engine;
  71740. this._engine.postProcesses.push(this);
  71741. }
  71742. this._options = options;
  71743. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71744. this._reusable = reusable || false;
  71745. this._textureType = textureType;
  71746. this._samplers = samplers || [];
  71747. this._samplers.push("textureSampler");
  71748. this._fragmentUrl = fragmentUrl;
  71749. this._vertexUrl = vertexUrl;
  71750. this._parameters = parameters || [];
  71751. this._parameters.push("scale");
  71752. this._indexParameters = indexParameters;
  71753. if (!blockCompilation) {
  71754. this.updateEffect(defines);
  71755. }
  71756. }
  71757. Object.defineProperty(PostProcess.prototype, "samples", {
  71758. /**
  71759. * Number of sample textures (default: 1)
  71760. */
  71761. get: function () {
  71762. return this._samples;
  71763. },
  71764. set: function (n) {
  71765. var _this = this;
  71766. this._samples = n;
  71767. this._textures.forEach(function (texture) {
  71768. if (texture.samples !== _this._samples) {
  71769. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71770. }
  71771. });
  71772. },
  71773. enumerable: true,
  71774. configurable: true
  71775. });
  71776. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71777. /**
  71778. * A function that is added to the onActivateObservable
  71779. */
  71780. set: function (callback) {
  71781. if (this._onActivateObserver) {
  71782. this.onActivateObservable.remove(this._onActivateObserver);
  71783. }
  71784. if (callback) {
  71785. this._onActivateObserver = this.onActivateObservable.add(callback);
  71786. }
  71787. },
  71788. enumerable: true,
  71789. configurable: true
  71790. });
  71791. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71792. /**
  71793. * A function that is added to the onSizeChangedObservable
  71794. */
  71795. set: function (callback) {
  71796. if (this._onSizeChangedObserver) {
  71797. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71798. }
  71799. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71800. },
  71801. enumerable: true,
  71802. configurable: true
  71803. });
  71804. Object.defineProperty(PostProcess.prototype, "onApply", {
  71805. /**
  71806. * A function that is added to the onApplyObservable
  71807. */
  71808. set: function (callback) {
  71809. if (this._onApplyObserver) {
  71810. this.onApplyObservable.remove(this._onApplyObserver);
  71811. }
  71812. this._onApplyObserver = this.onApplyObservable.add(callback);
  71813. },
  71814. enumerable: true,
  71815. configurable: true
  71816. });
  71817. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71818. /**
  71819. * A function that is added to the onBeforeRenderObservable
  71820. */
  71821. set: function (callback) {
  71822. if (this._onBeforeRenderObserver) {
  71823. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71824. }
  71825. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71826. },
  71827. enumerable: true,
  71828. configurable: true
  71829. });
  71830. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71831. /**
  71832. * A function that is added to the onAfterRenderObservable
  71833. */
  71834. set: function (callback) {
  71835. if (this._onAfterRenderObserver) {
  71836. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71837. }
  71838. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71839. },
  71840. enumerable: true,
  71841. configurable: true
  71842. });
  71843. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71844. /**
  71845. * 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
  71846. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71847. */
  71848. get: function () {
  71849. return this._textures.data[this._currentRenderTextureInd];
  71850. },
  71851. set: function (value) {
  71852. this._forcedOutputTexture = value;
  71853. },
  71854. enumerable: true,
  71855. configurable: true
  71856. });
  71857. /**
  71858. * Gets the camera which post process is applied to.
  71859. * @returns The camera the post process is applied to.
  71860. */
  71861. PostProcess.prototype.getCamera = function () {
  71862. return this._camera;
  71863. };
  71864. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71865. /**
  71866. * Gets the texel size of the postprocess.
  71867. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71868. */
  71869. get: function () {
  71870. if (this._shareOutputWithPostProcess) {
  71871. return this._shareOutputWithPostProcess.texelSize;
  71872. }
  71873. if (this._forcedOutputTexture) {
  71874. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71875. }
  71876. return this._texelSize;
  71877. },
  71878. enumerable: true,
  71879. configurable: true
  71880. });
  71881. /**
  71882. * Gets the engine which this post process belongs to.
  71883. * @returns The engine the post process was enabled with.
  71884. */
  71885. PostProcess.prototype.getEngine = function () {
  71886. return this._engine;
  71887. };
  71888. /**
  71889. * The effect that is created when initializing the post process.
  71890. * @returns The created effect corrisponding the the postprocess.
  71891. */
  71892. PostProcess.prototype.getEffect = function () {
  71893. return this._effect;
  71894. };
  71895. /**
  71896. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71897. * @param postProcess The post process to share the output with.
  71898. * @returns This post process.
  71899. */
  71900. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71901. this._disposeTextures();
  71902. this._shareOutputWithPostProcess = postProcess;
  71903. return this;
  71904. };
  71905. /**
  71906. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71907. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71908. */
  71909. PostProcess.prototype.useOwnOutput = function () {
  71910. if (this._textures.length == 0) {
  71911. this._textures = new BABYLON.SmartArray(2);
  71912. }
  71913. this._shareOutputWithPostProcess = null;
  71914. };
  71915. /**
  71916. * Updates the effect with the current post process compile time values and recompiles the shader.
  71917. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71918. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71919. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71920. * @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
  71921. * @param onCompiled Called when the shader has been compiled.
  71922. * @param onError Called if there is an error when compiling a shader.
  71923. */
  71924. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71925. if (defines === void 0) { defines = null; }
  71926. if (uniforms === void 0) { uniforms = null; }
  71927. if (samplers === void 0) { samplers = null; }
  71928. 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);
  71929. };
  71930. /**
  71931. * The post process is reusable if it can be used multiple times within one frame.
  71932. * @returns If the post process is reusable
  71933. */
  71934. PostProcess.prototype.isReusable = function () {
  71935. return this._reusable;
  71936. };
  71937. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71938. PostProcess.prototype.markTextureDirty = function () {
  71939. this.width = -1;
  71940. };
  71941. /**
  71942. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71943. * 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.
  71944. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71945. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71946. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71947. * @returns The target texture that was bound to be written to.
  71948. */
  71949. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71950. var _this = this;
  71951. if (sourceTexture === void 0) { sourceTexture = null; }
  71952. camera = camera || this._camera;
  71953. var scene = camera.getScene();
  71954. var engine = scene.getEngine();
  71955. var maxSize = engine.getCaps().maxTextureSize;
  71956. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71957. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71958. // 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
  71959. var webVRCamera = camera.parent;
  71960. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71961. requiredWidth /= 2;
  71962. }
  71963. var desiredWidth = (this._options.width || requiredWidth);
  71964. var desiredHeight = this._options.height || requiredHeight;
  71965. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71966. if (this.adaptScaleToCurrentViewport) {
  71967. var currentViewport = engine.currentViewport;
  71968. if (currentViewport) {
  71969. desiredWidth *= currentViewport.width;
  71970. desiredHeight *= currentViewport.height;
  71971. }
  71972. }
  71973. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71974. if (!this._options.width) {
  71975. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71976. }
  71977. if (!this._options.height) {
  71978. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71979. }
  71980. }
  71981. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71982. if (this._textures.length > 0) {
  71983. for (var i = 0; i < this._textures.length; i++) {
  71984. this._engine._releaseTexture(this._textures.data[i]);
  71985. }
  71986. this._textures.reset();
  71987. }
  71988. this.width = desiredWidth;
  71989. this.height = desiredHeight;
  71990. var textureSize = { width: this.width, height: this.height };
  71991. var textureOptions = {
  71992. generateMipMaps: false,
  71993. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71994. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71995. samplingMode: this.renderTargetSamplingMode,
  71996. type: this._textureType
  71997. };
  71998. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71999. if (this._reusable) {
  72000. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72001. }
  72002. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  72003. this.onSizeChangedObservable.notifyObservers(this);
  72004. }
  72005. this._textures.forEach(function (texture) {
  72006. if (texture.samples !== _this.samples) {
  72007. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  72008. }
  72009. });
  72010. }
  72011. var target;
  72012. if (this._shareOutputWithPostProcess) {
  72013. target = this._shareOutputWithPostProcess.inputTexture;
  72014. }
  72015. else if (this._forcedOutputTexture) {
  72016. target = this._forcedOutputTexture;
  72017. this.width = this._forcedOutputTexture.width;
  72018. this.height = this._forcedOutputTexture.height;
  72019. }
  72020. else {
  72021. target = this.inputTexture;
  72022. }
  72023. // Bind the input of this post process to be used as the output of the previous post process.
  72024. if (this.enablePixelPerfectMode) {
  72025. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72026. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72027. }
  72028. else {
  72029. this._scaleRatio.copyFromFloats(1, 1);
  72030. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72031. }
  72032. this.onActivateObservable.notifyObservers(camera);
  72033. // Clear
  72034. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72035. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72036. }
  72037. if (this._reusable) {
  72038. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72039. }
  72040. return target;
  72041. };
  72042. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72043. /**
  72044. * If the post process is supported.
  72045. */
  72046. get: function () {
  72047. return this._effect.isSupported;
  72048. },
  72049. enumerable: true,
  72050. configurable: true
  72051. });
  72052. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72053. /**
  72054. * The aspect ratio of the output texture.
  72055. */
  72056. get: function () {
  72057. if (this._shareOutputWithPostProcess) {
  72058. return this._shareOutputWithPostProcess.aspectRatio;
  72059. }
  72060. if (this._forcedOutputTexture) {
  72061. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  72062. }
  72063. return this.width / this.height;
  72064. },
  72065. enumerable: true,
  72066. configurable: true
  72067. });
  72068. /**
  72069. * Get a value indicating if the post-process is ready to be used
  72070. * @returns true if the post-process is ready (shader is compiled)
  72071. */
  72072. PostProcess.prototype.isReady = function () {
  72073. return this._effect && this._effect.isReady();
  72074. };
  72075. /**
  72076. * Binds all textures and uniforms to the shader, this will be run on every pass.
  72077. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  72078. */
  72079. PostProcess.prototype.apply = function () {
  72080. // Check
  72081. if (!this._effect || !this._effect.isReady())
  72082. return null;
  72083. // States
  72084. this._engine.enableEffect(this._effect);
  72085. this._engine.setState(false);
  72086. this._engine.setDepthBuffer(false);
  72087. this._engine.setDepthWrite(false);
  72088. // Alpha
  72089. this._engine.setAlphaMode(this.alphaMode);
  72090. if (this.alphaConstants) {
  72091. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  72092. }
  72093. // Bind the output texture of the preivous post process as the input to this post process.
  72094. var source;
  72095. if (this._shareOutputWithPostProcess) {
  72096. source = this._shareOutputWithPostProcess.inputTexture;
  72097. }
  72098. else if (this._forcedOutputTexture) {
  72099. source = this._forcedOutputTexture;
  72100. }
  72101. else {
  72102. source = this.inputTexture;
  72103. }
  72104. this._effect._bindTexture("textureSampler", source);
  72105. // Parameters
  72106. this._effect.setVector2("scale", this._scaleRatio);
  72107. this.onApplyObservable.notifyObservers(this._effect);
  72108. return this._effect;
  72109. };
  72110. PostProcess.prototype._disposeTextures = function () {
  72111. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  72112. return;
  72113. }
  72114. if (this._textures.length > 0) {
  72115. for (var i = 0; i < this._textures.length; i++) {
  72116. this._engine._releaseTexture(this._textures.data[i]);
  72117. }
  72118. }
  72119. this._textures.dispose();
  72120. };
  72121. /**
  72122. * Disposes the post process.
  72123. * @param camera The camera to dispose the post process on.
  72124. */
  72125. PostProcess.prototype.dispose = function (camera) {
  72126. camera = camera || this._camera;
  72127. this._disposeTextures();
  72128. if (this._scene) {
  72129. var index_1 = this._scene.postProcesses.indexOf(this);
  72130. if (index_1 !== -1) {
  72131. this._scene.postProcesses.splice(index_1, 1);
  72132. }
  72133. }
  72134. else {
  72135. var index_2 = this._engine.postProcesses.indexOf(this);
  72136. if (index_2 !== -1) {
  72137. this._engine.postProcesses.splice(index_2, 1);
  72138. }
  72139. }
  72140. if (!camera) {
  72141. return;
  72142. }
  72143. camera.detachPostProcess(this);
  72144. var index = camera._postProcesses.indexOf(this);
  72145. if (index === 0 && camera._postProcesses.length > 0) {
  72146. var firstPostProcess = this._camera._getFirstPostProcess();
  72147. if (firstPostProcess) {
  72148. firstPostProcess.markTextureDirty();
  72149. }
  72150. }
  72151. this.onActivateObservable.clear();
  72152. this.onAfterRenderObservable.clear();
  72153. this.onApplyObservable.clear();
  72154. this.onBeforeRenderObservable.clear();
  72155. this.onSizeChangedObservable.clear();
  72156. };
  72157. return PostProcess;
  72158. }());
  72159. BABYLON.PostProcess = PostProcess;
  72160. })(BABYLON || (BABYLON = {}));
  72161. //# sourceMappingURL=babylon.postProcess.js.map
  72162. var BABYLON;
  72163. (function (BABYLON) {
  72164. var PassPostProcess = /** @class */ (function (_super) {
  72165. __extends(PassPostProcess, _super);
  72166. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72167. if (camera === void 0) { camera = null; }
  72168. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72169. if (blockCompilation === void 0) { blockCompilation = false; }
  72170. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  72171. }
  72172. return PassPostProcess;
  72173. }(BABYLON.PostProcess));
  72174. BABYLON.PassPostProcess = PassPostProcess;
  72175. })(BABYLON || (BABYLON = {}));
  72176. //# sourceMappingURL=babylon.passPostProcess.js.map
  72177. var __assign = (this && this.__assign) || function () {
  72178. __assign = Object.assign || function(t) {
  72179. for (var s, i = 1, n = arguments.length; i < n; i++) {
  72180. s = arguments[i];
  72181. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  72182. t[p] = s[p];
  72183. }
  72184. return t;
  72185. };
  72186. return __assign.apply(this, arguments);
  72187. };
  72188. var BABYLON;
  72189. (function (BABYLON) {
  72190. /**
  72191. * Default implementation IShadowGenerator.
  72192. * This is the main object responsible of generating shadows in the framework.
  72193. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  72194. */
  72195. var ShadowGenerator = /** @class */ (function () {
  72196. /**
  72197. * Creates a ShadowGenerator object.
  72198. * A ShadowGenerator is the required tool to use the shadows.
  72199. * Each light casting shadows needs to use its own ShadowGenerator.
  72200. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  72201. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  72202. * @param light The light object generating the shadows.
  72203. * @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.
  72204. */
  72205. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  72206. this._bias = 0.00005;
  72207. this._normalBias = 0;
  72208. this._blurBoxOffset = 1;
  72209. this._blurScale = 2;
  72210. this._blurKernel = 1;
  72211. this._useKernelBlur = false;
  72212. this._filter = ShadowGenerator.FILTER_NONE;
  72213. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  72214. this._contactHardeningLightSizeUVRatio = 0.1;
  72215. this._darkness = 0;
  72216. this._transparencyShadow = false;
  72217. /**
  72218. * Controls the extent to which the shadows fade out at the edge of the frustum
  72219. * Used only by directionals and spots
  72220. */
  72221. this.frustumEdgeFalloff = 0;
  72222. /**
  72223. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  72224. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  72225. * It might on the other hand introduce peter panning.
  72226. */
  72227. this.forceBackFacesOnly = false;
  72228. this._lightDirection = BABYLON.Vector3.Zero();
  72229. this._viewMatrix = BABYLON.Matrix.Zero();
  72230. this._projectionMatrix = BABYLON.Matrix.Zero();
  72231. this._transformMatrix = BABYLON.Matrix.Zero();
  72232. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72233. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72234. this._currentFaceIndex = 0;
  72235. this._currentFaceIndexCache = 0;
  72236. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  72237. this._mapSize = mapSize;
  72238. this._light = light;
  72239. this._scene = light.getScene();
  72240. light._shadowGenerator = this;
  72241. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  72242. if (!component) {
  72243. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  72244. this._scene._addComponent(component);
  72245. }
  72246. // Texture type fallback from float to int if not supported.
  72247. var caps = this._scene.getEngine().getCaps();
  72248. if (!useFullFloatFirst) {
  72249. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72250. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72251. }
  72252. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72253. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72254. }
  72255. else {
  72256. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72257. }
  72258. }
  72259. else {
  72260. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72261. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72262. }
  72263. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72264. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72265. }
  72266. else {
  72267. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72268. }
  72269. }
  72270. this._initializeGenerator();
  72271. this._applyFilterValues();
  72272. }
  72273. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  72274. /**
  72275. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  72276. */
  72277. get: function () {
  72278. return this._bias;
  72279. },
  72280. /**
  72281. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  72282. */
  72283. set: function (bias) {
  72284. this._bias = bias;
  72285. },
  72286. enumerable: true,
  72287. configurable: true
  72288. });
  72289. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  72290. /**
  72291. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72292. */
  72293. get: function () {
  72294. return this._normalBias;
  72295. },
  72296. /**
  72297. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72298. */
  72299. set: function (normalBias) {
  72300. this._normalBias = normalBias;
  72301. },
  72302. enumerable: true,
  72303. configurable: true
  72304. });
  72305. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  72306. /**
  72307. * Gets the blur box offset: offset applied during the blur pass.
  72308. * Only usefull if useKernelBlur = false
  72309. */
  72310. get: function () {
  72311. return this._blurBoxOffset;
  72312. },
  72313. /**
  72314. * Sets the blur box offset: offset applied during the blur pass.
  72315. * Only usefull if useKernelBlur = false
  72316. */
  72317. set: function (value) {
  72318. if (this._blurBoxOffset === value) {
  72319. return;
  72320. }
  72321. this._blurBoxOffset = value;
  72322. this._disposeBlurPostProcesses();
  72323. },
  72324. enumerable: true,
  72325. configurable: true
  72326. });
  72327. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72328. /**
  72329. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72330. * 2 means half of the size.
  72331. */
  72332. get: function () {
  72333. return this._blurScale;
  72334. },
  72335. /**
  72336. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72337. * 2 means half of the size.
  72338. */
  72339. set: function (value) {
  72340. if (this._blurScale === value) {
  72341. return;
  72342. }
  72343. this._blurScale = value;
  72344. this._disposeBlurPostProcesses();
  72345. },
  72346. enumerable: true,
  72347. configurable: true
  72348. });
  72349. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72350. /**
  72351. * Gets the blur kernel: kernel size of the blur pass.
  72352. * Only usefull if useKernelBlur = true
  72353. */
  72354. get: function () {
  72355. return this._blurKernel;
  72356. },
  72357. /**
  72358. * Sets the blur kernel: kernel size of the blur pass.
  72359. * Only usefull if useKernelBlur = true
  72360. */
  72361. set: function (value) {
  72362. if (this._blurKernel === value) {
  72363. return;
  72364. }
  72365. this._blurKernel = value;
  72366. this._disposeBlurPostProcesses();
  72367. },
  72368. enumerable: true,
  72369. configurable: true
  72370. });
  72371. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72372. /**
  72373. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72374. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72375. */
  72376. get: function () {
  72377. return this._useKernelBlur;
  72378. },
  72379. /**
  72380. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72381. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72382. */
  72383. set: function (value) {
  72384. if (this._useKernelBlur === value) {
  72385. return;
  72386. }
  72387. this._useKernelBlur = value;
  72388. this._disposeBlurPostProcesses();
  72389. },
  72390. enumerable: true,
  72391. configurable: true
  72392. });
  72393. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72394. /**
  72395. * Gets the depth scale used in ESM mode.
  72396. */
  72397. get: function () {
  72398. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72399. },
  72400. /**
  72401. * Sets the depth scale used in ESM mode.
  72402. * This can override the scale stored on the light.
  72403. */
  72404. set: function (value) {
  72405. this._depthScale = value;
  72406. },
  72407. enumerable: true,
  72408. configurable: true
  72409. });
  72410. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72411. /**
  72412. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72413. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72414. */
  72415. get: function () {
  72416. return this._filter;
  72417. },
  72418. /**
  72419. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72420. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72421. */
  72422. set: function (value) {
  72423. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72424. if (this._light.needCube()) {
  72425. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72426. this.useExponentialShadowMap = true;
  72427. return;
  72428. }
  72429. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72430. this.useCloseExponentialShadowMap = true;
  72431. return;
  72432. }
  72433. // PCF on cubemap would also be expensive
  72434. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72435. this.usePoissonSampling = true;
  72436. return;
  72437. }
  72438. }
  72439. // Weblg1 fallback for PCF.
  72440. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72441. if (this._scene.getEngine().webGLVersion === 1) {
  72442. this.usePoissonSampling = true;
  72443. return;
  72444. }
  72445. }
  72446. if (this._filter === value) {
  72447. return;
  72448. }
  72449. this._filter = value;
  72450. this._disposeBlurPostProcesses();
  72451. this._applyFilterValues();
  72452. this._light._markMeshesAsLightDirty();
  72453. },
  72454. enumerable: true,
  72455. configurable: true
  72456. });
  72457. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72458. /**
  72459. * Gets if the current filter is set to Poisson Sampling.
  72460. */
  72461. get: function () {
  72462. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72463. },
  72464. /**
  72465. * Sets the current filter to Poisson Sampling.
  72466. */
  72467. set: function (value) {
  72468. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72469. return;
  72470. }
  72471. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72472. },
  72473. enumerable: true,
  72474. configurable: true
  72475. });
  72476. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72477. /**
  72478. * Gets if the current filter is set to VSM.
  72479. * DEPRECATED. Should use useExponentialShadowMap instead.
  72480. */
  72481. get: function () {
  72482. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72483. return this.useExponentialShadowMap;
  72484. },
  72485. /**
  72486. * Sets the current filter is to VSM.
  72487. * DEPRECATED. Should use useExponentialShadowMap instead.
  72488. */
  72489. set: function (value) {
  72490. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72491. this.useExponentialShadowMap = value;
  72492. },
  72493. enumerable: true,
  72494. configurable: true
  72495. });
  72496. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72497. /**
  72498. * Gets if the current filter is set to blurred VSM.
  72499. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72500. */
  72501. get: function () {
  72502. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72503. return this.useBlurExponentialShadowMap;
  72504. },
  72505. /**
  72506. * Sets the current filter is to blurred VSM.
  72507. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72508. */
  72509. set: function (value) {
  72510. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72511. this.useBlurExponentialShadowMap = value;
  72512. },
  72513. enumerable: true,
  72514. configurable: true
  72515. });
  72516. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72517. /**
  72518. * Gets if the current filter is set to ESM.
  72519. */
  72520. get: function () {
  72521. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72522. },
  72523. /**
  72524. * Sets the current filter is to ESM.
  72525. */
  72526. set: function (value) {
  72527. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72528. return;
  72529. }
  72530. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72531. },
  72532. enumerable: true,
  72533. configurable: true
  72534. });
  72535. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72536. /**
  72537. * Gets if the current filter is set to filtered ESM.
  72538. */
  72539. get: function () {
  72540. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72541. },
  72542. /**
  72543. * Gets if the current filter is set to filtered ESM.
  72544. */
  72545. set: function (value) {
  72546. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72547. return;
  72548. }
  72549. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72550. },
  72551. enumerable: true,
  72552. configurable: true
  72553. });
  72554. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72555. /**
  72556. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72557. * exponential to prevent steep falloff artifacts).
  72558. */
  72559. get: function () {
  72560. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72561. },
  72562. /**
  72563. * Sets the current filter to "close ESM" (using the inverse of the
  72564. * exponential to prevent steep falloff artifacts).
  72565. */
  72566. set: function (value) {
  72567. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72568. return;
  72569. }
  72570. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72571. },
  72572. enumerable: true,
  72573. configurable: true
  72574. });
  72575. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72576. /**
  72577. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72578. * exponential to prevent steep falloff artifacts).
  72579. */
  72580. get: function () {
  72581. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72582. },
  72583. /**
  72584. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72585. * exponential to prevent steep falloff artifacts).
  72586. */
  72587. set: function (value) {
  72588. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72589. return;
  72590. }
  72591. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72592. },
  72593. enumerable: true,
  72594. configurable: true
  72595. });
  72596. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72597. /**
  72598. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72599. */
  72600. get: function () {
  72601. return this.filter === ShadowGenerator.FILTER_PCF;
  72602. },
  72603. /**
  72604. * Sets the current filter to "PCF" (percentage closer filtering).
  72605. */
  72606. set: function (value) {
  72607. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72608. return;
  72609. }
  72610. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72611. },
  72612. enumerable: true,
  72613. configurable: true
  72614. });
  72615. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72616. /**
  72617. * Gets the PCF or PCSS Quality.
  72618. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72619. */
  72620. get: function () {
  72621. return this._filteringQuality;
  72622. },
  72623. /**
  72624. * Sets the PCF or PCSS Quality.
  72625. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72626. */
  72627. set: function (filteringQuality) {
  72628. this._filteringQuality = filteringQuality;
  72629. },
  72630. enumerable: true,
  72631. configurable: true
  72632. });
  72633. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72634. /**
  72635. * Gets if the current filter is set to "PCSS" (contact hardening).
  72636. */
  72637. get: function () {
  72638. return this.filter === ShadowGenerator.FILTER_PCSS;
  72639. },
  72640. /**
  72641. * Sets the current filter to "PCSS" (contact hardening).
  72642. */
  72643. set: function (value) {
  72644. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72645. return;
  72646. }
  72647. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72648. },
  72649. enumerable: true,
  72650. configurable: true
  72651. });
  72652. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72653. /**
  72654. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72655. * Using a ratio helps keeping shape stability independently of the map size.
  72656. *
  72657. * It does not account for the light projection as it was having too much
  72658. * instability during the light setup or during light position changes.
  72659. *
  72660. * Only valid if useContactHardeningShadow is true.
  72661. */
  72662. get: function () {
  72663. return this._contactHardeningLightSizeUVRatio;
  72664. },
  72665. /**
  72666. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72667. * Using a ratio helps keeping shape stability independently of the map size.
  72668. *
  72669. * It does not account for the light projection as it was having too much
  72670. * instability during the light setup or during light position changes.
  72671. *
  72672. * Only valid if useContactHardeningShadow is true.
  72673. */
  72674. set: function (contactHardeningLightSizeUVRatio) {
  72675. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72676. },
  72677. enumerable: true,
  72678. configurable: true
  72679. });
  72680. /**
  72681. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72682. * 0 means strongest and 1 would means no shadow.
  72683. * @returns the darkness.
  72684. */
  72685. ShadowGenerator.prototype.getDarkness = function () {
  72686. return this._darkness;
  72687. };
  72688. /**
  72689. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72690. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72691. * @returns the shadow generator allowing fluent coding.
  72692. */
  72693. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72694. if (darkness >= 1.0)
  72695. this._darkness = 1.0;
  72696. else if (darkness <= 0.0)
  72697. this._darkness = 0.0;
  72698. else
  72699. this._darkness = darkness;
  72700. return this;
  72701. };
  72702. /**
  72703. * Sets the ability to have transparent shadow (boolean).
  72704. * @param transparent True if transparent else False
  72705. * @returns the shadow generator allowing fluent coding
  72706. */
  72707. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72708. this._transparencyShadow = transparent;
  72709. return this;
  72710. };
  72711. /**
  72712. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72713. * @returns The render target texture if present otherwise, null
  72714. */
  72715. ShadowGenerator.prototype.getShadowMap = function () {
  72716. return this._shadowMap;
  72717. };
  72718. /**
  72719. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72720. * @returns The render target texture if the shadow map is present otherwise, null
  72721. */
  72722. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72723. if (this._shadowMap2) {
  72724. return this._shadowMap2;
  72725. }
  72726. return this._shadowMap;
  72727. };
  72728. /**
  72729. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72730. * @param mesh Mesh to add
  72731. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72732. * @returns the Shadow Generator itself
  72733. */
  72734. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72735. if (includeDescendants === void 0) { includeDescendants = true; }
  72736. var _a;
  72737. if (!this._shadowMap) {
  72738. return this;
  72739. }
  72740. if (!this._shadowMap.renderList) {
  72741. this._shadowMap.renderList = [];
  72742. }
  72743. this._shadowMap.renderList.push(mesh);
  72744. if (includeDescendants) {
  72745. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72746. }
  72747. return this;
  72748. };
  72749. /**
  72750. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72751. * @param mesh Mesh to remove
  72752. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72753. * @returns the Shadow Generator itself
  72754. */
  72755. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72756. if (includeDescendants === void 0) { includeDescendants = true; }
  72757. if (!this._shadowMap || !this._shadowMap.renderList) {
  72758. return this;
  72759. }
  72760. var index = this._shadowMap.renderList.indexOf(mesh);
  72761. if (index !== -1) {
  72762. this._shadowMap.renderList.splice(index, 1);
  72763. }
  72764. if (includeDescendants) {
  72765. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72766. var child = _a[_i];
  72767. this.removeShadowCaster(child);
  72768. }
  72769. }
  72770. return this;
  72771. };
  72772. /**
  72773. * Returns the associated light object.
  72774. * @returns the light generating the shadow
  72775. */
  72776. ShadowGenerator.prototype.getLight = function () {
  72777. return this._light;
  72778. };
  72779. ShadowGenerator.prototype._initializeGenerator = function () {
  72780. this._light._markMeshesAsLightDirty();
  72781. this._initializeShadowMap();
  72782. };
  72783. ShadowGenerator.prototype._initializeShadowMap = function () {
  72784. var _this = this;
  72785. // Render target
  72786. var engine = this._scene.getEngine();
  72787. if (engine.webGLVersion > 1) {
  72788. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72789. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72790. }
  72791. else {
  72792. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72793. }
  72794. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72795. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72796. this._shadowMap.anisotropicFilteringLevel = 1;
  72797. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72798. this._shadowMap.renderParticles = false;
  72799. this._shadowMap.ignoreCameraViewport = true;
  72800. // Record Face Index before render.
  72801. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72802. _this._currentFaceIndex = faceIndex;
  72803. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72804. engine.setColorWrite(false);
  72805. }
  72806. });
  72807. // Custom render function.
  72808. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72809. // Blur if required afer render.
  72810. this._shadowMap.onAfterUnbindObservable.add(function () {
  72811. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72812. engine.setColorWrite(true);
  72813. }
  72814. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72815. return;
  72816. }
  72817. var shadowMap = _this.getShadowMapForRendering();
  72818. if (shadowMap) {
  72819. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72820. }
  72821. });
  72822. // Clear according to the chosen filter.
  72823. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72824. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72825. this._shadowMap.onClearObservable.add(function (engine) {
  72826. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72827. engine.clear(clearOne, false, true, false);
  72828. }
  72829. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72830. engine.clear(clearZero, true, true, false);
  72831. }
  72832. else {
  72833. engine.clear(clearOne, true, true, false);
  72834. }
  72835. });
  72836. };
  72837. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72838. var _this = this;
  72839. var engine = this._scene.getEngine();
  72840. var targetSize = this._mapSize / this.blurScale;
  72841. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72842. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72843. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72844. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72845. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72846. }
  72847. if (this.useKernelBlur) {
  72848. 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);
  72849. this._kernelBlurXPostprocess.width = targetSize;
  72850. this._kernelBlurXPostprocess.height = targetSize;
  72851. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72852. effect.setTexture("textureSampler", _this._shadowMap);
  72853. });
  72854. 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);
  72855. this._kernelBlurXPostprocess.autoClear = false;
  72856. this._kernelBlurYPostprocess.autoClear = false;
  72857. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72858. this._kernelBlurXPostprocess.packedFloat = true;
  72859. this._kernelBlurYPostprocess.packedFloat = true;
  72860. }
  72861. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72862. }
  72863. else {
  72864. 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);
  72865. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72866. effect.setFloat2("screenSize", targetSize, targetSize);
  72867. effect.setTexture("textureSampler", _this._shadowMap);
  72868. });
  72869. this._boxBlurPostprocess.autoClear = false;
  72870. this._blurPostProcesses = [this._boxBlurPostprocess];
  72871. }
  72872. };
  72873. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72874. var index;
  72875. var engine = this._scene.getEngine();
  72876. if (depthOnlySubMeshes.length) {
  72877. engine.setColorWrite(false);
  72878. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72879. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72880. }
  72881. engine.setColorWrite(true);
  72882. }
  72883. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72884. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72885. }
  72886. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72887. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72888. }
  72889. if (this._transparencyShadow) {
  72890. for (index = 0; index < transparentSubMeshes.length; index++) {
  72891. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72892. }
  72893. }
  72894. };
  72895. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72896. var _this = this;
  72897. var mesh = subMesh.getRenderingMesh();
  72898. var scene = this._scene;
  72899. var engine = scene.getEngine();
  72900. var material = subMesh.getMaterial();
  72901. if (!material) {
  72902. return;
  72903. }
  72904. // Culling
  72905. engine.setState(material.backFaceCulling);
  72906. // Managing instances
  72907. var batch = mesh._getInstancesRenderList(subMesh._id);
  72908. if (batch.mustReturn) {
  72909. return;
  72910. }
  72911. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72912. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72913. engine.enableEffect(this._effect);
  72914. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72915. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72916. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72917. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72918. this._effect.setVector3("lightData", this._cachedDirection);
  72919. }
  72920. else {
  72921. this._effect.setVector3("lightData", this._cachedPosition);
  72922. }
  72923. if (scene.activeCamera) {
  72924. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72925. }
  72926. // Alpha test
  72927. if (material && material.needAlphaTesting()) {
  72928. var alphaTexture = material.getAlphaTestTexture();
  72929. if (alphaTexture) {
  72930. this._effect.setTexture("diffuseSampler", alphaTexture);
  72931. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72932. }
  72933. }
  72934. // Bones
  72935. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72936. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72937. }
  72938. // Morph targets
  72939. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72940. if (this.forceBackFacesOnly) {
  72941. engine.setState(true, 0, false, true);
  72942. }
  72943. // Draw
  72944. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72945. if (this.forceBackFacesOnly) {
  72946. engine.setState(true, 0, false, false);
  72947. }
  72948. }
  72949. else {
  72950. // Need to reset refresh rate of the shadowMap
  72951. if (this._shadowMap) {
  72952. this._shadowMap.resetRefreshCounter();
  72953. }
  72954. }
  72955. };
  72956. ShadowGenerator.prototype._applyFilterValues = function () {
  72957. if (!this._shadowMap) {
  72958. return;
  72959. }
  72960. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72961. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72962. }
  72963. else {
  72964. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72965. }
  72966. };
  72967. /**
  72968. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72969. * @param onCompiled Callback triggered at the and of the effects compilation
  72970. * @param options Sets of optional options forcing the compilation with different modes
  72971. */
  72972. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72973. var _this = this;
  72974. var localOptions = __assign({ useInstances: false }, options);
  72975. var shadowMap = this.getShadowMap();
  72976. if (!shadowMap) {
  72977. if (onCompiled) {
  72978. onCompiled(this);
  72979. }
  72980. return;
  72981. }
  72982. var renderList = shadowMap.renderList;
  72983. if (!renderList) {
  72984. if (onCompiled) {
  72985. onCompiled(this);
  72986. }
  72987. return;
  72988. }
  72989. var subMeshes = new Array();
  72990. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72991. var mesh = renderList_1[_i];
  72992. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72993. }
  72994. if (subMeshes.length === 0) {
  72995. if (onCompiled) {
  72996. onCompiled(this);
  72997. }
  72998. return;
  72999. }
  73000. var currentIndex = 0;
  73001. var checkReady = function () {
  73002. if (!_this._scene || !_this._scene.getEngine()) {
  73003. return;
  73004. }
  73005. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  73006. currentIndex++;
  73007. if (currentIndex >= subMeshes.length) {
  73008. if (onCompiled) {
  73009. onCompiled(_this);
  73010. }
  73011. return;
  73012. }
  73013. }
  73014. setTimeout(checkReady, 16);
  73015. };
  73016. checkReady();
  73017. };
  73018. /**
  73019. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73020. * @param options Sets of optional options forcing the compilation with different modes
  73021. * @returns A promise that resolves when the compilation completes
  73022. */
  73023. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  73024. var _this = this;
  73025. return new Promise(function (resolve) {
  73026. _this.forceCompilation(function () {
  73027. resolve();
  73028. }, options);
  73029. });
  73030. };
  73031. /**
  73032. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73033. * @param subMesh The submesh we want to render in the shadow map
  73034. * @param useInstances Defines wether will draw in the map using instances
  73035. * @returns true if ready otherwise, false
  73036. */
  73037. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73038. var defines = [];
  73039. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73040. defines.push("#define FLOAT");
  73041. }
  73042. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73043. defines.push("#define ESM");
  73044. }
  73045. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73046. defines.push("#define DEPTHTEXTURE");
  73047. }
  73048. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73049. var mesh = subMesh.getMesh();
  73050. var material = subMesh.getMaterial();
  73051. // Normal bias.
  73052. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73053. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73054. defines.push("#define NORMAL");
  73055. if (mesh.nonUniformScaling) {
  73056. defines.push("#define NONUNIFORMSCALING");
  73057. }
  73058. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73059. defines.push("#define DIRECTIONINLIGHTDATA");
  73060. }
  73061. }
  73062. // Alpha test
  73063. if (material && material.needAlphaTesting()) {
  73064. var alphaTexture = material.getAlphaTestTexture();
  73065. if (alphaTexture) {
  73066. defines.push("#define ALPHATEST");
  73067. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73068. attribs.push(BABYLON.VertexBuffer.UVKind);
  73069. defines.push("#define UV1");
  73070. }
  73071. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73072. if (alphaTexture.coordinatesIndex === 1) {
  73073. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73074. defines.push("#define UV2");
  73075. }
  73076. }
  73077. }
  73078. }
  73079. // Bones
  73080. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73081. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73082. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73083. if (mesh.numBoneInfluencers > 4) {
  73084. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73085. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73086. }
  73087. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73088. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  73089. }
  73090. else {
  73091. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73092. }
  73093. // Morph targets
  73094. var manager = mesh.morphTargetManager;
  73095. var morphInfluencers = 0;
  73096. if (manager) {
  73097. if (manager.numInfluencers > 0) {
  73098. defines.push("#define MORPHTARGETS");
  73099. morphInfluencers = manager.numInfluencers;
  73100. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  73101. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  73102. }
  73103. }
  73104. // Instances
  73105. if (useInstances) {
  73106. defines.push("#define INSTANCES");
  73107. attribs.push("world0");
  73108. attribs.push("world1");
  73109. attribs.push("world2");
  73110. attribs.push("world3");
  73111. }
  73112. // Get correct effect
  73113. var join = defines.join("\n");
  73114. if (this._cachedDefines !== join) {
  73115. this._cachedDefines = join;
  73116. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  73117. }
  73118. if (!this._effect.isReady()) {
  73119. return false;
  73120. }
  73121. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73122. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  73123. this._initializeBlurRTTAndPostProcesses();
  73124. }
  73125. }
  73126. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  73127. return false;
  73128. }
  73129. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  73130. return false;
  73131. }
  73132. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  73133. return false;
  73134. }
  73135. return true;
  73136. };
  73137. /**
  73138. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  73139. * @param defines Defines of the material we want to update
  73140. * @param lightIndex Index of the light in the enabled light list of the material
  73141. */
  73142. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  73143. var scene = this._scene;
  73144. var light = this._light;
  73145. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73146. return;
  73147. }
  73148. defines["SHADOW" + lightIndex] = true;
  73149. if (this.useContactHardeningShadow) {
  73150. defines["SHADOWPCSS" + lightIndex] = true;
  73151. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73152. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73153. }
  73154. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73155. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73156. }
  73157. // else default to high.
  73158. }
  73159. if (this.usePercentageCloserFiltering) {
  73160. defines["SHADOWPCF" + lightIndex] = true;
  73161. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73162. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73163. }
  73164. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73165. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73166. }
  73167. // else default to high.
  73168. }
  73169. else if (this.usePoissonSampling) {
  73170. defines["SHADOWPOISSON" + lightIndex] = true;
  73171. }
  73172. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73173. defines["SHADOWESM" + lightIndex] = true;
  73174. }
  73175. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73176. defines["SHADOWCLOSEESM" + lightIndex] = true;
  73177. }
  73178. if (light.needCube()) {
  73179. defines["SHADOWCUBE" + lightIndex] = true;
  73180. }
  73181. };
  73182. /**
  73183. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  73184. * defined in the generator but impacting the effect).
  73185. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  73186. * @param effect The effect we are binfing the information for
  73187. */
  73188. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  73189. var light = this._light;
  73190. var scene = this._scene;
  73191. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73192. return;
  73193. }
  73194. var camera = scene.activeCamera;
  73195. if (!camera) {
  73196. return;
  73197. }
  73198. var shadowMap = this.getShadowMap();
  73199. if (!shadowMap) {
  73200. return;
  73201. }
  73202. if (!light.needCube()) {
  73203. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  73204. }
  73205. // Only PCF uses depth stencil texture.
  73206. if (this._filter === ShadowGenerator.FILTER_PCF) {
  73207. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73208. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73209. }
  73210. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  73211. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73212. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  73213. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73214. }
  73215. else {
  73216. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73217. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  73218. }
  73219. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  73220. };
  73221. /**
  73222. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  73223. * (eq to shadow prjection matrix * light transform matrix)
  73224. * @returns The transform matrix used to create the shadow map
  73225. */
  73226. ShadowGenerator.prototype.getTransformMatrix = function () {
  73227. var scene = this._scene;
  73228. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  73229. return this._transformMatrix;
  73230. }
  73231. this._currentRenderID = scene.getRenderId();
  73232. this._currentFaceIndexCache = this._currentFaceIndex;
  73233. var lightPosition = this._light.position;
  73234. if (this._light.computeTransformedInformation()) {
  73235. lightPosition = this._light.transformedPosition;
  73236. }
  73237. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  73238. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  73239. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  73240. }
  73241. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  73242. this._cachedPosition.copyFrom(lightPosition);
  73243. this._cachedDirection.copyFrom(this._lightDirection);
  73244. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  73245. var shadowMap = this.getShadowMap();
  73246. if (shadowMap) {
  73247. var renderList = shadowMap.renderList;
  73248. if (renderList) {
  73249. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  73250. }
  73251. }
  73252. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  73253. }
  73254. return this._transformMatrix;
  73255. };
  73256. /**
  73257. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  73258. * Cube and 2D textures for instance.
  73259. */
  73260. ShadowGenerator.prototype.recreateShadowMap = function () {
  73261. var shadowMap = this._shadowMap;
  73262. if (!shadowMap) {
  73263. return;
  73264. }
  73265. // Track render list.
  73266. var renderList = shadowMap.renderList;
  73267. // Clean up existing data.
  73268. this._disposeRTTandPostProcesses();
  73269. // Reinitializes.
  73270. this._initializeGenerator();
  73271. // Reaffect the filter to ensure a correct fallback if necessary.
  73272. this.filter = this.filter;
  73273. // Reaffect the filter.
  73274. this._applyFilterValues();
  73275. // Reaffect Render List.
  73276. this._shadowMap.renderList = renderList;
  73277. };
  73278. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  73279. if (this._shadowMap2) {
  73280. this._shadowMap2.dispose();
  73281. this._shadowMap2 = null;
  73282. }
  73283. if (this._boxBlurPostprocess) {
  73284. this._boxBlurPostprocess.dispose();
  73285. this._boxBlurPostprocess = null;
  73286. }
  73287. if (this._kernelBlurXPostprocess) {
  73288. this._kernelBlurXPostprocess.dispose();
  73289. this._kernelBlurXPostprocess = null;
  73290. }
  73291. if (this._kernelBlurYPostprocess) {
  73292. this._kernelBlurYPostprocess.dispose();
  73293. this._kernelBlurYPostprocess = null;
  73294. }
  73295. this._blurPostProcesses = [];
  73296. };
  73297. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  73298. if (this._shadowMap) {
  73299. this._shadowMap.dispose();
  73300. this._shadowMap = null;
  73301. }
  73302. this._disposeBlurPostProcesses();
  73303. };
  73304. /**
  73305. * Disposes the ShadowGenerator.
  73306. * Returns nothing.
  73307. */
  73308. ShadowGenerator.prototype.dispose = function () {
  73309. this._disposeRTTandPostProcesses();
  73310. if (this._light) {
  73311. this._light._shadowGenerator = null;
  73312. this._light._markMeshesAsLightDirty();
  73313. }
  73314. };
  73315. /**
  73316. * Serializes the shadow generator setup to a json object.
  73317. * @returns The serialized JSON object
  73318. */
  73319. ShadowGenerator.prototype.serialize = function () {
  73320. var serializationObject = {};
  73321. var shadowMap = this.getShadowMap();
  73322. if (!shadowMap) {
  73323. return serializationObject;
  73324. }
  73325. serializationObject.lightId = this._light.id;
  73326. serializationObject.mapSize = shadowMap.getRenderSize();
  73327. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73328. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73329. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73330. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73331. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73332. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73333. serializationObject.depthScale = this.depthScale;
  73334. serializationObject.darkness = this.getDarkness();
  73335. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73336. serializationObject.blurKernel = this.blurKernel;
  73337. serializationObject.blurScale = this.blurScale;
  73338. serializationObject.useKernelBlur = this.useKernelBlur;
  73339. serializationObject.transparencyShadow = this._transparencyShadow;
  73340. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73341. serializationObject.bias = this.bias;
  73342. serializationObject.normalBias = this.normalBias;
  73343. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73344. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73345. serializationObject.filteringQuality = this.filteringQuality;
  73346. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73347. serializationObject.renderList = [];
  73348. if (shadowMap.renderList) {
  73349. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73350. var mesh = shadowMap.renderList[meshIndex];
  73351. serializationObject.renderList.push(mesh.id);
  73352. }
  73353. }
  73354. return serializationObject;
  73355. };
  73356. /**
  73357. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73358. * @param parsedShadowGenerator The JSON object to parse
  73359. * @param scene The scene to create the shadow map for
  73360. * @returns The parsed shadow generator
  73361. */
  73362. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73363. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73364. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73365. var shadowMap = shadowGenerator.getShadowMap();
  73366. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73367. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73368. meshes.forEach(function (mesh) {
  73369. if (!shadowMap) {
  73370. return;
  73371. }
  73372. if (!shadowMap.renderList) {
  73373. shadowMap.renderList = [];
  73374. }
  73375. shadowMap.renderList.push(mesh);
  73376. });
  73377. }
  73378. if (parsedShadowGenerator.usePoissonSampling) {
  73379. shadowGenerator.usePoissonSampling = true;
  73380. }
  73381. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73382. shadowGenerator.useExponentialShadowMap = true;
  73383. }
  73384. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73385. shadowGenerator.useBlurExponentialShadowMap = true;
  73386. }
  73387. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73388. shadowGenerator.useCloseExponentialShadowMap = true;
  73389. }
  73390. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73391. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73392. }
  73393. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73394. shadowGenerator.usePercentageCloserFiltering = true;
  73395. }
  73396. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73397. shadowGenerator.useContactHardeningShadow = true;
  73398. }
  73399. if (parsedShadowGenerator.filteringQuality) {
  73400. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73401. }
  73402. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73403. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73404. }
  73405. // Backward compat
  73406. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73407. shadowGenerator.useExponentialShadowMap = true;
  73408. }
  73409. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73410. shadowGenerator.useBlurExponentialShadowMap = true;
  73411. }
  73412. if (parsedShadowGenerator.depthScale) {
  73413. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73414. }
  73415. if (parsedShadowGenerator.blurScale) {
  73416. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73417. }
  73418. if (parsedShadowGenerator.blurBoxOffset) {
  73419. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73420. }
  73421. if (parsedShadowGenerator.useKernelBlur) {
  73422. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73423. }
  73424. if (parsedShadowGenerator.blurKernel) {
  73425. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73426. }
  73427. if (parsedShadowGenerator.bias !== undefined) {
  73428. shadowGenerator.bias = parsedShadowGenerator.bias;
  73429. }
  73430. if (parsedShadowGenerator.normalBias !== undefined) {
  73431. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73432. }
  73433. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73434. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73435. }
  73436. if (parsedShadowGenerator.darkness) {
  73437. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73438. }
  73439. if (parsedShadowGenerator.transparencyShadow) {
  73440. shadowGenerator.setTransparencyShadow(true);
  73441. }
  73442. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73443. return shadowGenerator;
  73444. };
  73445. /**
  73446. * Shadow generator mode None: no filtering applied.
  73447. */
  73448. ShadowGenerator.FILTER_NONE = 0;
  73449. /**
  73450. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73451. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73452. */
  73453. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73454. /**
  73455. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73456. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73457. */
  73458. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73459. /**
  73460. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73461. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73462. */
  73463. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73464. /**
  73465. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73466. * edge artifacts on steep falloff.
  73467. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73468. */
  73469. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73470. /**
  73471. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73472. * edge artifacts on steep falloff.
  73473. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73474. */
  73475. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73476. /**
  73477. * Shadow generator mode PCF: Percentage Closer Filtering
  73478. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73479. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73480. */
  73481. ShadowGenerator.FILTER_PCF = 6;
  73482. /**
  73483. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73484. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73485. * Contact Hardening
  73486. */
  73487. ShadowGenerator.FILTER_PCSS = 7;
  73488. /**
  73489. * Reserved for PCF and PCSS
  73490. * Highest Quality.
  73491. *
  73492. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73493. *
  73494. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73495. */
  73496. ShadowGenerator.QUALITY_HIGH = 0;
  73497. /**
  73498. * Reserved for PCF and PCSS
  73499. * Good tradeoff for quality/perf cross devices
  73500. *
  73501. * Execute PCF on a 3*3 kernel.
  73502. *
  73503. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73504. */
  73505. ShadowGenerator.QUALITY_MEDIUM = 1;
  73506. /**
  73507. * Reserved for PCF and PCSS
  73508. * The lowest quality but the fastest.
  73509. *
  73510. * Execute PCF on a 1*1 kernel.
  73511. *
  73512. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73513. */
  73514. ShadowGenerator.QUALITY_LOW = 2;
  73515. return ShadowGenerator;
  73516. }());
  73517. BABYLON.ShadowGenerator = ShadowGenerator;
  73518. })(BABYLON || (BABYLON = {}));
  73519. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73520. var BABYLON;
  73521. (function (BABYLON) {
  73522. // Adds the parser to the scene parsers.
  73523. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73524. // Shadows
  73525. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73526. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73527. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73528. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73529. // SG would be available on their associated lights
  73530. }
  73531. }
  73532. });
  73533. /**
  73534. * Defines the shadow generator component responsible to manage any shadow generators
  73535. * in a given scene.
  73536. */
  73537. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73538. /**
  73539. * Creates a new instance of the component for the given scene
  73540. * @param scene Defines the scene to register the component in
  73541. */
  73542. function ShadowGeneratorSceneComponent(scene) {
  73543. /**
  73544. * The component name helpfull to identify the component in the list of scene components.
  73545. */
  73546. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73547. this.scene = scene;
  73548. }
  73549. /**
  73550. * Registers the component in a given scene
  73551. */
  73552. ShadowGeneratorSceneComponent.prototype.register = function () {
  73553. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73554. };
  73555. /**
  73556. * Rebuilds the elements related to this component in case of
  73557. * context lost for instance.
  73558. */
  73559. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73560. // Nothing To Do Here.
  73561. };
  73562. /**
  73563. * Serializes the component data to the specified json object
  73564. * @param serializationObject The object to serialize to
  73565. */
  73566. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73567. // Shadows
  73568. serializationObject.shadowGenerators = [];
  73569. var lights = this.scene.lights;
  73570. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73571. var light = lights_1[_i];
  73572. var shadowGenerator = light.getShadowGenerator();
  73573. if (shadowGenerator) {
  73574. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73575. }
  73576. }
  73577. };
  73578. /**
  73579. * Adds all the element from the container to the scene
  73580. * @param container the container holding the elements
  73581. */
  73582. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73583. // Nothing To Do Here. (directly attached to a light)
  73584. };
  73585. /**
  73586. * Removes all the elements in the container from the scene
  73587. * @param container contains the elements to remove
  73588. */
  73589. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73590. // Nothing To Do Here. (directly attached to a light)
  73591. };
  73592. /**
  73593. * Rebuilds the elements related to this component in case of
  73594. * context lost for instance.
  73595. */
  73596. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73597. // Nothing To Do Here.
  73598. };
  73599. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73600. // Shadows
  73601. var scene = this.scene;
  73602. if (this.scene.shadowsEnabled) {
  73603. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73604. var light = scene.lights[lightIndex];
  73605. var shadowGenerator = light.getShadowGenerator();
  73606. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73607. var shadowMap = (shadowGenerator.getShadowMap());
  73608. if (scene.textures.indexOf(shadowMap) !== -1) {
  73609. renderTargets.push(shadowMap);
  73610. }
  73611. }
  73612. }
  73613. }
  73614. };
  73615. return ShadowGeneratorSceneComponent;
  73616. }());
  73617. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73618. })(BABYLON || (BABYLON = {}));
  73619. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73620. var BABYLON;
  73621. (function (BABYLON) {
  73622. var DefaultLoadingScreen = /** @class */ (function () {
  73623. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73624. if (_loadingText === void 0) { _loadingText = ""; }
  73625. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73626. var _this = this;
  73627. this._renderingCanvas = _renderingCanvas;
  73628. this._loadingText = _loadingText;
  73629. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73630. // Resize
  73631. this._resizeLoadingUI = function () {
  73632. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73633. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73634. if (!_this._loadingDiv) {
  73635. return;
  73636. }
  73637. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73638. _this._loadingDiv.style.left = canvasRect.left + "px";
  73639. _this._loadingDiv.style.top = canvasRect.top + "px";
  73640. _this._loadingDiv.style.width = canvasRect.width + "px";
  73641. _this._loadingDiv.style.height = canvasRect.height + "px";
  73642. };
  73643. }
  73644. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73645. if (this._loadingDiv) {
  73646. // Do not add a loading screen if there is already one
  73647. return;
  73648. }
  73649. this._loadingDiv = document.createElement("div");
  73650. this._loadingDiv.id = "babylonjsLoadingDiv";
  73651. this._loadingDiv.style.opacity = "0";
  73652. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73653. this._loadingDiv.style.pointerEvents = "none";
  73654. // Loading text
  73655. this._loadingTextDiv = document.createElement("div");
  73656. this._loadingTextDiv.style.position = "absolute";
  73657. this._loadingTextDiv.style.left = "0";
  73658. this._loadingTextDiv.style.top = "50%";
  73659. this._loadingTextDiv.style.marginTop = "80px";
  73660. this._loadingTextDiv.style.width = "100%";
  73661. this._loadingTextDiv.style.height = "20px";
  73662. this._loadingTextDiv.style.fontFamily = "Arial";
  73663. this._loadingTextDiv.style.fontSize = "14px";
  73664. this._loadingTextDiv.style.color = "white";
  73665. this._loadingTextDiv.style.textAlign = "center";
  73666. this._loadingTextDiv.innerHTML = "Loading";
  73667. this._loadingDiv.appendChild(this._loadingTextDiv);
  73668. //set the predefined text
  73669. this._loadingTextDiv.innerHTML = this._loadingText;
  73670. // Generating keyframes
  73671. var style = document.createElement('style');
  73672. style.type = 'text/css';
  73673. 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 }";
  73674. style.innerHTML = keyFrames;
  73675. document.getElementsByTagName('head')[0].appendChild(style);
  73676. // Loading img
  73677. var imgBack = new Image();
  73678. 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";
  73679. imgBack.style.position = "absolute";
  73680. imgBack.style.left = "50%";
  73681. imgBack.style.top = "50%";
  73682. imgBack.style.marginLeft = "-60px";
  73683. imgBack.style.marginTop = "-60px";
  73684. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73685. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73686. imgBack.style.transformOrigin = "50% 50%";
  73687. imgBack.style.webkitTransformOrigin = "50% 50%";
  73688. this._loadingDiv.appendChild(imgBack);
  73689. this._resizeLoadingUI();
  73690. window.addEventListener("resize", this._resizeLoadingUI);
  73691. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73692. document.body.appendChild(this._loadingDiv);
  73693. this._loadingDiv.style.opacity = "1";
  73694. };
  73695. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73696. var _this = this;
  73697. if (!this._loadingDiv) {
  73698. return;
  73699. }
  73700. var onTransitionEnd = function () {
  73701. if (!_this._loadingDiv) {
  73702. return;
  73703. }
  73704. document.body.removeChild(_this._loadingDiv);
  73705. window.removeEventListener("resize", _this._resizeLoadingUI);
  73706. _this._loadingDiv = null;
  73707. };
  73708. this._loadingDiv.style.opacity = "0";
  73709. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73710. };
  73711. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73712. set: function (text) {
  73713. this._loadingText = text;
  73714. if (this._loadingTextDiv) {
  73715. this._loadingTextDiv.innerHTML = this._loadingText;
  73716. }
  73717. },
  73718. enumerable: true,
  73719. configurable: true
  73720. });
  73721. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73722. get: function () {
  73723. return this._loadingDivBackgroundColor;
  73724. },
  73725. set: function (color) {
  73726. this._loadingDivBackgroundColor = color;
  73727. if (!this._loadingDiv) {
  73728. return;
  73729. }
  73730. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73731. },
  73732. enumerable: true,
  73733. configurable: true
  73734. });
  73735. return DefaultLoadingScreen;
  73736. }());
  73737. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73738. })(BABYLON || (BABYLON = {}));
  73739. //# sourceMappingURL=babylon.loadingScreen.js.map
  73740. var BABYLON;
  73741. (function (BABYLON) {
  73742. var SceneLoaderProgressEvent = /** @class */ (function () {
  73743. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73744. this.lengthComputable = lengthComputable;
  73745. this.loaded = loaded;
  73746. this.total = total;
  73747. }
  73748. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73749. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73750. };
  73751. return SceneLoaderProgressEvent;
  73752. }());
  73753. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73754. var SceneLoader = /** @class */ (function () {
  73755. function SceneLoader() {
  73756. }
  73757. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73758. get: function () {
  73759. return 0;
  73760. },
  73761. enumerable: true,
  73762. configurable: true
  73763. });
  73764. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73765. get: function () {
  73766. return 1;
  73767. },
  73768. enumerable: true,
  73769. configurable: true
  73770. });
  73771. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73772. get: function () {
  73773. return 2;
  73774. },
  73775. enumerable: true,
  73776. configurable: true
  73777. });
  73778. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73779. get: function () {
  73780. return 3;
  73781. },
  73782. enumerable: true,
  73783. configurable: true
  73784. });
  73785. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73786. get: function () {
  73787. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73788. },
  73789. set: function (value) {
  73790. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73791. },
  73792. enumerable: true,
  73793. configurable: true
  73794. });
  73795. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73796. get: function () {
  73797. return SceneLoader._ShowLoadingScreen;
  73798. },
  73799. set: function (value) {
  73800. SceneLoader._ShowLoadingScreen = value;
  73801. },
  73802. enumerable: true,
  73803. configurable: true
  73804. });
  73805. Object.defineProperty(SceneLoader, "loggingLevel", {
  73806. get: function () {
  73807. return SceneLoader._loggingLevel;
  73808. },
  73809. set: function (value) {
  73810. SceneLoader._loggingLevel = value;
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73816. get: function () {
  73817. return SceneLoader._CleanBoneMatrixWeights;
  73818. },
  73819. set: function (value) {
  73820. SceneLoader._CleanBoneMatrixWeights = value;
  73821. },
  73822. enumerable: true,
  73823. configurable: true
  73824. });
  73825. SceneLoader._getDefaultPlugin = function () {
  73826. return SceneLoader._registeredPlugins[".babylon"];
  73827. };
  73828. SceneLoader._getPluginForExtension = function (extension) {
  73829. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73830. if (registeredPlugin) {
  73831. return registeredPlugin;
  73832. }
  73833. 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");
  73834. return SceneLoader._getDefaultPlugin();
  73835. };
  73836. SceneLoader._getPluginForDirectLoad = function (data) {
  73837. for (var extension in SceneLoader._registeredPlugins) {
  73838. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73839. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73840. return SceneLoader._registeredPlugins[extension];
  73841. }
  73842. }
  73843. return SceneLoader._getDefaultPlugin();
  73844. };
  73845. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73846. var queryStringPosition = sceneFilename.indexOf("?");
  73847. if (queryStringPosition !== -1) {
  73848. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73849. }
  73850. var dotPosition = sceneFilename.lastIndexOf(".");
  73851. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73852. return SceneLoader._getPluginForExtension(extension);
  73853. };
  73854. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73855. SceneLoader._getDirectLoad = function (sceneFilename) {
  73856. if (sceneFilename.substr(0, 5) === "data:") {
  73857. return sceneFilename.substr(5);
  73858. }
  73859. return null;
  73860. };
  73861. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73862. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73863. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73864. var plugin;
  73865. if (registeredPlugin.plugin.createPlugin) {
  73866. plugin = registeredPlugin.plugin.createPlugin();
  73867. }
  73868. else {
  73869. plugin = registeredPlugin.plugin;
  73870. }
  73871. var useArrayBuffer = registeredPlugin.isBinary;
  73872. var database;
  73873. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73874. var dataCallback = function (data, responseURL) {
  73875. if (scene.isDisposed) {
  73876. onError("Scene has been disposed");
  73877. return;
  73878. }
  73879. scene.database = database;
  73880. onSuccess(plugin, data, responseURL);
  73881. };
  73882. var request = null;
  73883. var pluginDisposed = false;
  73884. var onDisposeObservable = plugin.onDisposeObservable;
  73885. if (onDisposeObservable) {
  73886. onDisposeObservable.add(function () {
  73887. pluginDisposed = true;
  73888. if (request) {
  73889. request.abort();
  73890. request = null;
  73891. }
  73892. onDispose();
  73893. });
  73894. }
  73895. var manifestChecked = function () {
  73896. if (pluginDisposed) {
  73897. return;
  73898. }
  73899. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73900. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73901. } : undefined, database, useArrayBuffer, function (request, exception) {
  73902. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  73903. });
  73904. };
  73905. if (directLoad) {
  73906. dataCallback(directLoad);
  73907. return plugin;
  73908. }
  73909. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73910. var engine = scene.getEngine();
  73911. var canUseOfflineSupport = engine.enableOfflineSupport;
  73912. if (canUseOfflineSupport) {
  73913. // Also check for exceptions
  73914. var exceptionFound = false;
  73915. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73916. var regex = _a[_i];
  73917. if (regex.test(fileInfo.url)) {
  73918. exceptionFound = true;
  73919. break;
  73920. }
  73921. }
  73922. canUseOfflineSupport = !exceptionFound;
  73923. }
  73924. if (canUseOfflineSupport) {
  73925. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73926. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73927. }
  73928. else {
  73929. manifestChecked();
  73930. }
  73931. }
  73932. // Loading file from disk via input file or drag'n'drop
  73933. else {
  73934. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73935. if (file) {
  73936. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73937. }
  73938. else {
  73939. onError("Unable to find file named " + fileInfo.name);
  73940. }
  73941. }
  73942. return plugin;
  73943. };
  73944. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73945. var url;
  73946. var name;
  73947. if (!sceneFilename) {
  73948. url = rootUrl;
  73949. name = BABYLON.Tools.GetFilename(rootUrl);
  73950. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73951. }
  73952. else {
  73953. if (sceneFilename.substr(0, 1) === "/") {
  73954. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73955. return null;
  73956. }
  73957. url = rootUrl + sceneFilename;
  73958. name = sceneFilename;
  73959. }
  73960. ;
  73961. return {
  73962. url: url,
  73963. rootUrl: rootUrl,
  73964. name: name
  73965. };
  73966. };
  73967. // Public functions
  73968. SceneLoader.GetPluginForExtension = function (extension) {
  73969. return SceneLoader._getPluginForExtension(extension).plugin;
  73970. };
  73971. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73972. return !!SceneLoader._registeredPlugins[extension];
  73973. };
  73974. SceneLoader.RegisterPlugin = function (plugin) {
  73975. if (typeof plugin.extensions === "string") {
  73976. var extension = plugin.extensions;
  73977. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73978. plugin: plugin,
  73979. isBinary: false
  73980. };
  73981. }
  73982. else {
  73983. var extensions = plugin.extensions;
  73984. Object.keys(extensions).forEach(function (extension) {
  73985. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73986. plugin: plugin,
  73987. isBinary: extensions[extension].isBinary
  73988. };
  73989. });
  73990. }
  73991. };
  73992. /**
  73993. * Import meshes into a scene
  73994. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73995. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73996. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73997. * @param scene the instance of BABYLON.Scene to append to
  73998. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73999. * @param onProgress a callback with a progress event for each file being loaded
  74000. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74001. * @param pluginExtension the extension used to determine the plugin
  74002. * @returns The loaded plugin
  74003. */
  74004. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74005. if (sceneFilename === void 0) { sceneFilename = ""; }
  74006. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74007. if (onSuccess === void 0) { onSuccess = null; }
  74008. if (onProgress === void 0) { onProgress = null; }
  74009. if (onError === void 0) { onError = null; }
  74010. if (pluginExtension === void 0) { pluginExtension = null; }
  74011. if (!scene) {
  74012. BABYLON.Tools.Error("No scene available to import mesh to");
  74013. return null;
  74014. }
  74015. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74016. if (!fileInfo) {
  74017. return null;
  74018. }
  74019. var loadingToken = {};
  74020. scene._addPendingData(loadingToken);
  74021. var disposeHandler = function () {
  74022. scene._removePendingData(loadingToken);
  74023. };
  74024. var errorHandler = function (message, exception) {
  74025. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74026. if (onError) {
  74027. onError(scene, errorMessage, exception);
  74028. }
  74029. else {
  74030. BABYLON.Tools.Error(errorMessage);
  74031. // should the exception be thrown?
  74032. }
  74033. disposeHandler();
  74034. };
  74035. var progressHandler = onProgress ? function (event) {
  74036. try {
  74037. onProgress(event);
  74038. }
  74039. catch (e) {
  74040. errorHandler("Error in onProgress callback", e);
  74041. }
  74042. } : undefined;
  74043. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74044. scene.importedMeshesFiles.push(fileInfo.url);
  74045. if (onSuccess) {
  74046. try {
  74047. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74048. }
  74049. catch (e) {
  74050. errorHandler("Error in onSuccess callback", e);
  74051. }
  74052. }
  74053. scene._removePendingData(loadingToken);
  74054. };
  74055. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74056. if (plugin.rewriteRootURL) {
  74057. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74058. }
  74059. if (plugin.importMesh) {
  74060. var syncedPlugin = plugin;
  74061. var meshes = new Array();
  74062. var particleSystems = new Array();
  74063. var skeletons = new Array();
  74064. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  74065. return;
  74066. }
  74067. scene.loadingPluginName = plugin.name;
  74068. successHandler(meshes, particleSystems, skeletons, []);
  74069. }
  74070. else {
  74071. var asyncedPlugin = plugin;
  74072. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  74073. scene.loadingPluginName = plugin.name;
  74074. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  74075. }).catch(function (error) {
  74076. errorHandler(error.message, error);
  74077. });
  74078. }
  74079. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74080. };
  74081. /**
  74082. * Import meshes into a scene
  74083. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74084. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74085. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74086. * @param scene the instance of BABYLON.Scene to append to
  74087. * @param onProgress a callback with a progress event for each file being loaded
  74088. * @param pluginExtension the extension used to determine the plugin
  74089. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  74090. */
  74091. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74092. if (sceneFilename === void 0) { sceneFilename = ""; }
  74093. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74094. if (onProgress === void 0) { onProgress = null; }
  74095. if (pluginExtension === void 0) { pluginExtension = null; }
  74096. return new Promise(function (resolve, reject) {
  74097. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  74098. resolve({
  74099. meshes: meshes,
  74100. particleSystems: particleSystems,
  74101. skeletons: skeletons,
  74102. animationGroups: animationGroups
  74103. });
  74104. }, onProgress, function (scene, message, exception) {
  74105. reject(exception || new Error(message));
  74106. }, pluginExtension);
  74107. });
  74108. };
  74109. /**
  74110. * Load a scene
  74111. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74112. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74113. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74114. * @param onSuccess a callback with the scene when import succeeds
  74115. * @param onProgress a callback with a progress event for each file being loaded
  74116. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74117. * @param pluginExtension the extension used to determine the plugin
  74118. * @returns The loaded plugin
  74119. */
  74120. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  74121. if (onSuccess === void 0) { onSuccess = null; }
  74122. if (onProgress === void 0) { onProgress = null; }
  74123. if (onError === void 0) { onError = null; }
  74124. if (pluginExtension === void 0) { pluginExtension = null; }
  74125. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  74126. };
  74127. /**
  74128. * Load a scene
  74129. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74130. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74131. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74132. * @param onProgress a callback with a progress event for each file being loaded
  74133. * @param pluginExtension the extension used to determine the plugin
  74134. * @returns The loaded scene
  74135. */
  74136. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  74137. if (onProgress === void 0) { onProgress = null; }
  74138. if (pluginExtension === void 0) { pluginExtension = null; }
  74139. return new Promise(function (resolve, reject) {
  74140. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  74141. resolve(scene);
  74142. }, onProgress, function (scene, message, exception) {
  74143. reject(exception || new Error(message));
  74144. }, pluginExtension);
  74145. });
  74146. };
  74147. /**
  74148. * Append a scene
  74149. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74150. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74151. * @param scene is the instance of BABYLON.Scene to append to
  74152. * @param onSuccess a callback with the scene when import succeeds
  74153. * @param onProgress a callback with a progress event for each file being loaded
  74154. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74155. * @param pluginExtension the extension used to determine the plugin
  74156. * @returns The loaded plugin
  74157. */
  74158. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74159. if (sceneFilename === void 0) { sceneFilename = ""; }
  74160. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74161. if (onSuccess === void 0) { onSuccess = null; }
  74162. if (onProgress === void 0) { onProgress = null; }
  74163. if (onError === void 0) { onError = null; }
  74164. if (pluginExtension === void 0) { pluginExtension = null; }
  74165. if (!scene) {
  74166. BABYLON.Tools.Error("No scene available to append to");
  74167. return null;
  74168. }
  74169. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74170. if (!fileInfo) {
  74171. return null;
  74172. }
  74173. if (SceneLoader.ShowLoadingScreen) {
  74174. scene.getEngine().displayLoadingUI();
  74175. }
  74176. var loadingToken = {};
  74177. scene._addPendingData(loadingToken);
  74178. var disposeHandler = function () {
  74179. scene._removePendingData(loadingToken);
  74180. scene.getEngine().hideLoadingUI();
  74181. };
  74182. var errorHandler = function (message, exception) {
  74183. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  74184. if (onError) {
  74185. onError(scene, errorMessage, exception);
  74186. }
  74187. else {
  74188. BABYLON.Tools.Error(errorMessage);
  74189. // should the exception be thrown?
  74190. }
  74191. disposeHandler();
  74192. };
  74193. var progressHandler = onProgress ? function (event) {
  74194. try {
  74195. onProgress(event);
  74196. }
  74197. catch (e) {
  74198. errorHandler("Error in onProgress callback", e);
  74199. }
  74200. } : undefined;
  74201. var successHandler = function () {
  74202. if (onSuccess) {
  74203. try {
  74204. onSuccess(scene);
  74205. }
  74206. catch (e) {
  74207. errorHandler("Error in onSuccess callback", e);
  74208. }
  74209. }
  74210. scene._removePendingData(loadingToken);
  74211. };
  74212. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74213. if (plugin.load) {
  74214. var syncedPlugin = plugin;
  74215. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  74216. return;
  74217. }
  74218. scene.loadingPluginName = plugin.name;
  74219. successHandler();
  74220. }
  74221. else {
  74222. var asyncedPlugin = plugin;
  74223. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  74224. scene.loadingPluginName = plugin.name;
  74225. successHandler();
  74226. }).catch(function (error) {
  74227. errorHandler(error.message, error);
  74228. });
  74229. }
  74230. if (SceneLoader.ShowLoadingScreen) {
  74231. scene.executeWhenReady(function () {
  74232. scene.getEngine().hideLoadingUI();
  74233. });
  74234. }
  74235. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74236. };
  74237. /**
  74238. * Append a scene
  74239. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74240. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74241. * @param scene is the instance of BABYLON.Scene to append to
  74242. * @param onProgress a callback with a progress event for each file being loaded
  74243. * @param pluginExtension the extension used to determine the plugin
  74244. * @returns The given scene
  74245. */
  74246. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74247. if (sceneFilename === void 0) { sceneFilename = ""; }
  74248. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74249. if (onProgress === void 0) { onProgress = null; }
  74250. if (pluginExtension === void 0) { pluginExtension = null; }
  74251. return new Promise(function (resolve, reject) {
  74252. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  74253. resolve(scene);
  74254. }, onProgress, function (scene, message, exception) {
  74255. reject(exception || new Error(message));
  74256. }, pluginExtension);
  74257. });
  74258. };
  74259. /**
  74260. * Load a scene into an asset container
  74261. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74262. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74263. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  74264. * @param onSuccess a callback with the scene when import succeeds
  74265. * @param onProgress a callback with a progress event for each file being loaded
  74266. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74267. * @param pluginExtension the extension used to determine the plugin
  74268. * @returns The loaded plugin
  74269. */
  74270. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74271. if (sceneFilename === void 0) { sceneFilename = ""; }
  74272. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74273. if (onSuccess === void 0) { onSuccess = null; }
  74274. if (onProgress === void 0) { onProgress = null; }
  74275. if (onError === void 0) { onError = null; }
  74276. if (pluginExtension === void 0) { pluginExtension = null; }
  74277. if (!scene) {
  74278. BABYLON.Tools.Error("No scene available to load asset container to");
  74279. return null;
  74280. }
  74281. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74282. if (!fileInfo) {
  74283. return null;
  74284. }
  74285. var loadingToken = {};
  74286. scene._addPendingData(loadingToken);
  74287. var disposeHandler = function () {
  74288. scene._removePendingData(loadingToken);
  74289. };
  74290. var errorHandler = function (message, exception) {
  74291. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  74292. if (onError) {
  74293. onError(scene, errorMessage, exception);
  74294. }
  74295. else {
  74296. BABYLON.Tools.Error(errorMessage);
  74297. // should the exception be thrown?
  74298. }
  74299. disposeHandler();
  74300. };
  74301. var progressHandler = onProgress ? function (event) {
  74302. try {
  74303. onProgress(event);
  74304. }
  74305. catch (e) {
  74306. errorHandler("Error in onProgress callback", e);
  74307. }
  74308. } : undefined;
  74309. var successHandler = function (assets) {
  74310. if (onSuccess) {
  74311. try {
  74312. onSuccess(assets);
  74313. }
  74314. catch (e) {
  74315. errorHandler("Error in onSuccess callback", e);
  74316. }
  74317. }
  74318. scene._removePendingData(loadingToken);
  74319. };
  74320. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74321. if (plugin.loadAssetContainer) {
  74322. var syncedPlugin = plugin;
  74323. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74324. if (!assetContainer) {
  74325. return;
  74326. }
  74327. scene.loadingPluginName = plugin.name;
  74328. successHandler(assetContainer);
  74329. }
  74330. else if (plugin.loadAssetContainerAsync) {
  74331. var asyncedPlugin = plugin;
  74332. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74333. scene.loadingPluginName = plugin.name;
  74334. successHandler(assetContainer);
  74335. }).catch(function (error) {
  74336. errorHandler(error.message, error);
  74337. });
  74338. }
  74339. else {
  74340. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74341. }
  74342. if (SceneLoader.ShowLoadingScreen) {
  74343. scene.executeWhenReady(function () {
  74344. scene.getEngine().hideLoadingUI();
  74345. });
  74346. }
  74347. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74348. };
  74349. /**
  74350. * Load a scene into an asset container
  74351. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  74352. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  74353. * @param scene is the instance of BABYLON.Scene to append to
  74354. * @param onProgress a callback with a progress event for each file being loaded
  74355. * @param pluginExtension the extension used to determine the plugin
  74356. * @returns The loaded asset container
  74357. */
  74358. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74359. if (sceneFilename === void 0) { sceneFilename = ""; }
  74360. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74361. if (onProgress === void 0) { onProgress = null; }
  74362. if (pluginExtension === void 0) { pluginExtension = null; }
  74363. return new Promise(function (resolve, reject) {
  74364. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74365. resolve(assetContainer);
  74366. }, onProgress, function (scene, message, exception) {
  74367. reject(exception || new Error(message));
  74368. }, pluginExtension);
  74369. });
  74370. };
  74371. // Flags
  74372. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74373. SceneLoader._ShowLoadingScreen = true;
  74374. SceneLoader._CleanBoneMatrixWeights = false;
  74375. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74376. // Members
  74377. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74378. SceneLoader._registeredPlugins = {};
  74379. return SceneLoader;
  74380. }());
  74381. BABYLON.SceneLoader = SceneLoader;
  74382. ;
  74383. })(BABYLON || (BABYLON = {}));
  74384. //# sourceMappingURL=babylon.sceneLoader.js.map
  74385. var BABYLON;
  74386. (function (BABYLON) {
  74387. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74388. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74389. var parsedMaterial = parsedData.materials[index];
  74390. if (parsedMaterial.id === id) {
  74391. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74392. }
  74393. }
  74394. return null;
  74395. };
  74396. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74397. for (var i in names) {
  74398. if (mesh.name === names[i]) {
  74399. hierarchyIds.push(mesh.id);
  74400. return true;
  74401. }
  74402. }
  74403. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74404. hierarchyIds.push(mesh.id);
  74405. return true;
  74406. }
  74407. return false;
  74408. };
  74409. var logOperation = function (operation, producer) {
  74410. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74411. };
  74412. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74413. if (addToScene === void 0) { addToScene = false; }
  74414. var container = new BABYLON.AssetContainer(scene);
  74415. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74416. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74417. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74418. // and avoid problems with multiple concurrent .babylon loads.
  74419. var log = "importScene has failed JSON parse";
  74420. try {
  74421. var parsedData = JSON.parse(data);
  74422. log = "";
  74423. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74424. var index;
  74425. var cache;
  74426. // Lights
  74427. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74428. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74429. var parsedLight = parsedData.lights[index];
  74430. var light = BABYLON.Light.Parse(parsedLight, scene);
  74431. if (light) {
  74432. container.lights.push(light);
  74433. log += (index === 0 ? "\n\tLights:" : "");
  74434. log += "\n\t\t" + light.toString(fullDetails);
  74435. }
  74436. }
  74437. }
  74438. // Animations
  74439. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74440. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74441. var parsedAnimation = parsedData.animations[index];
  74442. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74443. scene.animations.push(animation);
  74444. container.animations.push(animation);
  74445. log += (index === 0 ? "\n\tAnimations:" : "");
  74446. log += "\n\t\t" + animation.toString(fullDetails);
  74447. }
  74448. }
  74449. // Materials
  74450. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74451. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74452. var parsedMaterial = parsedData.materials[index];
  74453. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74454. container.materials.push(mat);
  74455. log += (index === 0 ? "\n\tMaterials:" : "");
  74456. log += "\n\t\t" + mat.toString(fullDetails);
  74457. }
  74458. }
  74459. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74460. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74461. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74462. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74463. container.multiMaterials.push(mmat);
  74464. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74465. log += "\n\t\t" + mmat.toString(fullDetails);
  74466. }
  74467. }
  74468. // Morph targets
  74469. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74470. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74471. var managerData = _a[_i];
  74472. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74473. }
  74474. }
  74475. // Skeletons
  74476. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74477. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74478. var parsedSkeleton = parsedData.skeletons[index];
  74479. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74480. container.skeletons.push(skeleton);
  74481. log += (index === 0 ? "\n\tSkeletons:" : "");
  74482. log += "\n\t\t" + skeleton.toString(fullDetails);
  74483. }
  74484. }
  74485. // Geometries
  74486. var geometries = parsedData.geometries;
  74487. if (geometries !== undefined && geometries !== null) {
  74488. var addedGeometry = new Array();
  74489. // Boxes
  74490. var boxes = geometries.boxes;
  74491. if (boxes !== undefined && boxes !== null) {
  74492. for (index = 0, cache = boxes.length; index < cache; index++) {
  74493. var parsedBox = boxes[index];
  74494. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74495. }
  74496. }
  74497. // Spheres
  74498. var spheres = geometries.spheres;
  74499. if (spheres !== undefined && spheres !== null) {
  74500. for (index = 0, cache = spheres.length; index < cache; index++) {
  74501. var parsedSphere = spheres[index];
  74502. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74503. }
  74504. }
  74505. // Cylinders
  74506. var cylinders = geometries.cylinders;
  74507. if (cylinders !== undefined && cylinders !== null) {
  74508. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74509. var parsedCylinder = cylinders[index];
  74510. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74511. }
  74512. }
  74513. // Toruses
  74514. var toruses = geometries.toruses;
  74515. if (toruses !== undefined && toruses !== null) {
  74516. for (index = 0, cache = toruses.length; index < cache; index++) {
  74517. var parsedTorus = toruses[index];
  74518. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74519. }
  74520. }
  74521. // Grounds
  74522. var grounds = geometries.grounds;
  74523. if (grounds !== undefined && grounds !== null) {
  74524. for (index = 0, cache = grounds.length; index < cache; index++) {
  74525. var parsedGround = grounds[index];
  74526. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74527. }
  74528. }
  74529. // Planes
  74530. var planes = geometries.planes;
  74531. if (planes !== undefined && planes !== null) {
  74532. for (index = 0, cache = planes.length; index < cache; index++) {
  74533. var parsedPlane = planes[index];
  74534. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74535. }
  74536. }
  74537. // TorusKnots
  74538. var torusKnots = geometries.torusKnots;
  74539. if (torusKnots !== undefined && torusKnots !== null) {
  74540. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74541. var parsedTorusKnot = torusKnots[index];
  74542. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74543. }
  74544. }
  74545. // VertexData
  74546. var vertexData = geometries.vertexData;
  74547. if (vertexData !== undefined && vertexData !== null) {
  74548. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74549. var parsedVertexData = vertexData[index];
  74550. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74551. }
  74552. }
  74553. addedGeometry.forEach(function (g) {
  74554. if (g) {
  74555. container.geometries.push(g);
  74556. }
  74557. });
  74558. }
  74559. // Transform nodes
  74560. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74561. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74562. var parsedTransformNode = parsedData.transformNodes[index];
  74563. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74564. container.transformNodes.push(node);
  74565. }
  74566. }
  74567. // Meshes
  74568. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74569. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74570. var parsedMesh = parsedData.meshes[index];
  74571. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74572. container.meshes.push(mesh);
  74573. log += (index === 0 ? "\n\tMeshes:" : "");
  74574. log += "\n\t\t" + mesh.toString(fullDetails);
  74575. }
  74576. }
  74577. // Cameras
  74578. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74579. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74580. var parsedCamera = parsedData.cameras[index];
  74581. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74582. container.cameras.push(camera);
  74583. log += (index === 0 ? "\n\tCameras:" : "");
  74584. log += "\n\t\t" + camera.toString(fullDetails);
  74585. }
  74586. }
  74587. // Animation Groups
  74588. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74589. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74590. var parsedAnimationGroup = parsedData.animationGroups[index];
  74591. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74592. container.animationGroups.push(animationGroup);
  74593. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74594. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74595. }
  74596. }
  74597. // Browsing all the graph to connect the dots
  74598. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74599. var camera = scene.cameras[index];
  74600. if (camera._waitingParentId) {
  74601. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74602. camera._waitingParentId = null;
  74603. }
  74604. }
  74605. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74606. var light_1 = scene.lights[index];
  74607. if (light_1 && light_1._waitingParentId) {
  74608. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74609. light_1._waitingParentId = null;
  74610. }
  74611. }
  74612. // Connect parents & children and parse actions
  74613. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74614. var transformNode = scene.transformNodes[index];
  74615. if (transformNode._waitingParentId) {
  74616. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74617. transformNode._waitingParentId = null;
  74618. }
  74619. }
  74620. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74621. var mesh = scene.meshes[index];
  74622. if (mesh._waitingParentId) {
  74623. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74624. mesh._waitingParentId = null;
  74625. }
  74626. }
  74627. // freeze world matrix application
  74628. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74629. var currentMesh = scene.meshes[index];
  74630. if (currentMesh._waitingFreezeWorldMatrix) {
  74631. currentMesh.freezeWorldMatrix();
  74632. currentMesh._waitingFreezeWorldMatrix = null;
  74633. }
  74634. else {
  74635. currentMesh.computeWorldMatrix(true);
  74636. }
  74637. }
  74638. // Lights exclusions / inclusions
  74639. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74640. var light_2 = scene.lights[index];
  74641. // Excluded check
  74642. if (light_2._excludedMeshesIds.length > 0) {
  74643. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74644. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74645. if (excludedMesh) {
  74646. light_2.excludedMeshes.push(excludedMesh);
  74647. }
  74648. }
  74649. light_2._excludedMeshesIds = [];
  74650. }
  74651. // Included check
  74652. if (light_2._includedOnlyMeshesIds.length > 0) {
  74653. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74654. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74655. if (includedOnlyMesh) {
  74656. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74657. }
  74658. }
  74659. light_2._includedOnlyMeshesIds = [];
  74660. }
  74661. }
  74662. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74663. // Actions (scene) Done last as it can access other objects.
  74664. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74665. var mesh = scene.meshes[index];
  74666. if (mesh._waitingActions) {
  74667. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74668. mesh._waitingActions = null;
  74669. }
  74670. }
  74671. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74672. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74673. }
  74674. if (!addToScene) {
  74675. container.removeAllFromScene();
  74676. }
  74677. }
  74678. catch (err) {
  74679. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74680. if (onError) {
  74681. onError(msg, err);
  74682. }
  74683. else {
  74684. BABYLON.Tools.Log(msg);
  74685. throw err;
  74686. }
  74687. }
  74688. finally {
  74689. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74690. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74691. }
  74692. }
  74693. return container;
  74694. };
  74695. BABYLON.SceneLoader.RegisterPlugin({
  74696. name: "babylon.js",
  74697. extensions: ".babylon",
  74698. canDirectLoad: function (data) {
  74699. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74700. return true;
  74701. }
  74702. return false;
  74703. },
  74704. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74705. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74706. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74707. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74708. // and avoid problems with multiple concurrent .babylon loads.
  74709. var log = "importMesh has failed JSON parse";
  74710. try {
  74711. var parsedData = JSON.parse(data);
  74712. log = "";
  74713. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74714. if (!meshesNames) {
  74715. meshesNames = null;
  74716. }
  74717. else if (!Array.isArray(meshesNames)) {
  74718. meshesNames = [meshesNames];
  74719. }
  74720. var hierarchyIds = new Array();
  74721. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74722. var loadedSkeletonsIds = [];
  74723. var loadedMaterialsIds = [];
  74724. var index;
  74725. var cache;
  74726. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74727. var parsedMesh = parsedData.meshes[index];
  74728. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74729. if (meshesNames !== null) {
  74730. // Remove found mesh name from list.
  74731. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74732. }
  74733. //Geometry?
  74734. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74735. //does the file contain geometries?
  74736. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74737. //find the correct geometry and add it to the scene
  74738. var found = false;
  74739. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74740. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74741. return;
  74742. }
  74743. else {
  74744. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74745. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74746. switch (geometryType) {
  74747. case "boxes":
  74748. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74749. break;
  74750. case "spheres":
  74751. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74752. break;
  74753. case "cylinders":
  74754. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74755. break;
  74756. case "toruses":
  74757. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74758. break;
  74759. case "grounds":
  74760. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74761. break;
  74762. case "planes":
  74763. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74764. break;
  74765. case "torusKnots":
  74766. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74767. break;
  74768. case "vertexData":
  74769. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74770. break;
  74771. }
  74772. found = true;
  74773. }
  74774. });
  74775. }
  74776. });
  74777. if (found === false) {
  74778. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74779. }
  74780. }
  74781. }
  74782. // Material ?
  74783. if (parsedMesh.materialId) {
  74784. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74785. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74786. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74787. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74788. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74789. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74790. var subMatId = parsedMultiMaterial.materials[matIndex];
  74791. loadedMaterialsIds.push(subMatId);
  74792. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74793. if (mat) {
  74794. log += "\n\tMaterial " + mat.toString(fullDetails);
  74795. }
  74796. }
  74797. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74798. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74799. if (mmat) {
  74800. materialFound = true;
  74801. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74802. }
  74803. break;
  74804. }
  74805. }
  74806. }
  74807. if (materialFound === false) {
  74808. loadedMaterialsIds.push(parsedMesh.materialId);
  74809. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74810. if (!mat) {
  74811. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74812. }
  74813. else {
  74814. log += "\n\tMaterial " + mat.toString(fullDetails);
  74815. }
  74816. }
  74817. }
  74818. // Skeleton ?
  74819. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74820. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74821. if (skeletonAlreadyLoaded === false) {
  74822. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74823. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74824. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74825. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74826. skeletons.push(skeleton);
  74827. loadedSkeletonsIds.push(parsedSkeleton.id);
  74828. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74829. }
  74830. }
  74831. }
  74832. }
  74833. // Morph targets ?
  74834. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74835. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74836. var managerData = _a[_i];
  74837. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74838. }
  74839. }
  74840. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74841. meshes.push(mesh);
  74842. log += "\n\tMesh " + mesh.toString(fullDetails);
  74843. }
  74844. }
  74845. // Connecting parents
  74846. var currentMesh;
  74847. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74848. currentMesh = scene.meshes[index];
  74849. if (currentMesh._waitingParentId) {
  74850. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74851. currentMesh._waitingParentId = null;
  74852. }
  74853. }
  74854. // freeze and compute world matrix application
  74855. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74856. currentMesh = scene.meshes[index];
  74857. if (currentMesh._waitingFreezeWorldMatrix) {
  74858. currentMesh.freezeWorldMatrix();
  74859. currentMesh._waitingFreezeWorldMatrix = null;
  74860. }
  74861. else {
  74862. currentMesh.computeWorldMatrix(true);
  74863. }
  74864. }
  74865. }
  74866. // Particles
  74867. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74868. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74869. if (parser) {
  74870. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74871. var parsedParticleSystem = parsedData.particleSystems[index];
  74872. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74873. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74874. }
  74875. }
  74876. }
  74877. }
  74878. return true;
  74879. }
  74880. catch (err) {
  74881. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74882. if (onError) {
  74883. onError(msg, err);
  74884. }
  74885. else {
  74886. BABYLON.Tools.Log(msg);
  74887. throw err;
  74888. }
  74889. }
  74890. finally {
  74891. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74892. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74893. }
  74894. }
  74895. return false;
  74896. },
  74897. load: function (scene, data, rootUrl, onError) {
  74898. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74899. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74900. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74901. // and avoid problems with multiple concurrent .babylon loads.
  74902. var log = "importScene has failed JSON parse";
  74903. try {
  74904. var parsedData = JSON.parse(data);
  74905. log = "";
  74906. // Scene
  74907. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74908. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74909. }
  74910. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74911. scene.autoClear = parsedData.autoClear;
  74912. }
  74913. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74914. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74915. }
  74916. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74917. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74918. }
  74919. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74920. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74921. }
  74922. // Fog
  74923. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74924. scene.fogMode = parsedData.fogMode;
  74925. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74926. scene.fogStart = parsedData.fogStart;
  74927. scene.fogEnd = parsedData.fogEnd;
  74928. scene.fogDensity = parsedData.fogDensity;
  74929. log += "\tFog mode for scene: ";
  74930. switch (scene.fogMode) {
  74931. // getters not compiling, so using hardcoded
  74932. case 1:
  74933. log += "exp\n";
  74934. break;
  74935. case 2:
  74936. log += "exp2\n";
  74937. break;
  74938. case 3:
  74939. log += "linear\n";
  74940. break;
  74941. }
  74942. }
  74943. //Physics
  74944. if (parsedData.physicsEnabled) {
  74945. var physicsPlugin;
  74946. if (parsedData.physicsEngine === "cannon") {
  74947. physicsPlugin = new BABYLON.CannonJSPlugin();
  74948. }
  74949. else if (parsedData.physicsEngine === "oimo") {
  74950. physicsPlugin = new BABYLON.OimoJSPlugin();
  74951. }
  74952. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74953. //else - default engine, which is currently oimo
  74954. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74955. scene.enablePhysics(physicsGravity, physicsPlugin);
  74956. }
  74957. // Metadata
  74958. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74959. scene.metadata = parsedData.metadata;
  74960. }
  74961. //collisions, if defined. otherwise, default is true
  74962. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74963. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74964. }
  74965. scene.workerCollisions = !!parsedData.workerCollisions;
  74966. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74967. if (!container) {
  74968. return false;
  74969. }
  74970. if (parsedData.autoAnimate) {
  74971. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74972. }
  74973. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74974. scene.setActiveCameraByID(parsedData.activeCameraID);
  74975. }
  74976. // Environment texture
  74977. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74978. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74979. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74980. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74981. if (parsedData.environmentTextureRotationY) {
  74982. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74983. }
  74984. scene.environmentTexture = hdrTexture;
  74985. }
  74986. else {
  74987. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74988. if (parsedData.environmentTextureRotationY) {
  74989. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74990. }
  74991. scene.environmentTexture = cubeTexture;
  74992. }
  74993. if (parsedData.createDefaultSkybox === true) {
  74994. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74995. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74996. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74997. }
  74998. }
  74999. // Finish
  75000. return true;
  75001. }
  75002. catch (err) {
  75003. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  75004. if (onError) {
  75005. onError(msg, err);
  75006. }
  75007. else {
  75008. BABYLON.Tools.Log(msg);
  75009. throw err;
  75010. }
  75011. }
  75012. finally {
  75013. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75014. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75015. }
  75016. }
  75017. return false;
  75018. },
  75019. loadAssetContainer: function (scene, data, rootUrl, onError) {
  75020. var container = loadAssetContainer(scene, data, rootUrl, onError);
  75021. return container;
  75022. }
  75023. });
  75024. })(BABYLON || (BABYLON = {}));
  75025. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75026. var BABYLON;
  75027. (function (BABYLON) {
  75028. var FilesInput = /** @class */ (function () {
  75029. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75030. this.onProcessFileCallback = function () { return true; };
  75031. this._engine = engine;
  75032. this._currentScene = scene;
  75033. this._sceneLoadedCallback = sceneLoadedCallback;
  75034. this._progressCallback = progressCallback;
  75035. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75036. this._textureLoadingCallback = textureLoadingCallback;
  75037. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75038. this._onReloadCallback = onReloadCallback;
  75039. this._errorCallback = errorCallback;
  75040. }
  75041. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  75042. var _this = this;
  75043. if (elementToMonitor) {
  75044. this._elementToMonitor = elementToMonitor;
  75045. this._dragEnterHandler = function (e) { _this.drag(e); };
  75046. this._dragOverHandler = function (e) { _this.drag(e); };
  75047. this._dropHandler = function (e) { _this.drop(e); };
  75048. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  75049. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  75050. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  75051. }
  75052. };
  75053. FilesInput.prototype.dispose = function () {
  75054. if (!this._elementToMonitor) {
  75055. return;
  75056. }
  75057. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  75058. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  75059. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  75060. };
  75061. FilesInput.prototype.renderFunction = function () {
  75062. if (this._additionalRenderLoopLogicCallback) {
  75063. this._additionalRenderLoopLogicCallback();
  75064. }
  75065. if (this._currentScene) {
  75066. if (this._textureLoadingCallback) {
  75067. var remaining = this._currentScene.getWaitingItemsCount();
  75068. if (remaining > 0) {
  75069. this._textureLoadingCallback(remaining);
  75070. }
  75071. }
  75072. this._currentScene.render();
  75073. }
  75074. };
  75075. FilesInput.prototype.drag = function (e) {
  75076. e.stopPropagation();
  75077. e.preventDefault();
  75078. };
  75079. FilesInput.prototype.drop = function (eventDrop) {
  75080. eventDrop.stopPropagation();
  75081. eventDrop.preventDefault();
  75082. this.loadFiles(eventDrop);
  75083. };
  75084. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  75085. var _this = this;
  75086. var reader = folder.createReader();
  75087. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  75088. reader.readEntries(function (entries) {
  75089. remaining.count += entries.length;
  75090. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  75091. var entry = entries_1[_i];
  75092. if (entry.isFile) {
  75093. entry.file(function (file) {
  75094. file.correctName = relativePath + file.name;
  75095. files.push(file);
  75096. if (--remaining.count === 0) {
  75097. callback();
  75098. }
  75099. });
  75100. }
  75101. else if (entry.isDirectory) {
  75102. _this._traverseFolder(entry, files, remaining, callback);
  75103. }
  75104. }
  75105. if (--remaining.count) {
  75106. callback();
  75107. }
  75108. });
  75109. };
  75110. FilesInput.prototype._processFiles = function (files) {
  75111. for (var i = 0; i < files.length; i++) {
  75112. var name = files[i].correctName.toLowerCase();
  75113. var extension = name.split('.').pop();
  75114. if (!this.onProcessFileCallback(files[i], name, extension)) {
  75115. continue;
  75116. }
  75117. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  75118. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  75119. this._sceneFileToLoad = files[i];
  75120. }
  75121. FilesInput.FilesToLoad[name] = files[i];
  75122. }
  75123. };
  75124. FilesInput.prototype.loadFiles = function (event) {
  75125. var _this = this;
  75126. // Handling data transfer via drag'n'drop
  75127. if (event && event.dataTransfer && event.dataTransfer.files) {
  75128. this._filesToLoad = event.dataTransfer.files;
  75129. }
  75130. // Handling files from input files
  75131. if (event && event.target && event.target.files) {
  75132. this._filesToLoad = event.target.files;
  75133. }
  75134. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  75135. return;
  75136. }
  75137. if (this._startingProcessingFilesCallback) {
  75138. this._startingProcessingFilesCallback(this._filesToLoad);
  75139. }
  75140. if (this._filesToLoad && this._filesToLoad.length > 0) {
  75141. var files_1 = new Array();
  75142. var folders = [];
  75143. var items = event.dataTransfer ? event.dataTransfer.items : null;
  75144. for (var i = 0; i < this._filesToLoad.length; i++) {
  75145. var fileToLoad = this._filesToLoad[i];
  75146. var name_1 = fileToLoad.name.toLowerCase();
  75147. var entry = void 0;
  75148. fileToLoad.correctName = name_1;
  75149. if (items) {
  75150. var item = items[i];
  75151. if (item.getAsEntry) {
  75152. entry = item.getAsEntry();
  75153. }
  75154. else if (item.webkitGetAsEntry) {
  75155. entry = item.webkitGetAsEntry();
  75156. }
  75157. }
  75158. if (!entry) {
  75159. files_1.push(fileToLoad);
  75160. }
  75161. else {
  75162. if (entry.isDirectory) {
  75163. folders.push(entry);
  75164. }
  75165. else {
  75166. files_1.push(fileToLoad);
  75167. }
  75168. }
  75169. }
  75170. if (folders.length === 0) {
  75171. this._processFiles(files_1);
  75172. this._processReload();
  75173. }
  75174. else {
  75175. var remaining = { count: folders.length };
  75176. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  75177. var folder = folders_1[_i];
  75178. this._traverseFolder(folder, files_1, remaining, function () {
  75179. _this._processFiles(files_1);
  75180. if (remaining.count === 0) {
  75181. _this._processReload();
  75182. }
  75183. });
  75184. }
  75185. }
  75186. }
  75187. };
  75188. FilesInput.prototype._processReload = function () {
  75189. if (this._onReloadCallback) {
  75190. this._onReloadCallback(this._sceneFileToLoad);
  75191. }
  75192. else {
  75193. this.reload();
  75194. }
  75195. };
  75196. FilesInput.prototype.reload = function () {
  75197. var _this = this;
  75198. // If a scene file has been provided
  75199. if (this._sceneFileToLoad) {
  75200. if (this._currentScene) {
  75201. if (BABYLON.Tools.errorsCount > 0) {
  75202. BABYLON.Tools.ClearLogCache();
  75203. }
  75204. this._engine.stopRenderLoop();
  75205. }
  75206. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  75207. if (_this._progressCallback) {
  75208. _this._progressCallback(progress);
  75209. }
  75210. }).then(function (scene) {
  75211. if (_this._currentScene) {
  75212. _this._currentScene.dispose();
  75213. }
  75214. _this._currentScene = scene;
  75215. if (_this._sceneLoadedCallback) {
  75216. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  75217. }
  75218. // Wait for textures and shaders to be ready
  75219. _this._currentScene.executeWhenReady(function () {
  75220. _this._engine.runRenderLoop(function () {
  75221. _this.renderFunction();
  75222. });
  75223. });
  75224. }).catch(function (error) {
  75225. if (_this._errorCallback) {
  75226. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  75227. }
  75228. });
  75229. }
  75230. else {
  75231. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  75232. }
  75233. };
  75234. FilesInput.FilesToLoad = {};
  75235. return FilesInput;
  75236. }());
  75237. BABYLON.FilesInput = FilesInput;
  75238. })(BABYLON || (BABYLON = {}));
  75239. //# sourceMappingURL=babylon.filesInput.js.map
  75240. var BABYLON;
  75241. (function (BABYLON) {
  75242. var Tags = /** @class */ (function () {
  75243. function Tags() {
  75244. }
  75245. Tags.EnableFor = function (obj) {
  75246. obj._tags = obj._tags || {};
  75247. obj.hasTags = function () {
  75248. return Tags.HasTags(obj);
  75249. };
  75250. obj.addTags = function (tagsString) {
  75251. return Tags.AddTagsTo(obj, tagsString);
  75252. };
  75253. obj.removeTags = function (tagsString) {
  75254. return Tags.RemoveTagsFrom(obj, tagsString);
  75255. };
  75256. obj.matchesTagsQuery = function (tagsQuery) {
  75257. return Tags.MatchesQuery(obj, tagsQuery);
  75258. };
  75259. };
  75260. Tags.DisableFor = function (obj) {
  75261. delete obj._tags;
  75262. delete obj.hasTags;
  75263. delete obj.addTags;
  75264. delete obj.removeTags;
  75265. delete obj.matchesTagsQuery;
  75266. };
  75267. Tags.HasTags = function (obj) {
  75268. if (!obj._tags) {
  75269. return false;
  75270. }
  75271. return !BABYLON.Tools.IsEmpty(obj._tags);
  75272. };
  75273. Tags.GetTags = function (obj, asString) {
  75274. if (asString === void 0) { asString = true; }
  75275. if (!obj._tags) {
  75276. return null;
  75277. }
  75278. if (asString) {
  75279. var tagsArray = [];
  75280. for (var tag in obj._tags) {
  75281. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  75282. tagsArray.push(tag);
  75283. }
  75284. }
  75285. return tagsArray.join(" ");
  75286. }
  75287. else {
  75288. return obj._tags;
  75289. }
  75290. };
  75291. // the tags 'true' and 'false' are reserved and cannot be used as tags
  75292. // a tag cannot start with '||', '&&', and '!'
  75293. // it cannot contain whitespaces
  75294. Tags.AddTagsTo = function (obj, tagsString) {
  75295. if (!tagsString) {
  75296. return;
  75297. }
  75298. if (typeof tagsString !== "string") {
  75299. return;
  75300. }
  75301. var tags = tagsString.split(" ");
  75302. tags.forEach(function (tag, index, array) {
  75303. Tags._AddTagTo(obj, tag);
  75304. });
  75305. };
  75306. Tags._AddTagTo = function (obj, tag) {
  75307. tag = tag.trim();
  75308. if (tag === "" || tag === "true" || tag === "false") {
  75309. return;
  75310. }
  75311. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  75312. return;
  75313. }
  75314. Tags.EnableFor(obj);
  75315. obj._tags[tag] = true;
  75316. };
  75317. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75318. if (!Tags.HasTags(obj)) {
  75319. return;
  75320. }
  75321. var tags = tagsString.split(" ");
  75322. for (var t in tags) {
  75323. Tags._RemoveTagFrom(obj, tags[t]);
  75324. }
  75325. };
  75326. Tags._RemoveTagFrom = function (obj, tag) {
  75327. delete obj._tags[tag];
  75328. };
  75329. Tags.MatchesQuery = function (obj, tagsQuery) {
  75330. if (tagsQuery === undefined) {
  75331. return true;
  75332. }
  75333. if (tagsQuery === "") {
  75334. return Tags.HasTags(obj);
  75335. }
  75336. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75337. };
  75338. return Tags;
  75339. }());
  75340. BABYLON.Tags = Tags;
  75341. })(BABYLON || (BABYLON = {}));
  75342. //# sourceMappingURL=babylon.tags.js.map
  75343. var BABYLON;
  75344. (function (BABYLON) {
  75345. /**
  75346. * Class used to evalaute queries containing `and` and `or` operators
  75347. */
  75348. var AndOrNotEvaluator = /** @class */ (function () {
  75349. function AndOrNotEvaluator() {
  75350. }
  75351. /**
  75352. * Evaluate a query
  75353. * @param query defines the query to evaluate
  75354. * @param evaluateCallback defines the callback used to filter result
  75355. * @returns true if the query matches
  75356. */
  75357. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75358. if (!query.match(/\([^\(\)]*\)/g)) {
  75359. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75360. }
  75361. else {
  75362. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75363. // remove parenthesis
  75364. r = r.slice(1, r.length - 1);
  75365. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75366. });
  75367. }
  75368. if (query === "true") {
  75369. return true;
  75370. }
  75371. if (query === "false") {
  75372. return false;
  75373. }
  75374. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75375. };
  75376. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75377. evaluateCallback = evaluateCallback || (function (r) {
  75378. return r === "true" ? true : false;
  75379. });
  75380. var result;
  75381. var or = parenthesisContent.split("||");
  75382. for (var i in or) {
  75383. if (or.hasOwnProperty(i)) {
  75384. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75385. var and = ori.split("&&");
  75386. if (and.length > 1) {
  75387. for (var j = 0; j < and.length; ++j) {
  75388. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75389. if (andj !== "true" && andj !== "false") {
  75390. if (andj[0] === "!") {
  75391. result = !evaluateCallback(andj.substring(1));
  75392. }
  75393. else {
  75394. result = evaluateCallback(andj);
  75395. }
  75396. }
  75397. else {
  75398. result = andj === "true" ? true : false;
  75399. }
  75400. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75401. ori = "false";
  75402. break;
  75403. }
  75404. }
  75405. }
  75406. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75407. result = true;
  75408. break;
  75409. }
  75410. // result equals false (or undefined)
  75411. if (ori !== "true" && ori !== "false") {
  75412. if (ori[0] === "!") {
  75413. result = !evaluateCallback(ori.substring(1));
  75414. }
  75415. else {
  75416. result = evaluateCallback(ori);
  75417. }
  75418. }
  75419. else {
  75420. result = ori === "true" ? true : false;
  75421. }
  75422. }
  75423. }
  75424. // the whole parenthesis scope is replaced by 'true' or 'false'
  75425. return result ? "true" : "false";
  75426. };
  75427. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75428. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75429. // remove whitespaces
  75430. r = r.replace(/[\s]/g, function () { return ""; });
  75431. return r.length % 2 ? "!" : "";
  75432. });
  75433. booleanString = booleanString.trim();
  75434. if (booleanString === "!true") {
  75435. booleanString = "false";
  75436. }
  75437. else if (booleanString === "!false") {
  75438. booleanString = "true";
  75439. }
  75440. return booleanString;
  75441. };
  75442. return AndOrNotEvaluator;
  75443. }());
  75444. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75445. })(BABYLON || (BABYLON = {}));
  75446. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75447. var BABYLON;
  75448. (function (BABYLON) {
  75449. /**
  75450. * Class used to enable access to IndexedDB
  75451. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75452. */
  75453. var Database = /** @class */ (function () {
  75454. /**
  75455. * Creates a new Database
  75456. * @param urlToScene defines the url to load the scene
  75457. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75458. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75459. */
  75460. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75461. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75462. var _this = this;
  75463. // Handling various flavors of prefixed version of IndexedDB
  75464. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75465. this.callbackManifestChecked = callbackManifestChecked;
  75466. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75467. this.db = null;
  75468. this._enableSceneOffline = false;
  75469. this._enableTexturesOffline = false;
  75470. this.manifestVersionFound = 0;
  75471. this.mustUpdateRessources = false;
  75472. this.hasReachedQuota = false;
  75473. if (!Database.IDBStorageEnabled) {
  75474. this.callbackManifestChecked(true);
  75475. }
  75476. else {
  75477. if (disableManifestCheck) {
  75478. this._enableSceneOffline = true;
  75479. this._enableTexturesOffline = true;
  75480. this.manifestVersionFound = 1;
  75481. BABYLON.Tools.SetImmediate(function () {
  75482. _this.callbackManifestChecked(true);
  75483. });
  75484. }
  75485. else {
  75486. this._checkManifestFile();
  75487. }
  75488. }
  75489. }
  75490. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75491. /**
  75492. * Gets a boolean indicating if scene must be saved in the database
  75493. */
  75494. get: function () {
  75495. return this._enableSceneOffline;
  75496. },
  75497. enumerable: true,
  75498. configurable: true
  75499. });
  75500. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75501. /**
  75502. * Gets a boolean indicating if textures must be saved in the database
  75503. */
  75504. get: function () {
  75505. return this._enableTexturesOffline;
  75506. },
  75507. enumerable: true,
  75508. configurable: true
  75509. });
  75510. Database.prototype._checkManifestFile = function () {
  75511. var _this = this;
  75512. var noManifestFile = function () {
  75513. _this._enableSceneOffline = false;
  75514. _this._enableTexturesOffline = false;
  75515. _this.callbackManifestChecked(false);
  75516. };
  75517. var timeStampUsed = false;
  75518. var manifestURL = this.currentSceneUrl + ".manifest";
  75519. var xhr = new XMLHttpRequest();
  75520. if (navigator.onLine) {
  75521. // Adding a timestamp to by-pass browsers' cache
  75522. timeStampUsed = true;
  75523. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75524. }
  75525. xhr.open("GET", manifestURL, true);
  75526. xhr.addEventListener("load", function () {
  75527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75528. try {
  75529. var manifestFile = JSON.parse(xhr.response);
  75530. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75531. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75532. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75533. _this.manifestVersionFound = manifestFile.version;
  75534. }
  75535. if (_this.callbackManifestChecked) {
  75536. _this.callbackManifestChecked(true);
  75537. }
  75538. }
  75539. catch (ex) {
  75540. noManifestFile();
  75541. }
  75542. }
  75543. else {
  75544. noManifestFile();
  75545. }
  75546. }, false);
  75547. xhr.addEventListener("error", function (event) {
  75548. if (timeStampUsed) {
  75549. timeStampUsed = false;
  75550. // Let's retry without the timeStamp
  75551. // It could fail when coupled with HTML5 Offline API
  75552. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75553. xhr.open("GET", retryManifestURL, true);
  75554. xhr.send();
  75555. }
  75556. else {
  75557. noManifestFile();
  75558. }
  75559. }, false);
  75560. try {
  75561. xhr.send();
  75562. }
  75563. catch (ex) {
  75564. BABYLON.Tools.Error("Error on XHR send request.");
  75565. this.callbackManifestChecked(false);
  75566. }
  75567. };
  75568. /**
  75569. * Open the database and make it available
  75570. * @param successCallback defines the callback to call on success
  75571. * @param errorCallback defines the callback to call on error
  75572. */
  75573. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75574. var _this = this;
  75575. var handleError = function () {
  75576. _this.isSupported = false;
  75577. if (errorCallback)
  75578. errorCallback();
  75579. };
  75580. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75581. // Your browser doesn't support IndexedDB
  75582. this.isSupported = false;
  75583. if (errorCallback)
  75584. errorCallback();
  75585. }
  75586. else {
  75587. // If the DB hasn't been opened or created yet
  75588. if (!this.db) {
  75589. this.hasReachedQuota = false;
  75590. this.isSupported = true;
  75591. var request = this.idbFactory.open("babylonjs", 1);
  75592. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75593. request.onerror = function (event) {
  75594. handleError();
  75595. };
  75596. // executes when a version change transaction cannot complete due to other active transactions
  75597. request.onblocked = function (event) {
  75598. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75599. handleError();
  75600. };
  75601. // DB has been opened successfully
  75602. request.onsuccess = function (event) {
  75603. _this.db = request.result;
  75604. successCallback();
  75605. };
  75606. // Initialization of the DB. Creating Scenes & Textures stores
  75607. request.onupgradeneeded = function (event) {
  75608. _this.db = (event.target).result;
  75609. if (_this.db) {
  75610. try {
  75611. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75612. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75613. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75614. }
  75615. catch (ex) {
  75616. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75617. handleError();
  75618. }
  75619. }
  75620. };
  75621. }
  75622. // DB has already been created and opened
  75623. else {
  75624. if (successCallback)
  75625. successCallback();
  75626. }
  75627. }
  75628. };
  75629. /**
  75630. * Loads an image from the database
  75631. * @param url defines the url to load from
  75632. * @param image defines the target DOM image
  75633. */
  75634. Database.prototype.loadImageFromDB = function (url, image) {
  75635. var _this = this;
  75636. var completeURL = Database._ReturnFullUrlLocation(url);
  75637. var saveAndLoadImage = function () {
  75638. if (!_this.hasReachedQuota && _this.db !== null) {
  75639. // the texture is not yet in the DB, let's try to save it
  75640. _this._saveImageIntoDBAsync(completeURL, image);
  75641. }
  75642. // If the texture is not in the DB and we've reached the DB quota limit
  75643. // let's load it directly from the web
  75644. else {
  75645. image.src = url;
  75646. }
  75647. };
  75648. if (!this.mustUpdateRessources) {
  75649. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75650. }
  75651. // First time we're download the images or update requested in the manifest file by a version change
  75652. else {
  75653. saveAndLoadImage();
  75654. }
  75655. };
  75656. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75657. if (this.isSupported && this.db !== null) {
  75658. var texture;
  75659. var transaction = this.db.transaction(["textures"]);
  75660. transaction.onabort = function (event) {
  75661. image.src = url;
  75662. };
  75663. transaction.oncomplete = function (event) {
  75664. var blobTextureURL;
  75665. if (texture) {
  75666. var URL = window.URL || window.webkitURL;
  75667. blobTextureURL = URL.createObjectURL(texture.data);
  75668. image.onerror = function () {
  75669. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75670. image.src = url;
  75671. };
  75672. image.src = blobTextureURL;
  75673. }
  75674. else {
  75675. notInDBCallback();
  75676. }
  75677. };
  75678. var getRequest = transaction.objectStore("textures").get(url);
  75679. getRequest.onsuccess = function (event) {
  75680. texture = (event.target).result;
  75681. };
  75682. getRequest.onerror = function (event) {
  75683. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75684. image.src = url;
  75685. };
  75686. }
  75687. else {
  75688. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75689. image.src = url;
  75690. }
  75691. };
  75692. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75693. var _this = this;
  75694. if (this.isSupported) {
  75695. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75696. var generateBlobUrl = function () {
  75697. var blobTextureURL;
  75698. if (blob) {
  75699. var URL = window.URL || window.webkitURL;
  75700. try {
  75701. blobTextureURL = URL.createObjectURL(blob);
  75702. }
  75703. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75704. catch (ex) {
  75705. blobTextureURL = URL.createObjectURL(blob);
  75706. }
  75707. }
  75708. if (blobTextureURL) {
  75709. image.src = blobTextureURL;
  75710. }
  75711. };
  75712. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75713. var xhr = new XMLHttpRequest(), blob;
  75714. xhr.open("GET", url, true);
  75715. xhr.responseType = "blob";
  75716. xhr.addEventListener("load", function () {
  75717. if (xhr.status === 200 && _this.db) {
  75718. // Blob as response (XHR2)
  75719. blob = xhr.response;
  75720. var transaction = _this.db.transaction(["textures"], "readwrite");
  75721. // the transaction could abort because of a QuotaExceededError error
  75722. transaction.onabort = function (event) {
  75723. try {
  75724. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75725. var srcElement = (event.srcElement || event.target);
  75726. var error = srcElement.error;
  75727. if (error && error.name === "QuotaExceededError") {
  75728. _this.hasReachedQuota = true;
  75729. }
  75730. }
  75731. catch (ex) { }
  75732. generateBlobUrl();
  75733. };
  75734. transaction.oncomplete = function (event) {
  75735. generateBlobUrl();
  75736. };
  75737. var newTexture = { textureUrl: url, data: blob };
  75738. try {
  75739. // Put the blob into the dabase
  75740. var addRequest = transaction.objectStore("textures").put(newTexture);
  75741. addRequest.onsuccess = function (event) {
  75742. };
  75743. addRequest.onerror = function (event) {
  75744. generateBlobUrl();
  75745. };
  75746. }
  75747. catch (ex) {
  75748. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75749. if (ex.code === 25) {
  75750. Database.IsUASupportingBlobStorage = false;
  75751. }
  75752. image.src = url;
  75753. }
  75754. }
  75755. else {
  75756. image.src = url;
  75757. }
  75758. }, false);
  75759. xhr.addEventListener("error", function (event) {
  75760. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75761. image.src = url;
  75762. }, false);
  75763. xhr.send();
  75764. }
  75765. else {
  75766. image.src = url;
  75767. }
  75768. }
  75769. else {
  75770. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75771. image.src = url;
  75772. }
  75773. };
  75774. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75775. var _this = this;
  75776. var updateVersion = function () {
  75777. // the version is not yet in the DB or we need to update it
  75778. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75779. };
  75780. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75781. };
  75782. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75783. var _this = this;
  75784. if (this.isSupported && this.db) {
  75785. var version;
  75786. try {
  75787. var transaction = this.db.transaction(["versions"]);
  75788. transaction.oncomplete = function (event) {
  75789. if (version) {
  75790. // If the version in the JSON file is different from the version in DB
  75791. if (_this.manifestVersionFound !== version.data) {
  75792. _this.mustUpdateRessources = true;
  75793. updateInDBCallback();
  75794. }
  75795. else {
  75796. callback(version.data);
  75797. }
  75798. }
  75799. // version was not found in DB
  75800. else {
  75801. _this.mustUpdateRessources = true;
  75802. updateInDBCallback();
  75803. }
  75804. };
  75805. transaction.onabort = function (event) {
  75806. callback(-1);
  75807. };
  75808. var getRequest = transaction.objectStore("versions").get(url);
  75809. getRequest.onsuccess = function (event) {
  75810. version = (event.target).result;
  75811. };
  75812. getRequest.onerror = function (event) {
  75813. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75814. callback(-1);
  75815. };
  75816. }
  75817. catch (ex) {
  75818. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75819. callback(-1);
  75820. }
  75821. }
  75822. else {
  75823. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75824. callback(-1);
  75825. }
  75826. };
  75827. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75828. var _this = this;
  75829. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75830. try {
  75831. // Open a transaction to the database
  75832. var transaction = this.db.transaction(["versions"], "readwrite");
  75833. // the transaction could abort because of a QuotaExceededError error
  75834. transaction.onabort = function (event) {
  75835. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75836. var error = event.srcElement['error'];
  75837. if (error && error.name === "QuotaExceededError") {
  75838. _this.hasReachedQuota = true;
  75839. }
  75840. }
  75841. catch (ex) { }
  75842. callback(-1);
  75843. };
  75844. transaction.oncomplete = function (event) {
  75845. callback(_this.manifestVersionFound);
  75846. };
  75847. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75848. // Put the scene into the database
  75849. var addRequest = transaction.objectStore("versions").put(newVersion);
  75850. addRequest.onsuccess = function (event) {
  75851. };
  75852. addRequest.onerror = function (event) {
  75853. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75854. };
  75855. }
  75856. catch (ex) {
  75857. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75858. callback(-1);
  75859. }
  75860. }
  75861. else {
  75862. callback(-1);
  75863. }
  75864. };
  75865. /**
  75866. * Loads a file from database
  75867. * @param url defines the URL to load from
  75868. * @param sceneLoaded defines a callback to call on success
  75869. * @param progressCallBack defines a callback to call when progress changed
  75870. * @param errorCallback defines a callback to call on error
  75871. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75872. */
  75873. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75874. var _this = this;
  75875. var completeUrl = Database._ReturnFullUrlLocation(url);
  75876. var saveAndLoadFile = function () {
  75877. // the scene is not yet in the DB, let's try to save it
  75878. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75879. };
  75880. this._checkVersionFromDB(completeUrl, function (version) {
  75881. if (version !== -1) {
  75882. if (!_this.mustUpdateRessources) {
  75883. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75884. }
  75885. else {
  75886. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75887. }
  75888. }
  75889. else {
  75890. if (errorCallback) {
  75891. errorCallback();
  75892. }
  75893. }
  75894. });
  75895. };
  75896. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75897. if (this.isSupported && this.db) {
  75898. var targetStore;
  75899. if (url.indexOf(".babylon") !== -1) {
  75900. targetStore = "scenes";
  75901. }
  75902. else {
  75903. targetStore = "textures";
  75904. }
  75905. var file;
  75906. var transaction = this.db.transaction([targetStore]);
  75907. transaction.oncomplete = function (event) {
  75908. if (file) {
  75909. callback(file.data);
  75910. }
  75911. // file was not found in DB
  75912. else {
  75913. notInDBCallback();
  75914. }
  75915. };
  75916. transaction.onabort = function (event) {
  75917. notInDBCallback();
  75918. };
  75919. var getRequest = transaction.objectStore(targetStore).get(url);
  75920. getRequest.onsuccess = function (event) {
  75921. file = (event.target).result;
  75922. };
  75923. getRequest.onerror = function (event) {
  75924. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75925. notInDBCallback();
  75926. };
  75927. }
  75928. else {
  75929. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75930. callback();
  75931. }
  75932. };
  75933. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75934. var _this = this;
  75935. if (this.isSupported) {
  75936. var targetStore;
  75937. if (url.indexOf(".babylon") !== -1) {
  75938. targetStore = "scenes";
  75939. }
  75940. else {
  75941. targetStore = "textures";
  75942. }
  75943. // Create XHR
  75944. var xhr = new XMLHttpRequest();
  75945. var fileData;
  75946. xhr.open("GET", url + "?" + Date.now(), true);
  75947. if (useArrayBuffer) {
  75948. xhr.responseType = "arraybuffer";
  75949. }
  75950. if (progressCallback) {
  75951. xhr.onprogress = progressCallback;
  75952. }
  75953. xhr.addEventListener("load", function () {
  75954. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75955. // Blob as response (XHR2)
  75956. //fileData = xhr.responseText;
  75957. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75958. if (!_this.hasReachedQuota && _this.db) {
  75959. // Open a transaction to the database
  75960. var transaction = _this.db.transaction([targetStore], "readwrite");
  75961. // the transaction could abort because of a QuotaExceededError error
  75962. transaction.onabort = function (event) {
  75963. try {
  75964. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75965. var error = event.srcElement['error'];
  75966. if (error && error.name === "QuotaExceededError") {
  75967. _this.hasReachedQuota = true;
  75968. }
  75969. }
  75970. catch (ex) { }
  75971. callback(fileData);
  75972. };
  75973. transaction.oncomplete = function (event) {
  75974. callback(fileData);
  75975. };
  75976. var newFile;
  75977. if (targetStore === "scenes") {
  75978. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75979. }
  75980. else {
  75981. newFile = { textureUrl: url, data: fileData };
  75982. }
  75983. try {
  75984. // Put the scene into the database
  75985. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75986. addRequest.onsuccess = function (event) {
  75987. };
  75988. addRequest.onerror = function (event) {
  75989. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75990. };
  75991. }
  75992. catch (ex) {
  75993. callback(fileData);
  75994. }
  75995. }
  75996. else {
  75997. callback(fileData);
  75998. }
  75999. }
  76000. else {
  76001. if (xhr.status >= 400 && errorCallback) {
  76002. errorCallback(xhr);
  76003. }
  76004. else {
  76005. callback();
  76006. }
  76007. }
  76008. }, false);
  76009. xhr.addEventListener("error", function (event) {
  76010. BABYLON.Tools.Error("error on XHR request.");
  76011. callback();
  76012. }, false);
  76013. xhr.send();
  76014. }
  76015. else {
  76016. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76017. callback();
  76018. }
  76019. };
  76020. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  76021. Database.IsUASupportingBlobStorage = true;
  76022. /** Gets a boolean indicating if Database storate is enabled */
  76023. Database.IDBStorageEnabled = true;
  76024. Database._ParseURL = function (url) {
  76025. var a = document.createElement('a');
  76026. a.href = url;
  76027. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  76028. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  76029. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  76030. return absLocation;
  76031. };
  76032. Database._ReturnFullUrlLocation = function (url) {
  76033. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  76034. return (Database._ParseURL(window.location.href) + url);
  76035. }
  76036. else {
  76037. return url;
  76038. }
  76039. };
  76040. return Database;
  76041. }());
  76042. BABYLON.Database = Database;
  76043. })(BABYLON || (BABYLON = {}));
  76044. //# sourceMappingURL=babylon.database.js.map
  76045. var BABYLON;
  76046. (function (BABYLON) {
  76047. var FresnelParameters = /** @class */ (function () {
  76048. function FresnelParameters() {
  76049. this._isEnabled = true;
  76050. this.leftColor = BABYLON.Color3.White();
  76051. this.rightColor = BABYLON.Color3.Black();
  76052. this.bias = 0;
  76053. this.power = 1;
  76054. }
  76055. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  76056. get: function () {
  76057. return this._isEnabled;
  76058. },
  76059. set: function (value) {
  76060. if (this._isEnabled === value) {
  76061. return;
  76062. }
  76063. this._isEnabled = value;
  76064. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  76065. },
  76066. enumerable: true,
  76067. configurable: true
  76068. });
  76069. FresnelParameters.prototype.clone = function () {
  76070. var newFresnelParameters = new FresnelParameters();
  76071. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  76072. return newFresnelParameters;
  76073. };
  76074. FresnelParameters.prototype.serialize = function () {
  76075. var serializationObject = {};
  76076. serializationObject.isEnabled = this.isEnabled;
  76077. serializationObject.leftColor = this.leftColor.asArray();
  76078. serializationObject.rightColor = this.rightColor.asArray();
  76079. serializationObject.bias = this.bias;
  76080. serializationObject.power = this.power;
  76081. return serializationObject;
  76082. };
  76083. FresnelParameters.Parse = function (parsedFresnelParameters) {
  76084. var fresnelParameters = new FresnelParameters();
  76085. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  76086. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  76087. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  76088. fresnelParameters.bias = parsedFresnelParameters.bias;
  76089. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  76090. return fresnelParameters;
  76091. };
  76092. return FresnelParameters;
  76093. }());
  76094. BABYLON.FresnelParameters = FresnelParameters;
  76095. })(BABYLON || (BABYLON = {}));
  76096. //# sourceMappingURL=babylon.fresnelParameters.js.map
  76097. var BABYLON;
  76098. (function (BABYLON) {
  76099. var MultiMaterial = /** @class */ (function (_super) {
  76100. __extends(MultiMaterial, _super);
  76101. function MultiMaterial(name, scene) {
  76102. var _this = _super.call(this, name, scene, true) || this;
  76103. scene.multiMaterials.push(_this);
  76104. _this.subMaterials = new Array();
  76105. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  76106. return _this;
  76107. }
  76108. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  76109. get: function () {
  76110. return this._subMaterials;
  76111. },
  76112. set: function (value) {
  76113. this._subMaterials = value;
  76114. this._hookArray(value);
  76115. },
  76116. enumerable: true,
  76117. configurable: true
  76118. });
  76119. MultiMaterial.prototype._hookArray = function (array) {
  76120. var _this = this;
  76121. var oldPush = array.push;
  76122. array.push = function () {
  76123. var items = [];
  76124. for (var _i = 0; _i < arguments.length; _i++) {
  76125. items[_i] = arguments[_i];
  76126. }
  76127. var result = oldPush.apply(array, items);
  76128. _this._markAllSubMeshesAsTexturesDirty();
  76129. return result;
  76130. };
  76131. var oldSplice = array.splice;
  76132. array.splice = function (index, deleteCount) {
  76133. var deleted = oldSplice.apply(array, [index, deleteCount]);
  76134. _this._markAllSubMeshesAsTexturesDirty();
  76135. return deleted;
  76136. };
  76137. };
  76138. // Properties
  76139. MultiMaterial.prototype.getSubMaterial = function (index) {
  76140. if (index < 0 || index >= this.subMaterials.length) {
  76141. return this.getScene().defaultMaterial;
  76142. }
  76143. return this.subMaterials[index];
  76144. };
  76145. MultiMaterial.prototype.getActiveTextures = function () {
  76146. var _a;
  76147. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  76148. if (subMaterial) {
  76149. return subMaterial.getActiveTextures();
  76150. }
  76151. else {
  76152. return [];
  76153. }
  76154. }));
  76155. };
  76156. // Methods
  76157. MultiMaterial.prototype.getClassName = function () {
  76158. return "MultiMaterial";
  76159. };
  76160. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76161. for (var index = 0; index < this.subMaterials.length; index++) {
  76162. var subMaterial = this.subMaterials[index];
  76163. if (subMaterial) {
  76164. if (subMaterial.storeEffectOnSubMeshes) {
  76165. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  76166. return false;
  76167. }
  76168. continue;
  76169. }
  76170. if (!subMaterial.isReady(mesh)) {
  76171. return false;
  76172. }
  76173. }
  76174. }
  76175. return true;
  76176. };
  76177. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  76178. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  76179. for (var index = 0; index < this.subMaterials.length; index++) {
  76180. var subMaterial = null;
  76181. var current = this.subMaterials[index];
  76182. if (cloneChildren && current) {
  76183. subMaterial = current.clone(name + "-" + current.name);
  76184. }
  76185. else {
  76186. subMaterial = this.subMaterials[index];
  76187. }
  76188. newMultiMaterial.subMaterials.push(subMaterial);
  76189. }
  76190. return newMultiMaterial;
  76191. };
  76192. MultiMaterial.prototype.serialize = function () {
  76193. var serializationObject = {};
  76194. serializationObject.name = this.name;
  76195. serializationObject.id = this.id;
  76196. if (BABYLON.Tags) {
  76197. serializationObject.tags = BABYLON.Tags.GetTags(this);
  76198. }
  76199. serializationObject.materials = [];
  76200. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  76201. var subMat = this.subMaterials[matIndex];
  76202. if (subMat) {
  76203. serializationObject.materials.push(subMat.id);
  76204. }
  76205. else {
  76206. serializationObject.materials.push(null);
  76207. }
  76208. }
  76209. return serializationObject;
  76210. };
  76211. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76212. var scene = this.getScene();
  76213. if (!scene) {
  76214. return;
  76215. }
  76216. var index = scene.multiMaterials.indexOf(this);
  76217. if (index >= 0) {
  76218. scene.multiMaterials.splice(index, 1);
  76219. }
  76220. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  76221. };
  76222. return MultiMaterial;
  76223. }(BABYLON.Material));
  76224. BABYLON.MultiMaterial = MultiMaterial;
  76225. })(BABYLON || (BABYLON = {}));
  76226. //# sourceMappingURL=babylon.multiMaterial.js.map
  76227. var BABYLON;
  76228. (function (BABYLON) {
  76229. /**
  76230. * Manage the touch inputs to control the movement of a free camera.
  76231. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76232. */
  76233. var FreeCameraTouchInput = /** @class */ (function () {
  76234. function FreeCameraTouchInput() {
  76235. /**
  76236. * Defines the touch sensibility for rotation.
  76237. * The higher the faster.
  76238. */
  76239. this.touchAngularSensibility = 200000.0;
  76240. /**
  76241. * Defines the touch sensibility for move.
  76242. * The higher the faster.
  76243. */
  76244. this.touchMoveSensibility = 250.0;
  76245. this._offsetX = null;
  76246. this._offsetY = null;
  76247. this._pointerPressed = new Array();
  76248. }
  76249. /**
  76250. * Attach the input controls to a specific dom element to get the input from.
  76251. * @param element Defines the element the controls should be listened from
  76252. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76253. */
  76254. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  76255. var _this = this;
  76256. var previousPosition = null;
  76257. if (this._pointerInput === undefined) {
  76258. this._onLostFocus = function (evt) {
  76259. _this._offsetX = null;
  76260. _this._offsetY = null;
  76261. };
  76262. this._pointerInput = function (p, s) {
  76263. var evt = p.event;
  76264. if (evt.pointerType === "mouse") {
  76265. return;
  76266. }
  76267. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76268. if (!noPreventDefault) {
  76269. evt.preventDefault();
  76270. }
  76271. _this._pointerPressed.push(evt.pointerId);
  76272. if (_this._pointerPressed.length !== 1) {
  76273. return;
  76274. }
  76275. previousPosition = {
  76276. x: evt.clientX,
  76277. y: evt.clientY
  76278. };
  76279. }
  76280. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  76281. if (!noPreventDefault) {
  76282. evt.preventDefault();
  76283. }
  76284. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76285. if (index === -1) {
  76286. return;
  76287. }
  76288. _this._pointerPressed.splice(index, 1);
  76289. if (index != 0) {
  76290. return;
  76291. }
  76292. previousPosition = null;
  76293. _this._offsetX = null;
  76294. _this._offsetY = null;
  76295. }
  76296. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  76297. if (!noPreventDefault) {
  76298. evt.preventDefault();
  76299. }
  76300. if (!previousPosition) {
  76301. return;
  76302. }
  76303. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76304. if (index != 0) {
  76305. return;
  76306. }
  76307. _this._offsetX = evt.clientX - previousPosition.x;
  76308. _this._offsetY = -(evt.clientY - previousPosition.y);
  76309. }
  76310. };
  76311. }
  76312. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  76313. if (this._onLostFocus) {
  76314. element.addEventListener("blur", this._onLostFocus);
  76315. }
  76316. };
  76317. /**
  76318. * Detach the current controls from the specified dom element.
  76319. * @param element Defines the element to stop listening the inputs from
  76320. */
  76321. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76322. if (this._pointerInput && element) {
  76323. if (this._observer) {
  76324. this.camera.getScene().onPointerObservable.remove(this._observer);
  76325. this._observer = null;
  76326. }
  76327. if (this._onLostFocus) {
  76328. element.removeEventListener("blur", this._onLostFocus);
  76329. this._onLostFocus = null;
  76330. }
  76331. this._pointerPressed = [];
  76332. this._offsetX = null;
  76333. this._offsetY = null;
  76334. }
  76335. };
  76336. /**
  76337. * Update the current camera state depending on the inputs that have been used this frame.
  76338. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76339. */
  76340. FreeCameraTouchInput.prototype.checkInputs = function () {
  76341. if (this._offsetX && this._offsetY) {
  76342. var camera = this.camera;
  76343. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76344. if (this._pointerPressed.length > 1) {
  76345. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76346. }
  76347. else {
  76348. var speed = camera._computeLocalCameraSpeed();
  76349. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76350. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76351. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76352. }
  76353. }
  76354. };
  76355. /**
  76356. * Gets the class name of the current intput.
  76357. * @returns the class name
  76358. */
  76359. FreeCameraTouchInput.prototype.getClassName = function () {
  76360. return "FreeCameraTouchInput";
  76361. };
  76362. /**
  76363. * Get the friendly name associated with the input class.
  76364. * @returns the input friendly name
  76365. */
  76366. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76367. return "touch";
  76368. };
  76369. __decorate([
  76370. BABYLON.serialize()
  76371. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76372. __decorate([
  76373. BABYLON.serialize()
  76374. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76375. return FreeCameraTouchInput;
  76376. }());
  76377. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76378. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76379. })(BABYLON || (BABYLON = {}));
  76380. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76381. var BABYLON;
  76382. (function (BABYLON) {
  76383. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76384. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76385. });
  76386. /**
  76387. * This represents a FPS type of camera controlled by touch.
  76388. * This is like a universal camera minus the Gamepad controls.
  76389. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76390. */
  76391. var TouchCamera = /** @class */ (function (_super) {
  76392. __extends(TouchCamera, _super);
  76393. /**
  76394. * Instantiates a new touch camera.
  76395. * This represents a FPS type of camera controlled by touch.
  76396. * This is like a universal camera minus the Gamepad controls.
  76397. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76398. * @param name Define the name of the camera in the scene
  76399. * @param position Define the start position of the camera in the scene
  76400. * @param scene Define the scene the camera belongs to
  76401. */
  76402. function TouchCamera(name, position, scene) {
  76403. var _this = _super.call(this, name, position, scene) || this;
  76404. _this.inputs.addTouch();
  76405. _this._setupInputs();
  76406. return _this;
  76407. }
  76408. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76409. /**
  76410. * Defines the touch sensibility for rotation.
  76411. * The higher the faster.
  76412. */
  76413. get: function () {
  76414. var touch = this.inputs.attached["touch"];
  76415. if (touch)
  76416. return touch.touchAngularSensibility;
  76417. return 0;
  76418. },
  76419. set: function (value) {
  76420. var touch = this.inputs.attached["touch"];
  76421. if (touch)
  76422. touch.touchAngularSensibility = value;
  76423. },
  76424. enumerable: true,
  76425. configurable: true
  76426. });
  76427. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76428. /**
  76429. * Defines the touch sensibility for move.
  76430. * The higher the faster.
  76431. */
  76432. get: function () {
  76433. var touch = this.inputs.attached["touch"];
  76434. if (touch)
  76435. return touch.touchMoveSensibility;
  76436. return 0;
  76437. },
  76438. set: function (value) {
  76439. var touch = this.inputs.attached["touch"];
  76440. if (touch)
  76441. touch.touchMoveSensibility = value;
  76442. },
  76443. enumerable: true,
  76444. configurable: true
  76445. });
  76446. /**
  76447. * Gets the current object class name.
  76448. * @return the class name
  76449. */
  76450. TouchCamera.prototype.getClassName = function () {
  76451. return "TouchCamera";
  76452. };
  76453. /** @hidden */
  76454. TouchCamera.prototype._setupInputs = function () {
  76455. var mouse = this.inputs.attached["mouse"];
  76456. if (mouse) {
  76457. mouse.touchEnabled = false;
  76458. }
  76459. };
  76460. return TouchCamera;
  76461. }(BABYLON.FreeCamera));
  76462. BABYLON.TouchCamera = TouchCamera;
  76463. })(BABYLON || (BABYLON = {}));
  76464. //# sourceMappingURL=babylon.touchCamera.js.map
  76465. var BABYLON;
  76466. (function (BABYLON) {
  76467. var ProceduralTexture = /** @class */ (function (_super) {
  76468. __extends(ProceduralTexture, _super);
  76469. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76470. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76471. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76472. if (isCube === void 0) { isCube = false; }
  76473. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76474. _this.isCube = isCube;
  76475. _this.isEnabled = true;
  76476. _this._currentRefreshId = -1;
  76477. _this._refreshRate = 1;
  76478. /**
  76479. * Event raised when the texture is generated
  76480. */
  76481. _this.onGeneratedObservable = new BABYLON.Observable();
  76482. _this._vertexBuffers = {};
  76483. _this._uniforms = new Array();
  76484. _this._samplers = new Array();
  76485. /** @hidden */
  76486. _this._textures = {};
  76487. _this._floats = {};
  76488. _this._ints = {};
  76489. _this._floatsArrays = {};
  76490. _this._colors3 = {};
  76491. _this._colors4 = {};
  76492. _this._vectors2 = {};
  76493. _this._vectors3 = {};
  76494. _this._matrices = {};
  76495. _this._fallbackTextureUsed = false;
  76496. _this._cachedDefines = "";
  76497. _this._contentUpdateId = -1;
  76498. scene = _this.getScene();
  76499. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76500. if (!component) {
  76501. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76502. scene._addComponent(component);
  76503. }
  76504. scene.proceduralTextures.push(_this);
  76505. _this._engine = scene.getEngine();
  76506. _this.name = name;
  76507. _this.isRenderTarget = true;
  76508. _this._size = size;
  76509. _this._generateMipMaps = generateMipMaps;
  76510. _this.setFragment(fragment);
  76511. _this._fallbackTexture = fallbackTexture;
  76512. if (isCube) {
  76513. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76514. _this.setFloat("face", 0);
  76515. }
  76516. else {
  76517. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76518. }
  76519. // VBO
  76520. var vertices = [];
  76521. vertices.push(1, 1);
  76522. vertices.push(-1, 1);
  76523. vertices.push(-1, -1);
  76524. vertices.push(1, -1);
  76525. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76526. _this._createIndexBuffer();
  76527. return _this;
  76528. }
  76529. /**
  76530. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76531. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76532. */
  76533. ProceduralTexture.prototype.getContent = function () {
  76534. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76535. return this._contentData;
  76536. }
  76537. this._contentData = this.readPixels(0, 0, this._contentData);
  76538. this._contentUpdateId = this._currentRefreshId;
  76539. return this._contentData;
  76540. };
  76541. ProceduralTexture.prototype._createIndexBuffer = function () {
  76542. var engine = this._engine;
  76543. // Indices
  76544. var indices = [];
  76545. indices.push(0);
  76546. indices.push(1);
  76547. indices.push(2);
  76548. indices.push(0);
  76549. indices.push(2);
  76550. indices.push(3);
  76551. this._indexBuffer = engine.createIndexBuffer(indices);
  76552. };
  76553. /** @hidden */
  76554. ProceduralTexture.prototype._rebuild = function () {
  76555. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76556. if (vb) {
  76557. vb._rebuild();
  76558. }
  76559. this._createIndexBuffer();
  76560. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76561. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76562. }
  76563. };
  76564. ProceduralTexture.prototype.reset = function () {
  76565. if (this._effect === undefined) {
  76566. return;
  76567. }
  76568. var engine = this._engine;
  76569. engine._releaseEffect(this._effect);
  76570. };
  76571. ProceduralTexture.prototype._getDefines = function () {
  76572. return "";
  76573. };
  76574. ProceduralTexture.prototype.isReady = function () {
  76575. var _this = this;
  76576. var engine = this._engine;
  76577. var shaders;
  76578. if (!this._fragment) {
  76579. return false;
  76580. }
  76581. if (this._fallbackTextureUsed) {
  76582. return true;
  76583. }
  76584. var defines = this._getDefines();
  76585. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76586. return true;
  76587. }
  76588. if (this._fragment.fragmentElement !== undefined) {
  76589. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76590. }
  76591. else {
  76592. shaders = { vertex: "procedural", fragment: this._fragment };
  76593. }
  76594. this._cachedDefines = defines;
  76595. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76596. _this.releaseInternalTexture();
  76597. if (_this._fallbackTexture) {
  76598. _this._texture = _this._fallbackTexture._texture;
  76599. if (_this._texture) {
  76600. _this._texture.incrementReferences();
  76601. }
  76602. }
  76603. _this._fallbackTextureUsed = true;
  76604. });
  76605. return this._effect.isReady();
  76606. };
  76607. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76608. this._currentRefreshId = -1;
  76609. };
  76610. ProceduralTexture.prototype.setFragment = function (fragment) {
  76611. this._fragment = fragment;
  76612. };
  76613. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76614. get: function () {
  76615. return this._refreshRate;
  76616. },
  76617. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76618. set: function (value) {
  76619. this._refreshRate = value;
  76620. this.resetRefreshCounter();
  76621. },
  76622. enumerable: true,
  76623. configurable: true
  76624. });
  76625. /** @hidden */
  76626. ProceduralTexture.prototype._shouldRender = function () {
  76627. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76628. if (this._texture) {
  76629. this._texture.isReady = false;
  76630. }
  76631. return false;
  76632. }
  76633. if (this._fallbackTextureUsed) {
  76634. return false;
  76635. }
  76636. if (this._currentRefreshId === -1) { // At least render once
  76637. this._currentRefreshId = 1;
  76638. return true;
  76639. }
  76640. if (this.refreshRate === this._currentRefreshId) {
  76641. this._currentRefreshId = 1;
  76642. return true;
  76643. }
  76644. this._currentRefreshId++;
  76645. return false;
  76646. };
  76647. ProceduralTexture.prototype.getRenderSize = function () {
  76648. return this._size;
  76649. };
  76650. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76651. if (this._fallbackTextureUsed) {
  76652. return;
  76653. }
  76654. this.releaseInternalTexture();
  76655. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76656. // Update properties
  76657. this._size = size;
  76658. this._generateMipMaps = generateMipMaps;
  76659. };
  76660. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76661. if (this._uniforms.indexOf(uniformName) === -1) {
  76662. this._uniforms.push(uniformName);
  76663. }
  76664. };
  76665. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76666. if (this._samplers.indexOf(name) === -1) {
  76667. this._samplers.push(name);
  76668. }
  76669. this._textures[name] = texture;
  76670. return this;
  76671. };
  76672. ProceduralTexture.prototype.setFloat = function (name, value) {
  76673. this._checkUniform(name);
  76674. this._floats[name] = value;
  76675. return this;
  76676. };
  76677. /**
  76678. * Set the value of an uniform to an integer value
  76679. * @param name defines the name of the uniform
  76680. * @param value defines the value to set
  76681. * @returns the current procedural texture
  76682. */
  76683. ProceduralTexture.prototype.setInt = function (name, value) {
  76684. this._checkUniform(name);
  76685. this._ints[name] = value;
  76686. return this;
  76687. };
  76688. ProceduralTexture.prototype.setFloats = function (name, value) {
  76689. this._checkUniform(name);
  76690. this._floatsArrays[name] = value;
  76691. return this;
  76692. };
  76693. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76694. this._checkUniform(name);
  76695. this._colors3[name] = value;
  76696. return this;
  76697. };
  76698. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76699. this._checkUniform(name);
  76700. this._colors4[name] = value;
  76701. return this;
  76702. };
  76703. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76704. this._checkUniform(name);
  76705. this._vectors2[name] = value;
  76706. return this;
  76707. };
  76708. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76709. this._checkUniform(name);
  76710. this._vectors3[name] = value;
  76711. return this;
  76712. };
  76713. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76714. this._checkUniform(name);
  76715. this._matrices[name] = value;
  76716. return this;
  76717. };
  76718. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76719. var scene = this.getScene();
  76720. if (!scene) {
  76721. return;
  76722. }
  76723. var engine = this._engine;
  76724. // Render
  76725. engine.enableEffect(this._effect);
  76726. engine.setState(false);
  76727. // Texture
  76728. for (var name in this._textures) {
  76729. this._effect.setTexture(name, this._textures[name]);
  76730. }
  76731. // Float
  76732. for (name in this._ints) {
  76733. this._effect.setInt(name, this._ints[name]);
  76734. }
  76735. // Float
  76736. for (name in this._floats) {
  76737. this._effect.setFloat(name, this._floats[name]);
  76738. }
  76739. // Floats
  76740. for (name in this._floatsArrays) {
  76741. this._effect.setArray(name, this._floatsArrays[name]);
  76742. }
  76743. // Color3
  76744. for (name in this._colors3) {
  76745. this._effect.setColor3(name, this._colors3[name]);
  76746. }
  76747. // Color4
  76748. for (name in this._colors4) {
  76749. var color = this._colors4[name];
  76750. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76751. }
  76752. // Vector2
  76753. for (name in this._vectors2) {
  76754. this._effect.setVector2(name, this._vectors2[name]);
  76755. }
  76756. // Vector3
  76757. for (name in this._vectors3) {
  76758. this._effect.setVector3(name, this._vectors3[name]);
  76759. }
  76760. // Matrix
  76761. for (name in this._matrices) {
  76762. this._effect.setMatrix(name, this._matrices[name]);
  76763. }
  76764. if (!this._texture) {
  76765. return;
  76766. }
  76767. if (this.isCube) {
  76768. for (var face = 0; face < 6; face++) {
  76769. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76770. // VBOs
  76771. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76772. this._effect.setFloat("face", face);
  76773. // Clear
  76774. engine.clear(scene.clearColor, true, true, true);
  76775. // Draw order
  76776. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76777. // Mipmaps
  76778. if (face === 5) {
  76779. engine.generateMipMapsForCubemap(this._texture);
  76780. }
  76781. }
  76782. }
  76783. else {
  76784. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76785. // VBOs
  76786. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76787. // Clear
  76788. engine.clear(scene.clearColor, true, true, true);
  76789. // Draw order
  76790. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76791. }
  76792. // Unbind
  76793. engine.unBindFramebuffer(this._texture, this.isCube);
  76794. if (this.onGenerated) {
  76795. this.onGenerated();
  76796. }
  76797. this.onGeneratedObservable.notifyObservers(this);
  76798. };
  76799. ProceduralTexture.prototype.clone = function () {
  76800. var textureSize = this.getSize();
  76801. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76802. // Base texture
  76803. newTexture.hasAlpha = this.hasAlpha;
  76804. newTexture.level = this.level;
  76805. // RenderTarget Texture
  76806. newTexture.coordinatesMode = this.coordinatesMode;
  76807. return newTexture;
  76808. };
  76809. ProceduralTexture.prototype.dispose = function () {
  76810. var scene = this.getScene();
  76811. if (!scene) {
  76812. return;
  76813. }
  76814. var index = scene.proceduralTextures.indexOf(this);
  76815. if (index >= 0) {
  76816. scene.proceduralTextures.splice(index, 1);
  76817. }
  76818. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76819. if (vertexBuffer) {
  76820. vertexBuffer.dispose();
  76821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76822. }
  76823. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76824. this._indexBuffer = null;
  76825. }
  76826. _super.prototype.dispose.call(this);
  76827. };
  76828. __decorate([
  76829. BABYLON.serialize()
  76830. ], ProceduralTexture.prototype, "_size", void 0);
  76831. __decorate([
  76832. BABYLON.serialize()
  76833. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76834. __decorate([
  76835. BABYLON.serialize()
  76836. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76837. __decorate([
  76838. BABYLON.serialize()
  76839. ], ProceduralTexture.prototype, "refreshRate", null);
  76840. return ProceduralTexture;
  76841. }(BABYLON.Texture));
  76842. BABYLON.ProceduralTexture = ProceduralTexture;
  76843. })(BABYLON || (BABYLON = {}));
  76844. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76845. var BABYLON;
  76846. (function (BABYLON) {
  76847. /**
  76848. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76849. * in a given scene.
  76850. */
  76851. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76852. /**
  76853. * Creates a new instance of the component for the given scene
  76854. * @param scene Defines the scene to register the component in
  76855. */
  76856. function ProceduralTextureSceneComponent(scene) {
  76857. /**
  76858. * The component name helpfull to identify the component in the list of scene components.
  76859. */
  76860. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76861. this.scene = scene;
  76862. this.scene.proceduralTextures = new Array();
  76863. scene.layers = new Array();
  76864. }
  76865. /**
  76866. * Registers the component in a given scene
  76867. */
  76868. ProceduralTextureSceneComponent.prototype.register = function () {
  76869. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76870. };
  76871. /**
  76872. * Rebuilds the elements related to this component in case of
  76873. * context lost for instance.
  76874. */
  76875. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76876. // Nothing to do here.
  76877. };
  76878. /**
  76879. * Disposes the component and the associated ressources.
  76880. */
  76881. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76882. // Nothing to do here.
  76883. };
  76884. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76885. if (this.scene.proceduralTexturesEnabled) {
  76886. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76887. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76888. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76889. if (proceduralTexture._shouldRender()) {
  76890. proceduralTexture.render();
  76891. }
  76892. }
  76893. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76894. }
  76895. };
  76896. return ProceduralTextureSceneComponent;
  76897. }());
  76898. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76899. })(BABYLON || (BABYLON = {}));
  76900. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76901. var BABYLON;
  76902. (function (BABYLON) {
  76903. var CustomProceduralTexture = /** @class */ (function (_super) {
  76904. __extends(CustomProceduralTexture, _super);
  76905. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76906. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76907. _this._animate = true;
  76908. _this._time = 0;
  76909. _this._texturePath = texturePath;
  76910. //Try to load json
  76911. _this.loadJson(texturePath);
  76912. _this.refreshRate = 1;
  76913. return _this;
  76914. }
  76915. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76916. var _this = this;
  76917. var noConfigFile = function () {
  76918. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76919. try {
  76920. _this.setFragment(_this._texturePath);
  76921. }
  76922. catch (ex) {
  76923. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76924. }
  76925. };
  76926. var configFileUrl = jsonUrl + "/config.json";
  76927. var xhr = new XMLHttpRequest();
  76928. xhr.open("GET", configFileUrl, true);
  76929. xhr.addEventListener("load", function () {
  76930. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76931. try {
  76932. _this._config = JSON.parse(xhr.response);
  76933. _this.updateShaderUniforms();
  76934. _this.updateTextures();
  76935. _this.setFragment(_this._texturePath + "/custom");
  76936. _this._animate = _this._config.animate;
  76937. _this.refreshRate = _this._config.refreshrate;
  76938. }
  76939. catch (ex) {
  76940. noConfigFile();
  76941. }
  76942. }
  76943. else {
  76944. noConfigFile();
  76945. }
  76946. }, false);
  76947. xhr.addEventListener("error", function () {
  76948. noConfigFile();
  76949. }, false);
  76950. try {
  76951. xhr.send();
  76952. }
  76953. catch (ex) {
  76954. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76955. }
  76956. };
  76957. CustomProceduralTexture.prototype.isReady = function () {
  76958. if (!_super.prototype.isReady.call(this)) {
  76959. return false;
  76960. }
  76961. for (var name in this._textures) {
  76962. var texture = this._textures[name];
  76963. if (!texture.isReady()) {
  76964. return false;
  76965. }
  76966. }
  76967. return true;
  76968. };
  76969. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76970. var scene = this.getScene();
  76971. if (this._animate && scene) {
  76972. this._time += scene.getAnimationRatio() * 0.03;
  76973. this.updateShaderUniforms();
  76974. }
  76975. _super.prototype.render.call(this, useCameraPostProcess);
  76976. };
  76977. CustomProceduralTexture.prototype.updateTextures = function () {
  76978. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76979. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76980. }
  76981. };
  76982. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76983. if (this._config) {
  76984. for (var j = 0; j < this._config.uniforms.length; j++) {
  76985. var uniform = this._config.uniforms[j];
  76986. switch (uniform.type) {
  76987. case "float":
  76988. this.setFloat(uniform.name, uniform.value);
  76989. break;
  76990. case "color3":
  76991. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76992. break;
  76993. case "color4":
  76994. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76995. break;
  76996. case "vector2":
  76997. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76998. break;
  76999. case "vector3":
  77000. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  77001. break;
  77002. }
  77003. }
  77004. }
  77005. this.setFloat("time", this._time);
  77006. };
  77007. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  77008. get: function () {
  77009. return this._animate;
  77010. },
  77011. set: function (value) {
  77012. this._animate = value;
  77013. },
  77014. enumerable: true,
  77015. configurable: true
  77016. });
  77017. return CustomProceduralTexture;
  77018. }(BABYLON.ProceduralTexture));
  77019. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  77020. })(BABYLON || (BABYLON = {}));
  77021. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  77022. var BABYLON;
  77023. (function (BABYLON) {
  77024. /**
  77025. * Manage the gamepad inputs to control a free camera.
  77026. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77027. */
  77028. var FreeCameraGamepadInput = /** @class */ (function () {
  77029. function FreeCameraGamepadInput() {
  77030. /**
  77031. * Defines the gamepad rotation sensiblity.
  77032. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77033. */
  77034. this.gamepadAngularSensibility = 200;
  77035. /**
  77036. * Defines the gamepad move sensiblity.
  77037. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77038. */
  77039. this.gamepadMoveSensibility = 40;
  77040. this._cameraTransform = BABYLON.Matrix.Identity();
  77041. this._deltaTransform = BABYLON.Vector3.Zero();
  77042. this._vector3 = BABYLON.Vector3.Zero();
  77043. this._vector2 = BABYLON.Vector2.Zero();
  77044. }
  77045. /**
  77046. * Attach the input controls to a specific dom element to get the input from.
  77047. * @param element Defines the element the controls should be listened from
  77048. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77049. */
  77050. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77051. var _this = this;
  77052. var manager = this.camera.getScene().gamepadManager;
  77053. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77054. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77055. // prioritize XBOX gamepads.
  77056. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77057. _this.gamepad = gamepad;
  77058. }
  77059. }
  77060. });
  77061. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77062. if (_this.gamepad === gamepad) {
  77063. _this.gamepad = null;
  77064. }
  77065. });
  77066. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77067. };
  77068. /**
  77069. * Detach the current controls from the specified dom element.
  77070. * @param element Defines the element to stop listening the inputs from
  77071. */
  77072. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  77073. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77074. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77075. this.gamepad = null;
  77076. };
  77077. /**
  77078. * Update the current camera state depending on the inputs that have been used this frame.
  77079. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77080. */
  77081. FreeCameraGamepadInput.prototype.checkInputs = function () {
  77082. if (this.gamepad && this.gamepad.leftStick) {
  77083. var camera = this.camera;
  77084. var LSValues = this.gamepad.leftStick;
  77085. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  77086. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77087. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  77088. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  77089. var RSValues = this.gamepad.rightStick;
  77090. if (RSValues) {
  77091. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  77092. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  77093. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  77094. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  77095. }
  77096. else {
  77097. RSValues = { x: 0, y: 0 };
  77098. }
  77099. if (!camera.rotationQuaternion) {
  77100. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  77101. }
  77102. else {
  77103. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  77104. }
  77105. var speed = camera._computeLocalCameraSpeed() * 50.0;
  77106. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  77107. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  77108. camera.cameraDirection.addInPlace(this._deltaTransform);
  77109. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  77110. camera.cameraRotation.addInPlace(this._vector2);
  77111. }
  77112. };
  77113. /**
  77114. * Gets the class name of the current intput.
  77115. * @returns the class name
  77116. */
  77117. FreeCameraGamepadInput.prototype.getClassName = function () {
  77118. return "FreeCameraGamepadInput";
  77119. };
  77120. /**
  77121. * Get the friendly name associated with the input class.
  77122. * @returns the input friendly name
  77123. */
  77124. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  77125. return "gamepad";
  77126. };
  77127. __decorate([
  77128. BABYLON.serialize()
  77129. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  77130. __decorate([
  77131. BABYLON.serialize()
  77132. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77133. return FreeCameraGamepadInput;
  77134. }());
  77135. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  77136. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  77137. })(BABYLON || (BABYLON = {}));
  77138. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  77139. var BABYLON;
  77140. (function (BABYLON) {
  77141. /**
  77142. * Manage the gamepad inputs to control an arc rotate camera.
  77143. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77144. */
  77145. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  77146. function ArcRotateCameraGamepadInput() {
  77147. /**
  77148. * Defines the gamepad rotation sensiblity.
  77149. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77150. */
  77151. this.gamepadRotationSensibility = 80;
  77152. /**
  77153. * Defines the gamepad move sensiblity.
  77154. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77155. */
  77156. this.gamepadMoveSensibility = 40;
  77157. }
  77158. /**
  77159. * Attach the input controls to a specific dom element to get the input from.
  77160. * @param element Defines the element the controls should be listened from
  77161. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77162. */
  77163. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77164. var _this = this;
  77165. var manager = this.camera.getScene().gamepadManager;
  77166. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77167. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77168. // prioritize XBOX gamepads.
  77169. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77170. _this.gamepad = gamepad;
  77171. }
  77172. }
  77173. });
  77174. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77175. if (_this.gamepad === gamepad) {
  77176. _this.gamepad = null;
  77177. }
  77178. });
  77179. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77180. };
  77181. /**
  77182. * Detach the current controls from the specified dom element.
  77183. * @param element Defines the element to stop listening the inputs from
  77184. */
  77185. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  77186. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77187. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77188. this.gamepad = null;
  77189. };
  77190. /**
  77191. * Update the current camera state depending on the inputs that have been used this frame.
  77192. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77193. */
  77194. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  77195. if (this.gamepad) {
  77196. var camera = this.camera;
  77197. var RSValues = this.gamepad.rightStick;
  77198. if (RSValues) {
  77199. if (RSValues.x != 0) {
  77200. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  77201. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  77202. camera.inertialAlphaOffset += normalizedRX;
  77203. }
  77204. }
  77205. if (RSValues.y != 0) {
  77206. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  77207. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  77208. camera.inertialBetaOffset += normalizedRY;
  77209. }
  77210. }
  77211. }
  77212. var LSValues = this.gamepad.leftStick;
  77213. if (LSValues && LSValues.y != 0) {
  77214. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77215. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  77216. this.camera.inertialRadiusOffset -= normalizedLY;
  77217. }
  77218. }
  77219. }
  77220. };
  77221. /**
  77222. * Gets the class name of the current intput.
  77223. * @returns the class name
  77224. */
  77225. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  77226. return "ArcRotateCameraGamepadInput";
  77227. };
  77228. /**
  77229. * Get the friendly name associated with the input class.
  77230. * @returns the input friendly name
  77231. */
  77232. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  77233. return "gamepad";
  77234. };
  77235. __decorate([
  77236. BABYLON.serialize()
  77237. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  77238. __decorate([
  77239. BABYLON.serialize()
  77240. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77241. return ArcRotateCameraGamepadInput;
  77242. }());
  77243. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  77244. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  77245. })(BABYLON || (BABYLON = {}));
  77246. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  77247. var BABYLON;
  77248. (function (BABYLON) {
  77249. /**
  77250. * Manager for handling gamepads
  77251. */
  77252. var GamepadManager = /** @class */ (function () {
  77253. /**
  77254. * Initializes the gamepad manager
  77255. * @param _scene BabylonJS scene
  77256. */
  77257. function GamepadManager(_scene) {
  77258. var _this = this;
  77259. this._scene = _scene;
  77260. this._babylonGamepads = [];
  77261. this._oneGamepadConnected = false;
  77262. /** @hidden */
  77263. this._isMonitoring = false;
  77264. /**
  77265. * observable to be triggered when the gamepad controller has been disconnected
  77266. */
  77267. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  77268. if (!BABYLON.Tools.IsWindowObjectExist()) {
  77269. this._gamepadEventSupported = false;
  77270. }
  77271. else {
  77272. this._gamepadEventSupported = 'GamepadEvent' in window;
  77273. this._gamepadSupport = (navigator.getGamepads ||
  77274. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  77275. }
  77276. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  77277. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  77278. for (var i in _this._babylonGamepads) {
  77279. var gamepad = _this._babylonGamepads[i];
  77280. if (gamepad && gamepad._isConnected) {
  77281. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  77282. }
  77283. }
  77284. });
  77285. this._onGamepadConnectedEvent = function (evt) {
  77286. var gamepad = evt.gamepad;
  77287. if (gamepad.index in _this._babylonGamepads) {
  77288. if (_this._babylonGamepads[gamepad.index].isConnected) {
  77289. return;
  77290. }
  77291. }
  77292. var newGamepad;
  77293. if (_this._babylonGamepads[gamepad.index]) {
  77294. newGamepad = _this._babylonGamepads[gamepad.index];
  77295. newGamepad.browserGamepad = gamepad;
  77296. newGamepad._isConnected = true;
  77297. }
  77298. else {
  77299. newGamepad = _this._addNewGamepad(gamepad);
  77300. }
  77301. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77302. _this._startMonitoringGamepads();
  77303. };
  77304. this._onGamepadDisconnectedEvent = function (evt) {
  77305. var gamepad = evt.gamepad;
  77306. // Remove the gamepad from the list of gamepads to monitor.
  77307. for (var i in _this._babylonGamepads) {
  77308. if (_this._babylonGamepads[i].index === gamepad.index) {
  77309. var disconnectedGamepad = _this._babylonGamepads[i];
  77310. disconnectedGamepad._isConnected = false;
  77311. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  77312. break;
  77313. }
  77314. }
  77315. };
  77316. if (this._gamepadSupport) {
  77317. //first add already-connected gamepads
  77318. this._updateGamepadObjects();
  77319. if (this._babylonGamepads.length) {
  77320. this._startMonitoringGamepads();
  77321. }
  77322. // Checking if the gamepad connected event is supported (like in Firefox)
  77323. if (this._gamepadEventSupported) {
  77324. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77325. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77326. }
  77327. else {
  77328. this._startMonitoringGamepads();
  77329. }
  77330. }
  77331. }
  77332. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77333. /**
  77334. * The gamepads in the game pad manager
  77335. */
  77336. get: function () {
  77337. return this._babylonGamepads;
  77338. },
  77339. enumerable: true,
  77340. configurable: true
  77341. });
  77342. /**
  77343. * Get the gamepad controllers based on type
  77344. * @param type The type of gamepad controller
  77345. * @returns Nullable gamepad
  77346. */
  77347. GamepadManager.prototype.getGamepadByType = function (type) {
  77348. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77349. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77350. var gamepad = _a[_i];
  77351. if (gamepad && gamepad.type === type) {
  77352. return gamepad;
  77353. }
  77354. }
  77355. return null;
  77356. };
  77357. /**
  77358. * Disposes the gamepad manager
  77359. */
  77360. GamepadManager.prototype.dispose = function () {
  77361. if (this._gamepadEventSupported) {
  77362. if (this._onGamepadConnectedEvent) {
  77363. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77364. }
  77365. if (this._onGamepadDisconnectedEvent) {
  77366. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77367. }
  77368. this._onGamepadConnectedEvent = null;
  77369. this._onGamepadDisconnectedEvent = null;
  77370. }
  77371. this._babylonGamepads.forEach(function (gamepad) {
  77372. gamepad.dispose();
  77373. });
  77374. this.onGamepadConnectedObservable.clear();
  77375. this.onGamepadDisconnectedObservable.clear();
  77376. this._oneGamepadConnected = false;
  77377. this._stopMonitoringGamepads();
  77378. this._babylonGamepads = [];
  77379. };
  77380. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77381. if (!this._oneGamepadConnected) {
  77382. this._oneGamepadConnected = true;
  77383. }
  77384. var newGamepad;
  77385. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77386. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77387. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77388. }
  77389. // if pose is supported, use the (WebVR) pose enabled controller
  77390. else if (gamepad.pose) {
  77391. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77392. }
  77393. else {
  77394. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77395. }
  77396. this._babylonGamepads[newGamepad.index] = newGamepad;
  77397. return newGamepad;
  77398. };
  77399. GamepadManager.prototype._startMonitoringGamepads = function () {
  77400. if (!this._isMonitoring) {
  77401. this._isMonitoring = true;
  77402. //back-comp
  77403. if (!this._scene) {
  77404. this._checkGamepadsStatus();
  77405. }
  77406. }
  77407. };
  77408. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77409. this._isMonitoring = false;
  77410. };
  77411. /** @hidden */
  77412. GamepadManager.prototype._checkGamepadsStatus = function () {
  77413. var _this = this;
  77414. // Hack to be compatible Chrome
  77415. this._updateGamepadObjects();
  77416. for (var i in this._babylonGamepads) {
  77417. var gamepad = this._babylonGamepads[i];
  77418. if (!gamepad || !gamepad.isConnected) {
  77419. continue;
  77420. }
  77421. gamepad.update();
  77422. }
  77423. if (this._isMonitoring && !this._scene) {
  77424. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77425. }
  77426. };
  77427. // This function is called only on Chrome, which does not properly support
  77428. // connection/disconnection events and forces you to recopy again the gamepad object
  77429. GamepadManager.prototype._updateGamepadObjects = function () {
  77430. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77431. for (var i = 0; i < gamepads.length; i++) {
  77432. var gamepad = gamepads[i];
  77433. if (gamepad) {
  77434. if (!this._babylonGamepads[gamepad.index]) {
  77435. var newGamepad = this._addNewGamepad(gamepad);
  77436. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77437. }
  77438. else {
  77439. // Forced to copy again this object for Chrome for unknown reason
  77440. this._babylonGamepads[i].browserGamepad = gamepad;
  77441. if (!this._babylonGamepads[i].isConnected) {
  77442. this._babylonGamepads[i]._isConnected = true;
  77443. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77444. }
  77445. }
  77446. }
  77447. }
  77448. };
  77449. return GamepadManager;
  77450. }());
  77451. BABYLON.GamepadManager = GamepadManager;
  77452. })(BABYLON || (BABYLON = {}));
  77453. //# sourceMappingURL=babylon.gamepadManager.js.map
  77454. var BABYLON;
  77455. (function (BABYLON) {
  77456. /**
  77457. * Represents a gamepad control stick position
  77458. */
  77459. var StickValues = /** @class */ (function () {
  77460. /**
  77461. * Initializes the gamepad x and y control stick values
  77462. * @param x The x component of the gamepad control stick value
  77463. * @param y The y component of the gamepad control stick value
  77464. */
  77465. function StickValues(
  77466. /**
  77467. * The x component of the control stick
  77468. */
  77469. x,
  77470. /**
  77471. * The y component of the control stick
  77472. */
  77473. y) {
  77474. this.x = x;
  77475. this.y = y;
  77476. }
  77477. return StickValues;
  77478. }());
  77479. BABYLON.StickValues = StickValues;
  77480. /**
  77481. * Represents a gamepad
  77482. */
  77483. var Gamepad = /** @class */ (function () {
  77484. /**
  77485. * Initializes the gamepad
  77486. * @param id The id of the gamepad
  77487. * @param index The index of the gamepad
  77488. * @param browserGamepad The browser gamepad
  77489. * @param leftStickX The x component of the left joystick
  77490. * @param leftStickY The y component of the left joystick
  77491. * @param rightStickX The x component of the right joystick
  77492. * @param rightStickY The y component of the right joystick
  77493. */
  77494. function Gamepad(
  77495. /**
  77496. * The id of the gamepad
  77497. */
  77498. id,
  77499. /**
  77500. * The index of the gamepad
  77501. */
  77502. index,
  77503. /**
  77504. * The browser gamepad
  77505. */
  77506. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77507. if (leftStickX === void 0) { leftStickX = 0; }
  77508. if (leftStickY === void 0) { leftStickY = 1; }
  77509. if (rightStickX === void 0) { rightStickX = 2; }
  77510. if (rightStickY === void 0) { rightStickY = 3; }
  77511. this.id = id;
  77512. this.index = index;
  77513. this.browserGamepad = browserGamepad;
  77514. this._leftStick = { x: 0, y: 0 };
  77515. this._rightStick = { x: 0, y: 0 };
  77516. /** @hidden */
  77517. this._isConnected = true;
  77518. /**
  77519. * Specifies whether the left control stick should be Y-inverted
  77520. */
  77521. this._invertLeftStickY = false;
  77522. this.type = Gamepad.GAMEPAD;
  77523. this._leftStickAxisX = leftStickX;
  77524. this._leftStickAxisY = leftStickY;
  77525. this._rightStickAxisX = rightStickX;
  77526. this._rightStickAxisY = rightStickY;
  77527. if (this.browserGamepad.axes.length >= 2) {
  77528. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77529. }
  77530. if (this.browserGamepad.axes.length >= 4) {
  77531. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77532. }
  77533. }
  77534. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77535. /**
  77536. * Specifies if the gamepad has been connected
  77537. */
  77538. get: function () {
  77539. return this._isConnected;
  77540. },
  77541. enumerable: true,
  77542. configurable: true
  77543. });
  77544. /**
  77545. * Callback triggered when the left joystick has changed
  77546. * @param callback
  77547. */
  77548. Gamepad.prototype.onleftstickchanged = function (callback) {
  77549. this._onleftstickchanged = callback;
  77550. };
  77551. /**
  77552. * Callback triggered when the right joystick has changed
  77553. * @param callback
  77554. */
  77555. Gamepad.prototype.onrightstickchanged = function (callback) {
  77556. this._onrightstickchanged = callback;
  77557. };
  77558. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77559. /**
  77560. * Gets the left joystick
  77561. */
  77562. get: function () {
  77563. return this._leftStick;
  77564. },
  77565. /**
  77566. * Sets the left joystick values
  77567. */
  77568. set: function (newValues) {
  77569. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77570. this._onleftstickchanged(newValues);
  77571. }
  77572. this._leftStick = newValues;
  77573. },
  77574. enumerable: true,
  77575. configurable: true
  77576. });
  77577. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77578. /**
  77579. * Gets the right joystick
  77580. */
  77581. get: function () {
  77582. return this._rightStick;
  77583. },
  77584. /**
  77585. * Sets the right joystick value
  77586. */
  77587. set: function (newValues) {
  77588. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77589. this._onrightstickchanged(newValues);
  77590. }
  77591. this._rightStick = newValues;
  77592. },
  77593. enumerable: true,
  77594. configurable: true
  77595. });
  77596. /**
  77597. * Updates the gamepad joystick positions
  77598. */
  77599. Gamepad.prototype.update = function () {
  77600. if (this._leftStick) {
  77601. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77602. if (this._invertLeftStickY) {
  77603. this.leftStick.y *= -1;
  77604. }
  77605. }
  77606. if (this._rightStick) {
  77607. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77608. }
  77609. };
  77610. /**
  77611. * Disposes the gamepad
  77612. */
  77613. Gamepad.prototype.dispose = function () {
  77614. };
  77615. /**
  77616. * Represents a gamepad controller
  77617. */
  77618. Gamepad.GAMEPAD = 0;
  77619. /**
  77620. * Represents a generic controller
  77621. */
  77622. Gamepad.GENERIC = 1;
  77623. /**
  77624. * Represents an XBox controller
  77625. */
  77626. Gamepad.XBOX = 2;
  77627. /**
  77628. * Represents a pose-enabled controller
  77629. */
  77630. Gamepad.POSE_ENABLED = 3;
  77631. return Gamepad;
  77632. }());
  77633. BABYLON.Gamepad = Gamepad;
  77634. /**
  77635. * Represents a generic gamepad
  77636. */
  77637. var GenericPad = /** @class */ (function (_super) {
  77638. __extends(GenericPad, _super);
  77639. /**
  77640. * Initializes the generic gamepad
  77641. * @param id The id of the generic gamepad
  77642. * @param index The index of the generic gamepad
  77643. * @param browserGamepad The browser gamepad
  77644. */
  77645. function GenericPad(id, index, browserGamepad) {
  77646. var _this = _super.call(this, id, index, browserGamepad) || this;
  77647. /**
  77648. * Observable triggered when a button has been pressed
  77649. */
  77650. _this.onButtonDownObservable = new BABYLON.Observable();
  77651. /**
  77652. * Observable triggered when a button has been released
  77653. */
  77654. _this.onButtonUpObservable = new BABYLON.Observable();
  77655. _this.type = Gamepad.GENERIC;
  77656. _this._buttons = new Array(browserGamepad.buttons.length);
  77657. return _this;
  77658. }
  77659. /**
  77660. * Callback triggered when a button has been pressed
  77661. * @param callback Called when a button has been pressed
  77662. */
  77663. GenericPad.prototype.onbuttondown = function (callback) {
  77664. this._onbuttondown = callback;
  77665. };
  77666. /**
  77667. * Callback triggered when a button has been released
  77668. * @param callback Called when a button has been released
  77669. */
  77670. GenericPad.prototype.onbuttonup = function (callback) {
  77671. this._onbuttonup = callback;
  77672. };
  77673. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77674. if (newValue !== currentValue) {
  77675. if (newValue === 1) {
  77676. if (this._onbuttondown) {
  77677. this._onbuttondown(buttonIndex);
  77678. }
  77679. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77680. }
  77681. if (newValue === 0) {
  77682. if (this._onbuttonup) {
  77683. this._onbuttonup(buttonIndex);
  77684. }
  77685. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77686. }
  77687. }
  77688. return newValue;
  77689. };
  77690. /**
  77691. * Updates the generic gamepad
  77692. */
  77693. GenericPad.prototype.update = function () {
  77694. _super.prototype.update.call(this);
  77695. for (var index = 0; index < this._buttons.length; index++) {
  77696. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  77697. }
  77698. };
  77699. /**
  77700. * Disposes the generic gamepad
  77701. */
  77702. GenericPad.prototype.dispose = function () {
  77703. _super.prototype.dispose.call(this);
  77704. this.onButtonDownObservable.clear();
  77705. this.onButtonUpObservable.clear();
  77706. };
  77707. return GenericPad;
  77708. }(Gamepad));
  77709. BABYLON.GenericPad = GenericPad;
  77710. })(BABYLON || (BABYLON = {}));
  77711. //# sourceMappingURL=babylon.gamepad.js.map
  77712. var BABYLON;
  77713. (function (BABYLON) {
  77714. /**
  77715. * Defines supported buttons for XBox360 compatible gamepads
  77716. */
  77717. var Xbox360Button;
  77718. (function (Xbox360Button) {
  77719. /** A */
  77720. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  77721. /** B */
  77722. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  77723. /** X */
  77724. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  77725. /** Y */
  77726. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  77727. /** Start */
  77728. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  77729. /** Back */
  77730. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  77731. /** Left button */
  77732. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  77733. /** Right button */
  77734. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  77735. /** Left stick */
  77736. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  77737. /** Right stick */
  77738. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  77739. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  77740. /** Defines values for XBox360 DPad */
  77741. var Xbox360Dpad;
  77742. (function (Xbox360Dpad) {
  77743. /** Up */
  77744. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  77745. /** Down */
  77746. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  77747. /** Left */
  77748. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  77749. /** Right */
  77750. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  77751. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  77752. /**
  77753. * Defines a XBox360 gamepad
  77754. */
  77755. var Xbox360Pad = /** @class */ (function (_super) {
  77756. __extends(Xbox360Pad, _super);
  77757. /**
  77758. * Creates a new XBox360 gamepad object
  77759. * @param id defines the id of this gamepad
  77760. * @param index defines its index
  77761. * @param gamepad defines the internal HTML gamepad object
  77762. * @param xboxOne defines if it is a XBox One gamepad
  77763. */
  77764. function Xbox360Pad(id, index, gamepad, xboxOne) {
  77765. if (xboxOne === void 0) { xboxOne = false; }
  77766. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  77767. _this._leftTrigger = 0;
  77768. _this._rightTrigger = 0;
  77769. /** Observable raised when a button is pressed */
  77770. _this.onButtonDownObservable = new BABYLON.Observable();
  77771. /** Observable raised when a button is released */
  77772. _this.onButtonUpObservable = new BABYLON.Observable();
  77773. /** Observable raised when a pad is pressed */
  77774. _this.onPadDownObservable = new BABYLON.Observable();
  77775. /** Observable raised when a pad is released */
  77776. _this.onPadUpObservable = new BABYLON.Observable();
  77777. _this._buttonA = 0;
  77778. _this._buttonB = 0;
  77779. _this._buttonX = 0;
  77780. _this._buttonY = 0;
  77781. _this._buttonBack = 0;
  77782. _this._buttonStart = 0;
  77783. _this._buttonLB = 0;
  77784. _this._buttonRB = 0;
  77785. _this._buttonLeftStick = 0;
  77786. _this._buttonRightStick = 0;
  77787. _this._dPadUp = 0;
  77788. _this._dPadDown = 0;
  77789. _this._dPadLeft = 0;
  77790. _this._dPadRight = 0;
  77791. _this._isXboxOnePad = false;
  77792. _this.type = BABYLON.Gamepad.XBOX;
  77793. _this._isXboxOnePad = xboxOne;
  77794. return _this;
  77795. }
  77796. /**
  77797. * Defines the callback to call when left trigger is pressed
  77798. * @param callback defines the callback to use
  77799. */
  77800. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  77801. this._onlefttriggerchanged = callback;
  77802. };
  77803. /**
  77804. * Defines the callback to call when right trigger is pressed
  77805. * @param callback defines the callback to use
  77806. */
  77807. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  77808. this._onrighttriggerchanged = callback;
  77809. };
  77810. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77811. /**
  77812. * Gets the left trigger value
  77813. */
  77814. get: function () {
  77815. return this._leftTrigger;
  77816. },
  77817. /**
  77818. * Sets the left trigger value
  77819. */
  77820. set: function (newValue) {
  77821. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77822. this._onlefttriggerchanged(newValue);
  77823. }
  77824. this._leftTrigger = newValue;
  77825. },
  77826. enumerable: true,
  77827. configurable: true
  77828. });
  77829. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77830. /**
  77831. * Gets the right trigger value
  77832. */
  77833. get: function () {
  77834. return this._rightTrigger;
  77835. },
  77836. /**
  77837. * Sets the right trigger value
  77838. */
  77839. set: function (newValue) {
  77840. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77841. this._onrighttriggerchanged(newValue);
  77842. }
  77843. this._rightTrigger = newValue;
  77844. },
  77845. enumerable: true,
  77846. configurable: true
  77847. });
  77848. /**
  77849. * Defines the callback to call when a button is pressed
  77850. * @param callback defines the callback to use
  77851. */
  77852. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77853. this._onbuttondown = callback;
  77854. };
  77855. /**
  77856. * Defines the callback to call when a button is released
  77857. * @param callback defines the callback to use
  77858. */
  77859. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77860. this._onbuttonup = callback;
  77861. };
  77862. /**
  77863. * Defines the callback to call when a pad is pressed
  77864. * @param callback defines the callback to use
  77865. */
  77866. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77867. this._ondpaddown = callback;
  77868. };
  77869. /**
  77870. * Defines the callback to call when a pad is released
  77871. * @param callback defines the callback to use
  77872. */
  77873. Xbox360Pad.prototype.ondpadup = function (callback) {
  77874. this._ondpadup = callback;
  77875. };
  77876. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77877. if (newValue !== currentValue) {
  77878. if (newValue === 1) {
  77879. if (this._onbuttondown) {
  77880. this._onbuttondown(buttonType);
  77881. }
  77882. this.onButtonDownObservable.notifyObservers(buttonType);
  77883. }
  77884. if (newValue === 0) {
  77885. if (this._onbuttonup) {
  77886. this._onbuttonup(buttonType);
  77887. }
  77888. this.onButtonUpObservable.notifyObservers(buttonType);
  77889. }
  77890. }
  77891. return newValue;
  77892. };
  77893. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77894. if (newValue !== currentValue) {
  77895. if (newValue === 1) {
  77896. if (this._ondpaddown) {
  77897. this._ondpaddown(buttonType);
  77898. }
  77899. this.onPadDownObservable.notifyObservers(buttonType);
  77900. }
  77901. if (newValue === 0) {
  77902. if (this._ondpadup) {
  77903. this._ondpadup(buttonType);
  77904. }
  77905. this.onPadUpObservable.notifyObservers(buttonType);
  77906. }
  77907. }
  77908. return newValue;
  77909. };
  77910. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77911. /**
  77912. * Gets the value of the `A` button
  77913. */
  77914. get: function () {
  77915. return this._buttonA;
  77916. },
  77917. /**
  77918. * Sets the value of the `A` button
  77919. */
  77920. set: function (value) {
  77921. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77922. },
  77923. enumerable: true,
  77924. configurable: true
  77925. });
  77926. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77927. /**
  77928. * Gets the value of the `B` button
  77929. */
  77930. get: function () {
  77931. return this._buttonB;
  77932. },
  77933. /**
  77934. * Sets the value of the `B` button
  77935. */
  77936. set: function (value) {
  77937. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77938. },
  77939. enumerable: true,
  77940. configurable: true
  77941. });
  77942. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77943. /**
  77944. * Gets the value of the `X` button
  77945. */
  77946. get: function () {
  77947. return this._buttonX;
  77948. },
  77949. /**
  77950. * Sets the value of the `X` button
  77951. */
  77952. set: function (value) {
  77953. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77954. },
  77955. enumerable: true,
  77956. configurable: true
  77957. });
  77958. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77959. /**
  77960. * Gets the value of the `Y` button
  77961. */
  77962. get: function () {
  77963. return this._buttonY;
  77964. },
  77965. /**
  77966. * Sets the value of the `Y` button
  77967. */
  77968. set: function (value) {
  77969. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77970. },
  77971. enumerable: true,
  77972. configurable: true
  77973. });
  77974. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77975. /**
  77976. * Gets the value of the `Start` button
  77977. */
  77978. get: function () {
  77979. return this._buttonStart;
  77980. },
  77981. /**
  77982. * Sets the value of the `Start` button
  77983. */
  77984. set: function (value) {
  77985. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77986. },
  77987. enumerable: true,
  77988. configurable: true
  77989. });
  77990. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77991. /**
  77992. * Gets the value of the `Back` button
  77993. */
  77994. get: function () {
  77995. return this._buttonBack;
  77996. },
  77997. /**
  77998. * Sets the value of the `Back` button
  77999. */
  78000. set: function (value) {
  78001. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  78002. },
  78003. enumerable: true,
  78004. configurable: true
  78005. });
  78006. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  78007. /**
  78008. * Gets the value of the `Left` button
  78009. */
  78010. get: function () {
  78011. return this._buttonLB;
  78012. },
  78013. /**
  78014. * Sets the value of the `Left` button
  78015. */
  78016. set: function (value) {
  78017. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  78018. },
  78019. enumerable: true,
  78020. configurable: true
  78021. });
  78022. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  78023. /**
  78024. * Gets the value of the `Right` button
  78025. */
  78026. get: function () {
  78027. return this._buttonRB;
  78028. },
  78029. /**
  78030. * Sets the value of the `Right` button
  78031. */
  78032. set: function (value) {
  78033. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  78034. },
  78035. enumerable: true,
  78036. configurable: true
  78037. });
  78038. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  78039. /**
  78040. * Gets the value of the Left joystick
  78041. */
  78042. get: function () {
  78043. return this._buttonLeftStick;
  78044. },
  78045. /**
  78046. * Sets the value of the Left joystick
  78047. */
  78048. set: function (value) {
  78049. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  78050. },
  78051. enumerable: true,
  78052. configurable: true
  78053. });
  78054. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  78055. /**
  78056. * Gets the value of the Right joystick
  78057. */
  78058. get: function () {
  78059. return this._buttonRightStick;
  78060. },
  78061. /**
  78062. * Sets the value of the Right joystick
  78063. */
  78064. set: function (value) {
  78065. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  78066. },
  78067. enumerable: true,
  78068. configurable: true
  78069. });
  78070. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  78071. /**
  78072. * Gets the value of D-pad up
  78073. */
  78074. get: function () {
  78075. return this._dPadUp;
  78076. },
  78077. /**
  78078. * Sets the value of D-pad up
  78079. */
  78080. set: function (value) {
  78081. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  78082. },
  78083. enumerable: true,
  78084. configurable: true
  78085. });
  78086. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  78087. /**
  78088. * Gets the value of D-pad down
  78089. */
  78090. get: function () {
  78091. return this._dPadDown;
  78092. },
  78093. /**
  78094. * Sets the value of D-pad down
  78095. */
  78096. set: function (value) {
  78097. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  78098. },
  78099. enumerable: true,
  78100. configurable: true
  78101. });
  78102. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  78103. /**
  78104. * Gets the value of D-pad left
  78105. */
  78106. get: function () {
  78107. return this._dPadLeft;
  78108. },
  78109. /**
  78110. * Sets the value of D-pad left
  78111. */
  78112. set: function (value) {
  78113. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  78114. },
  78115. enumerable: true,
  78116. configurable: true
  78117. });
  78118. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  78119. /**
  78120. * Gets the value of D-pad right
  78121. */
  78122. get: function () {
  78123. return this._dPadRight;
  78124. },
  78125. /**
  78126. * Sets the value of D-pad right
  78127. */
  78128. set: function (value) {
  78129. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  78130. },
  78131. enumerable: true,
  78132. configurable: true
  78133. });
  78134. /**
  78135. * Force the gamepad to synchronize with device values
  78136. */
  78137. Xbox360Pad.prototype.update = function () {
  78138. _super.prototype.update.call(this);
  78139. if (this._isXboxOnePad) {
  78140. this.buttonA = this.browserGamepad.buttons[0].value;
  78141. this.buttonB = this.browserGamepad.buttons[1].value;
  78142. this.buttonX = this.browserGamepad.buttons[2].value;
  78143. this.buttonY = this.browserGamepad.buttons[3].value;
  78144. this.buttonLB = this.browserGamepad.buttons[4].value;
  78145. this.buttonRB = this.browserGamepad.buttons[5].value;
  78146. this.leftTrigger = this.browserGamepad.axes[2];
  78147. this.rightTrigger = this.browserGamepad.axes[5];
  78148. this.buttonBack = this.browserGamepad.buttons[9].value;
  78149. this.buttonStart = this.browserGamepad.buttons[8].value;
  78150. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  78151. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  78152. this.dPadUp = this.browserGamepad.buttons[11].value;
  78153. this.dPadDown = this.browserGamepad.buttons[12].value;
  78154. this.dPadLeft = this.browserGamepad.buttons[13].value;
  78155. this.dPadRight = this.browserGamepad.buttons[14].value;
  78156. }
  78157. else {
  78158. this.buttonA = this.browserGamepad.buttons[0].value;
  78159. this.buttonB = this.browserGamepad.buttons[1].value;
  78160. this.buttonX = this.browserGamepad.buttons[2].value;
  78161. this.buttonY = this.browserGamepad.buttons[3].value;
  78162. this.buttonLB = this.browserGamepad.buttons[4].value;
  78163. this.buttonRB = this.browserGamepad.buttons[5].value;
  78164. this.leftTrigger = this.browserGamepad.buttons[6].value;
  78165. this.rightTrigger = this.browserGamepad.buttons[7].value;
  78166. this.buttonBack = this.browserGamepad.buttons[8].value;
  78167. this.buttonStart = this.browserGamepad.buttons[9].value;
  78168. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  78169. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  78170. this.dPadUp = this.browserGamepad.buttons[12].value;
  78171. this.dPadDown = this.browserGamepad.buttons[13].value;
  78172. this.dPadLeft = this.browserGamepad.buttons[14].value;
  78173. this.dPadRight = this.browserGamepad.buttons[15].value;
  78174. }
  78175. };
  78176. /**
  78177. * Disposes the gamepad
  78178. */
  78179. Xbox360Pad.prototype.dispose = function () {
  78180. _super.prototype.dispose.call(this);
  78181. this.onButtonDownObservable.clear();
  78182. this.onButtonUpObservable.clear();
  78183. this.onPadDownObservable.clear();
  78184. this.onPadUpObservable.clear();
  78185. };
  78186. return Xbox360Pad;
  78187. }(BABYLON.Gamepad));
  78188. BABYLON.Xbox360Pad = Xbox360Pad;
  78189. })(BABYLON || (BABYLON = {}));
  78190. //# sourceMappingURL=babylon.xboxGamepad.js.map
  78191. var BABYLON;
  78192. (function (BABYLON) {
  78193. /**
  78194. * Defines the types of pose enabled controllers that are supported
  78195. */
  78196. var PoseEnabledControllerType;
  78197. (function (PoseEnabledControllerType) {
  78198. /**
  78199. * HTC Vive
  78200. */
  78201. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  78202. /**
  78203. * Oculus Rift
  78204. */
  78205. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  78206. /**
  78207. * Windows mixed reality
  78208. */
  78209. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  78210. /**
  78211. * Samsung gear VR
  78212. */
  78213. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  78214. /**
  78215. * Google Daydream
  78216. */
  78217. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  78218. /**
  78219. * Generic
  78220. */
  78221. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  78222. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  78223. /**
  78224. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78225. */
  78226. var PoseEnabledControllerHelper = /** @class */ (function () {
  78227. function PoseEnabledControllerHelper() {
  78228. }
  78229. /**
  78230. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78231. * @param vrGamepad the gamepad to initialized
  78232. * @returns a vr controller of the type the gamepad identified as
  78233. */
  78234. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  78235. // Oculus Touch
  78236. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  78237. return new BABYLON.OculusTouchController(vrGamepad);
  78238. }
  78239. // Windows Mixed Reality controllers
  78240. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  78241. return new BABYLON.WindowsMotionController(vrGamepad);
  78242. }
  78243. // HTC Vive
  78244. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  78245. return new BABYLON.ViveController(vrGamepad);
  78246. }
  78247. // Samsung/Oculus Gear VR or Oculus Go
  78248. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  78249. return new BABYLON.GearVRController(vrGamepad);
  78250. }
  78251. // Google Daydream
  78252. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  78253. return new BABYLON.DaydreamController(vrGamepad);
  78254. }
  78255. // Generic
  78256. else {
  78257. return new BABYLON.GenericController(vrGamepad);
  78258. }
  78259. };
  78260. return PoseEnabledControllerHelper;
  78261. }());
  78262. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  78263. /**
  78264. * Defines the PoseEnabledController object that contains state of a vr capable controller
  78265. */
  78266. var PoseEnabledController = /** @class */ (function (_super) {
  78267. __extends(PoseEnabledController, _super);
  78268. /**
  78269. * Creates a new PoseEnabledController from a gamepad
  78270. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  78271. */
  78272. function PoseEnabledController(browserGamepad) {
  78273. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  78274. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78275. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78276. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  78277. /**
  78278. * The device position in babylon space
  78279. */
  78280. _this.devicePosition = BABYLON.Vector3.Zero();
  78281. /**
  78282. * The device rotation in babylon space
  78283. */
  78284. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  78285. /**
  78286. * The scale factor of the device in babylon space
  78287. */
  78288. _this.deviceScaleFactor = 1;
  78289. // Used to convert 6dof controllers to 3dof
  78290. _this._trackPosition = true;
  78291. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78292. _this._draggedRoomRotation = 0;
  78293. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  78294. /**
  78295. * Internal, matrix used to convert room space to babylon space
  78296. * @hidden
  78297. */
  78298. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78299. /**
  78300. * Node to be used when casting a ray from the controller
  78301. * @hidden
  78302. */
  78303. _this._pointingPoseNode = null;
  78304. _this._workingMatrix = BABYLON.Matrix.Identity();
  78305. /**
  78306. * @hidden
  78307. */
  78308. _this._meshAttachedObservable = new BABYLON.Observable();
  78309. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  78310. _this.controllerType = PoseEnabledControllerType.GENERIC;
  78311. _this.position = BABYLON.Vector3.Zero();
  78312. _this.rotationQuaternion = new BABYLON.Quaternion();
  78313. _this._calculatedPosition = BABYLON.Vector3.Zero();
  78314. _this._calculatedRotation = new BABYLON.Quaternion();
  78315. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  78316. return _this;
  78317. }
  78318. /**
  78319. * @hidden
  78320. */
  78321. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  78322. if (this._trackPosition) {
  78323. this._calculatedPosition.copyFrom(fixedPosition);
  78324. this._trackPosition = false;
  78325. }
  78326. };
  78327. /**
  78328. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  78329. */
  78330. PoseEnabledController.prototype.update = function () {
  78331. _super.prototype.update.call(this);
  78332. this._updatePoseAndMesh();
  78333. };
  78334. /**
  78335. * Updates only the pose device and mesh without doing any button event checking
  78336. */
  78337. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  78338. var pose = this.browserGamepad.pose;
  78339. this.updateFromDevice(pose);
  78340. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  78341. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78342. camera._computeDevicePosition();
  78343. this._deviceToWorld.setTranslation(camera.devicePosition);
  78344. if (camera.deviceRotationQuaternion) {
  78345. var camera = camera;
  78346. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  78347. // Find the radian distance away that the headset is from the controllers rotation
  78348. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  78349. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78350. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78351. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78352. this._draggedRoomRotation += rotationAmount;
  78353. // Rotate controller around headset
  78354. var sin = Math.sin(-rotationAmount);
  78355. var cos = Math.cos(-rotationAmount);
  78356. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78357. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78358. }
  78359. }
  78360. }
  78361. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  78362. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  78363. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78364. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  78365. if (this._mesh) {
  78366. this._mesh.position.copyFrom(this.devicePosition);
  78367. if (this._mesh.rotationQuaternion) {
  78368. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  78369. }
  78370. }
  78371. };
  78372. /**
  78373. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78374. * @param poseData raw pose fromthe device
  78375. */
  78376. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  78377. if (poseData) {
  78378. this.rawPose = poseData;
  78379. if (poseData.position) {
  78380. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  78381. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  78382. this._deviceRoomPosition.z *= -1;
  78383. }
  78384. if (this._trackPosition) {
  78385. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  78386. }
  78387. this._calculatedPosition.addInPlace(this.position);
  78388. }
  78389. var pose = this.rawPose;
  78390. if (poseData.orientation && pose.orientation) {
  78391. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  78392. if (this._mesh) {
  78393. if (this._mesh.getScene().useRightHandedSystem) {
  78394. this._deviceRoomRotationQuaternion.z *= -1;
  78395. this._deviceRoomRotationQuaternion.w *= -1;
  78396. }
  78397. else {
  78398. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  78399. }
  78400. }
  78401. // if the camera is set, rotate to the camera's rotation
  78402. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  78403. }
  78404. }
  78405. };
  78406. /**
  78407. * Attaches a mesh to the controller
  78408. * @param mesh the mesh to be attached
  78409. */
  78410. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  78411. if (this._mesh) {
  78412. this._mesh.parent = null;
  78413. }
  78414. this._mesh = mesh;
  78415. if (this._poseControlledCamera) {
  78416. this._mesh.parent = this._poseControlledCamera;
  78417. }
  78418. if (!this._mesh.rotationQuaternion) {
  78419. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  78420. }
  78421. // 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
  78422. this._updatePoseAndMesh();
  78423. if (this._pointingPoseNode) {
  78424. var parents = [];
  78425. var obj = this._pointingPoseNode;
  78426. while (obj.parent) {
  78427. parents.push(obj.parent);
  78428. obj = obj.parent;
  78429. }
  78430. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  78431. }
  78432. this._meshAttachedObservable.notifyObservers(mesh);
  78433. };
  78434. /**
  78435. * Attaches the controllers mesh to a camera
  78436. * @param camera the camera the mesh should be attached to
  78437. */
  78438. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  78439. this._poseControlledCamera = camera;
  78440. if (this._mesh) {
  78441. this._mesh.parent = this._poseControlledCamera;
  78442. }
  78443. };
  78444. /**
  78445. * Disposes of the controller
  78446. */
  78447. PoseEnabledController.prototype.dispose = function () {
  78448. if (this._mesh) {
  78449. this._mesh.dispose();
  78450. }
  78451. this._mesh = null;
  78452. _super.prototype.dispose.call(this);
  78453. };
  78454. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  78455. /**
  78456. * The mesh that is attached to the controller
  78457. */
  78458. get: function () {
  78459. return this._mesh;
  78460. },
  78461. enumerable: true,
  78462. configurable: true
  78463. });
  78464. /**
  78465. * Gets the ray of the controller in the direction the controller is pointing
  78466. * @param length the length the resulting ray should be
  78467. * @returns a ray in the direction the controller is pointing
  78468. */
  78469. PoseEnabledController.prototype.getForwardRay = function (length) {
  78470. if (length === void 0) { length = 100; }
  78471. if (!this.mesh) {
  78472. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  78473. }
  78474. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  78475. var origin = m.getTranslation();
  78476. var forward = new BABYLON.Vector3(0, 0, -1);
  78477. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78478. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78479. return new BABYLON.Ray(origin, direction, length);
  78480. };
  78481. /**
  78482. * Name of the child mesh that can be used to cast a ray from the controller
  78483. */
  78484. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  78485. return PoseEnabledController;
  78486. }(BABYLON.Gamepad));
  78487. BABYLON.PoseEnabledController = PoseEnabledController;
  78488. })(BABYLON || (BABYLON = {}));
  78489. //# sourceMappingURL=babylon.poseEnabledController.js.map
  78490. var BABYLON;
  78491. (function (BABYLON) {
  78492. /**
  78493. * Defines the WebVRController object that represents controllers tracked in 3D space
  78494. */
  78495. var WebVRController = /** @class */ (function (_super) {
  78496. __extends(WebVRController, _super);
  78497. /**
  78498. * Creates a new WebVRController from a gamepad
  78499. * @param vrGamepad the gamepad that the WebVRController should be created from
  78500. */
  78501. function WebVRController(vrGamepad) {
  78502. var _this = _super.call(this, vrGamepad) || this;
  78503. // Observables
  78504. /**
  78505. * Fired when the trigger state has changed
  78506. */
  78507. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  78508. /**
  78509. * Fired when the main button state has changed
  78510. */
  78511. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  78512. /**
  78513. * Fired when the secondary button state has changed
  78514. */
  78515. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  78516. /**
  78517. * Fired when the pad state has changed
  78518. */
  78519. _this.onPadStateChangedObservable = new BABYLON.Observable();
  78520. /**
  78521. * Fired when controllers stick values have changed
  78522. */
  78523. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  78524. /**
  78525. * X and Y axis corrisponding to the controllers joystick
  78526. */
  78527. _this.pad = { x: 0, y: 0 };
  78528. // avoid GC, store state in a tmp object
  78529. _this._changes = {
  78530. pressChanged: false,
  78531. touchChanged: false,
  78532. valueChanged: false,
  78533. changed: false
  78534. };
  78535. _this._buttons = new Array(vrGamepad.buttons.length);
  78536. _this.hand = vrGamepad.hand;
  78537. return _this;
  78538. }
  78539. /**
  78540. * Fired when a controller button's state has changed
  78541. * @param callback the callback containing the button that was modified
  78542. */
  78543. WebVRController.prototype.onButtonStateChange = function (callback) {
  78544. this._onButtonStateChange = callback;
  78545. };
  78546. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78547. /**
  78548. * The default controller model for the controller
  78549. */
  78550. get: function () {
  78551. return this._defaultModel;
  78552. },
  78553. enumerable: true,
  78554. configurable: true
  78555. });
  78556. /**
  78557. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78558. */
  78559. WebVRController.prototype.update = function () {
  78560. _super.prototype.update.call(this);
  78561. for (var index = 0; index < this._buttons.length; index++) {
  78562. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78563. }
  78564. ;
  78565. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78566. this.pad.x = this.leftStick.x;
  78567. this.pad.y = this.leftStick.y;
  78568. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78569. }
  78570. };
  78571. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78572. if (!newState) {
  78573. newState = {
  78574. pressed: false,
  78575. touched: false,
  78576. value: 0
  78577. };
  78578. }
  78579. if (!currentState) {
  78580. this._buttons[buttonIndex] = {
  78581. pressed: newState.pressed,
  78582. touched: newState.touched,
  78583. value: newState.value
  78584. };
  78585. return;
  78586. }
  78587. this._checkChanges(newState, currentState);
  78588. if (this._changes.changed) {
  78589. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78590. this._handleButtonChange(buttonIndex, newState, this._changes);
  78591. }
  78592. this._buttons[buttonIndex].pressed = newState.pressed;
  78593. this._buttons[buttonIndex].touched = newState.touched;
  78594. // oculus triggers are never 0, thou not touched.
  78595. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78596. };
  78597. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78598. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78599. this._changes.touchChanged = newState.touched !== currentState.touched;
  78600. this._changes.valueChanged = newState.value !== currentState.value;
  78601. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78602. return this._changes;
  78603. };
  78604. /**
  78605. * Disposes of th webVRCOntroller
  78606. */
  78607. WebVRController.prototype.dispose = function () {
  78608. _super.prototype.dispose.call(this);
  78609. this.onTriggerStateChangedObservable.clear();
  78610. this.onMainButtonStateChangedObservable.clear();
  78611. this.onSecondaryButtonStateChangedObservable.clear();
  78612. this.onPadStateChangedObservable.clear();
  78613. this.onPadValuesChangedObservable.clear();
  78614. };
  78615. return WebVRController;
  78616. }(BABYLON.PoseEnabledController));
  78617. BABYLON.WebVRController = WebVRController;
  78618. })(BABYLON || (BABYLON = {}));
  78619. //# sourceMappingURL=babylon.webVRController.js.map
  78620. var BABYLON;
  78621. (function (BABYLON) {
  78622. /**
  78623. * Oculus Touch Controller
  78624. */
  78625. var OculusTouchController = /** @class */ (function (_super) {
  78626. __extends(OculusTouchController, _super);
  78627. /**
  78628. * Creates a new OculusTouchController from a gamepad
  78629. * @param vrGamepad the gamepad that the controller should be created from
  78630. */
  78631. function OculusTouchController(vrGamepad) {
  78632. var _this = _super.call(this, vrGamepad) || this;
  78633. /**
  78634. * Fired when the secondary trigger on this controller is modified
  78635. */
  78636. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78637. /**
  78638. * Fired when the thumb rest on this controller is modified
  78639. */
  78640. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78641. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78642. return _this;
  78643. }
  78644. /**
  78645. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78646. * @param scene scene in which to add meshes
  78647. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78648. */
  78649. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78650. var _this = this;
  78651. var meshName;
  78652. // Hand
  78653. if (this.hand === 'left') {
  78654. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78655. }
  78656. else { // Right is the default if no hand is specified
  78657. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78658. }
  78659. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78660. /*
  78661. Parent Mesh name: oculus_touch_left
  78662. - body
  78663. - trigger
  78664. - thumbstick
  78665. - grip
  78666. - button_y
  78667. - button_x
  78668. - button_enter
  78669. */
  78670. _this._defaultModel = newMeshes[1];
  78671. _this.attachToMesh(_this._defaultModel);
  78672. if (meshLoaded) {
  78673. meshLoaded(_this._defaultModel);
  78674. }
  78675. });
  78676. };
  78677. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  78678. /**
  78679. * Fired when the A button on this controller is modified
  78680. */
  78681. get: function () {
  78682. if (this.hand === 'right') {
  78683. return this.onMainButtonStateChangedObservable;
  78684. }
  78685. else {
  78686. throw new Error('No A button on left hand');
  78687. }
  78688. },
  78689. enumerable: true,
  78690. configurable: true
  78691. });
  78692. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  78693. /**
  78694. * Fired when the B button on this controller is modified
  78695. */
  78696. get: function () {
  78697. if (this.hand === 'right') {
  78698. return this.onSecondaryButtonStateChangedObservable;
  78699. }
  78700. else {
  78701. throw new Error('No B button on left hand');
  78702. }
  78703. },
  78704. enumerable: true,
  78705. configurable: true
  78706. });
  78707. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  78708. /**
  78709. * Fired when the X button on this controller is modified
  78710. */
  78711. get: function () {
  78712. if (this.hand === 'left') {
  78713. return this.onMainButtonStateChangedObservable;
  78714. }
  78715. else {
  78716. throw new Error('No X button on right hand');
  78717. }
  78718. },
  78719. enumerable: true,
  78720. configurable: true
  78721. });
  78722. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  78723. /**
  78724. * Fired when the Y button on this controller is modified
  78725. */
  78726. get: function () {
  78727. if (this.hand === 'left') {
  78728. return this.onSecondaryButtonStateChangedObservable;
  78729. }
  78730. else {
  78731. throw new Error('No Y button on right hand');
  78732. }
  78733. },
  78734. enumerable: true,
  78735. configurable: true
  78736. });
  78737. /**
  78738. * Called once for each button that changed state since the last frame
  78739. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  78740. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  78741. * 2) secondary trigger (same)
  78742. * 3) A (right) X (left), touch, pressed = value
  78743. * 4) B / Y
  78744. * 5) thumb rest
  78745. * @param buttonIdx Which button index changed
  78746. * @param state New state of the button
  78747. * @param changes Which properties on the state changed since last frame
  78748. */
  78749. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78750. var notifyObject = state; //{ state: state, changes: changes };
  78751. var triggerDirection = this.hand === 'right' ? -1 : 1;
  78752. switch (buttonIdx) {
  78753. case 0:
  78754. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78755. return;
  78756. case 1: // index trigger
  78757. if (this._defaultModel) {
  78758. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  78759. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  78760. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  78761. }
  78762. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78763. return;
  78764. case 2: // secondary trigger
  78765. if (this._defaultModel) {
  78766. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  78767. }
  78768. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  78769. return;
  78770. case 3:
  78771. if (this._defaultModel) {
  78772. if (notifyObject.pressed) {
  78773. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  78774. }
  78775. else {
  78776. (this._defaultModel.getChildren()[1]).position.y = 0;
  78777. }
  78778. }
  78779. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78780. return;
  78781. case 4:
  78782. if (this._defaultModel) {
  78783. if (notifyObject.pressed) {
  78784. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78785. }
  78786. else {
  78787. (this._defaultModel.getChildren()[2]).position.y = 0;
  78788. }
  78789. }
  78790. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78791. return;
  78792. case 5:
  78793. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  78794. return;
  78795. }
  78796. };
  78797. /**
  78798. * Base Url for the controller model.
  78799. */
  78800. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  78801. /**
  78802. * File name for the left controller model.
  78803. */
  78804. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  78805. /**
  78806. * File name for the right controller model.
  78807. */
  78808. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  78809. return OculusTouchController;
  78810. }(BABYLON.WebVRController));
  78811. BABYLON.OculusTouchController = OculusTouchController;
  78812. })(BABYLON || (BABYLON = {}));
  78813. //# sourceMappingURL=babylon.oculusTouchController.js.map
  78814. var BABYLON;
  78815. (function (BABYLON) {
  78816. /**
  78817. * Vive Controller
  78818. */
  78819. var ViveController = /** @class */ (function (_super) {
  78820. __extends(ViveController, _super);
  78821. /**
  78822. * Creates a new ViveController from a gamepad
  78823. * @param vrGamepad the gamepad that the controller should be created from
  78824. */
  78825. function ViveController(vrGamepad) {
  78826. var _this = _super.call(this, vrGamepad) || this;
  78827. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  78828. _this._invertLeftStickY = true;
  78829. return _this;
  78830. }
  78831. /**
  78832. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78833. * @param scene scene in which to add meshes
  78834. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78835. */
  78836. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78837. var _this = this;
  78838. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  78839. /*
  78840. Parent Mesh name: ViveWand
  78841. - body
  78842. - r_gripper
  78843. - l_gripper
  78844. - menu_button
  78845. - system_button
  78846. - trackpad
  78847. - trigger
  78848. - LED
  78849. */
  78850. _this._defaultModel = newMeshes[1];
  78851. _this.attachToMesh(_this._defaultModel);
  78852. if (meshLoaded) {
  78853. meshLoaded(_this._defaultModel);
  78854. }
  78855. });
  78856. };
  78857. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  78858. /**
  78859. * Fired when the left button on this controller is modified
  78860. */
  78861. get: function () {
  78862. return this.onMainButtonStateChangedObservable;
  78863. },
  78864. enumerable: true,
  78865. configurable: true
  78866. });
  78867. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  78868. /**
  78869. * Fired when the right button on this controller is modified
  78870. */
  78871. get: function () {
  78872. return this.onMainButtonStateChangedObservable;
  78873. },
  78874. enumerable: true,
  78875. configurable: true
  78876. });
  78877. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  78878. /**
  78879. * Fired when the menu button on this controller is modified
  78880. */
  78881. get: function () {
  78882. return this.onSecondaryButtonStateChangedObservable;
  78883. },
  78884. enumerable: true,
  78885. configurable: true
  78886. });
  78887. /**
  78888. * Called once for each button that changed state since the last frame
  78889. * Vive mapping:
  78890. * 0: touchpad
  78891. * 1: trigger
  78892. * 2: left AND right buttons
  78893. * 3: menu button
  78894. * @param buttonIdx Which button index changed
  78895. * @param state New state of the button
  78896. * @param changes Which properties on the state changed since last frame
  78897. */
  78898. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78899. var notifyObject = state; //{ state: state, changes: changes };
  78900. switch (buttonIdx) {
  78901. case 0:
  78902. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78903. return;
  78904. case 1: // index trigger
  78905. if (this._defaultModel) {
  78906. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  78907. }
  78908. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78909. return;
  78910. case 2: // left AND right button
  78911. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78912. return;
  78913. case 3:
  78914. if (this._defaultModel) {
  78915. if (notifyObject.pressed) {
  78916. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78917. }
  78918. else {
  78919. (this._defaultModel.getChildren()[2]).position.y = 0;
  78920. }
  78921. }
  78922. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78923. return;
  78924. }
  78925. };
  78926. /**
  78927. * Base Url for the controller model.
  78928. */
  78929. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78930. /**
  78931. * File name for the controller model.
  78932. */
  78933. ViveController.MODEL_FILENAME = 'wand.babylon';
  78934. return ViveController;
  78935. }(BABYLON.WebVRController));
  78936. BABYLON.ViveController = ViveController;
  78937. })(BABYLON || (BABYLON = {}));
  78938. //# sourceMappingURL=babylon.viveController.js.map
  78939. var BABYLON;
  78940. (function (BABYLON) {
  78941. /**
  78942. * Generic Controller
  78943. */
  78944. var GenericController = /** @class */ (function (_super) {
  78945. __extends(GenericController, _super);
  78946. /**
  78947. * Creates a new GenericController from a gamepad
  78948. * @param vrGamepad the gamepad that the controller should be created from
  78949. */
  78950. function GenericController(vrGamepad) {
  78951. return _super.call(this, vrGamepad) || this;
  78952. }
  78953. /**
  78954. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78955. * @param scene scene in which to add meshes
  78956. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78957. */
  78958. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78959. var _this = this;
  78960. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78961. _this._defaultModel = newMeshes[1];
  78962. _this.attachToMesh(_this._defaultModel);
  78963. if (meshLoaded) {
  78964. meshLoaded(_this._defaultModel);
  78965. }
  78966. });
  78967. };
  78968. /**
  78969. * Called once for each button that changed state since the last frame
  78970. * @param buttonIdx Which button index changed
  78971. * @param state New state of the button
  78972. * @param changes Which properties on the state changed since last frame
  78973. */
  78974. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78975. console.log("Button id: " + buttonIdx + "state: ");
  78976. console.dir(state);
  78977. };
  78978. /**
  78979. * Base Url for the controller model.
  78980. */
  78981. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78982. /**
  78983. * File name for the controller model.
  78984. */
  78985. GenericController.MODEL_FILENAME = 'generic.babylon';
  78986. return GenericController;
  78987. }(BABYLON.WebVRController));
  78988. BABYLON.GenericController = GenericController;
  78989. })(BABYLON || (BABYLON = {}));
  78990. //# sourceMappingURL=babylon.genericController.js.map
  78991. var BABYLON;
  78992. (function (BABYLON) {
  78993. /**
  78994. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78995. */
  78996. var LoadedMeshInfo = /** @class */ (function () {
  78997. function LoadedMeshInfo() {
  78998. /**
  78999. * Map of the button meshes contained in the controller
  79000. */
  79001. this.buttonMeshes = {};
  79002. /**
  79003. * Map of the axis meshes contained in the controller
  79004. */
  79005. this.axisMeshes = {};
  79006. }
  79007. return LoadedMeshInfo;
  79008. }());
  79009. /**
  79010. * Defines the WindowsMotionController object that the state of the windows motion controller
  79011. */
  79012. var WindowsMotionController = /** @class */ (function (_super) {
  79013. __extends(WindowsMotionController, _super);
  79014. /**
  79015. * Creates a new WindowsMotionController from a gamepad
  79016. * @param vrGamepad the gamepad that the controller should be created from
  79017. */
  79018. function WindowsMotionController(vrGamepad) {
  79019. var _this = _super.call(this, vrGamepad) || this;
  79020. _this._mapping = {
  79021. // Semantic button names
  79022. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  79023. // A mapping of the button name to glTF model node name
  79024. // that should be transformed by button value.
  79025. buttonMeshNames: {
  79026. 'trigger': 'SELECT',
  79027. 'menu': 'MENU',
  79028. 'grip': 'GRASP',
  79029. 'thumbstick': 'THUMBSTICK_PRESS',
  79030. 'trackpad': 'TOUCHPAD_PRESS'
  79031. },
  79032. // This mapping is used to translate from the Motion Controller to Babylon semantics
  79033. buttonObservableNames: {
  79034. 'trigger': 'onTriggerStateChangedObservable',
  79035. 'menu': 'onSecondaryButtonStateChangedObservable',
  79036. 'grip': 'onMainButtonStateChangedObservable',
  79037. 'thumbstick': 'onPadStateChangedObservable',
  79038. 'trackpad': 'onTrackpadChangedObservable'
  79039. },
  79040. // A mapping of the axis name to glTF model node name
  79041. // that should be transformed by axis value.
  79042. // This array mirrors the browserGamepad.axes array, such that
  79043. // the mesh corresponding to axis 0 is in this array index 0.
  79044. axisMeshNames: [
  79045. 'THUMBSTICK_X',
  79046. 'THUMBSTICK_Y',
  79047. 'TOUCHPAD_TOUCH_X',
  79048. 'TOUCHPAD_TOUCH_Y'
  79049. ],
  79050. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  79051. };
  79052. /**
  79053. * Fired when the trackpad on this controller is clicked
  79054. */
  79055. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  79056. /**
  79057. * Fired when the trackpad on this controller is modified
  79058. */
  79059. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  79060. /**
  79061. * The current x and y values of this controller's trackpad
  79062. */
  79063. _this.trackpad = { x: 0, y: 0 };
  79064. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  79065. _this._loadedMeshInfo = null;
  79066. return _this;
  79067. }
  79068. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  79069. /**
  79070. * Fired when the trigger on this controller is modified
  79071. */
  79072. get: function () {
  79073. return this.onTriggerStateChangedObservable;
  79074. },
  79075. enumerable: true,
  79076. configurable: true
  79077. });
  79078. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  79079. /**
  79080. * Fired when the menu button on this controller is modified
  79081. */
  79082. get: function () {
  79083. return this.onSecondaryButtonStateChangedObservable;
  79084. },
  79085. enumerable: true,
  79086. configurable: true
  79087. });
  79088. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  79089. /**
  79090. * Fired when the grip button on this controller is modified
  79091. */
  79092. get: function () {
  79093. return this.onMainButtonStateChangedObservable;
  79094. },
  79095. enumerable: true,
  79096. configurable: true
  79097. });
  79098. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  79099. /**
  79100. * Fired when the thumbstick button on this controller is modified
  79101. */
  79102. get: function () {
  79103. return this.onPadStateChangedObservable;
  79104. },
  79105. enumerable: true,
  79106. configurable: true
  79107. });
  79108. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  79109. /**
  79110. * Fired when the touchpad button on this controller is modified
  79111. */
  79112. get: function () {
  79113. return this.onTrackpadChangedObservable;
  79114. },
  79115. enumerable: true,
  79116. configurable: true
  79117. });
  79118. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  79119. /**
  79120. * Fired when the touchpad values on this controller are modified
  79121. */
  79122. get: function () {
  79123. return this.onTrackpadValuesChangedObservable;
  79124. },
  79125. enumerable: true,
  79126. configurable: true
  79127. });
  79128. WindowsMotionController.prototype._updateTrackpad = function () {
  79129. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  79130. this.trackpad.x = this.browserGamepad["axes"][2];
  79131. this.trackpad.y = this.browserGamepad["axes"][3];
  79132. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  79133. }
  79134. };
  79135. /**
  79136. * Called once per frame by the engine.
  79137. */
  79138. WindowsMotionController.prototype.update = function () {
  79139. _super.prototype.update.call(this);
  79140. if (this.browserGamepad.axes) {
  79141. this._updateTrackpad();
  79142. // Only need to animate axes if there is a loaded mesh
  79143. if (this._loadedMeshInfo) {
  79144. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  79145. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  79146. }
  79147. }
  79148. }
  79149. };
  79150. /**
  79151. * Called once for each button that changed state since the last frame
  79152. * @param buttonIdx Which button index changed
  79153. * @param state New state of the button
  79154. * @param changes Which properties on the state changed since last frame
  79155. */
  79156. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79157. var buttonName = this._mapping.buttons[buttonIdx];
  79158. if (!buttonName) {
  79159. return;
  79160. }
  79161. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  79162. this._updateTrackpad();
  79163. // Only emit events for buttons that we know how to map from index to name
  79164. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  79165. if (observable) {
  79166. observable.notifyObservers(state);
  79167. }
  79168. this._lerpButtonTransform(buttonName, state.value);
  79169. };
  79170. /**
  79171. * Moves the buttons on the controller mesh based on their current state
  79172. * @param buttonName the name of the button to move
  79173. * @param buttonValue the value of the button which determines the buttons new position
  79174. */
  79175. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  79176. // If there is no loaded mesh, there is nothing to transform.
  79177. if (!this._loadedMeshInfo) {
  79178. return;
  79179. }
  79180. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  79181. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79182. return;
  79183. }
  79184. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  79185. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  79186. };
  79187. /**
  79188. * Moves the axis on the controller mesh based on its current state
  79189. * @param axis the index of the axis
  79190. * @param axisValue the value of the axis which determines the meshes new position
  79191. * @hidden
  79192. */
  79193. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  79194. if (!this._loadedMeshInfo) {
  79195. return;
  79196. }
  79197. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  79198. if (!meshInfo) {
  79199. return;
  79200. }
  79201. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79202. return;
  79203. }
  79204. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  79205. var lerpValue = axisValue * 0.5 + 0.5;
  79206. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  79207. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  79208. };
  79209. /**
  79210. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79211. * @param scene scene in which to add meshes
  79212. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79213. */
  79214. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  79215. var _this = this;
  79216. if (forceDefault === void 0) { forceDefault = false; }
  79217. var path;
  79218. var filename;
  79219. // Checking if GLB loader is present
  79220. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  79221. // Determine the device specific folder based on the ID suffix
  79222. var device = 'default';
  79223. if (this.id && !forceDefault) {
  79224. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  79225. device = ((match && match[0]) || device);
  79226. }
  79227. // Hand
  79228. if (this.hand === 'left') {
  79229. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  79230. }
  79231. else { // Right is the default if no hand is specified
  79232. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  79233. }
  79234. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  79235. }
  79236. else {
  79237. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  79238. path = BABYLON.GenericController.MODEL_BASE_URL;
  79239. filename = BABYLON.GenericController.MODEL_FILENAME;
  79240. }
  79241. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  79242. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  79243. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  79244. if (!_this._loadedMeshInfo) {
  79245. return;
  79246. }
  79247. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  79248. _this.attachToMesh(_this._defaultModel);
  79249. if (meshLoaded) {
  79250. meshLoaded(_this._defaultModel);
  79251. }
  79252. }, null, function (scene, message) {
  79253. BABYLON.Tools.Log(message);
  79254. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  79255. if (!forceDefault) {
  79256. _this.initControllerMesh(scene, meshLoaded, true);
  79257. }
  79258. });
  79259. };
  79260. /**
  79261. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  79262. * can be transformed by button presses and axes values, based on this._mapping.
  79263. *
  79264. * @param scene scene in which the meshes exist
  79265. * @param meshes list of meshes that make up the controller model to process
  79266. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  79267. */
  79268. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  79269. var loadedMeshInfo = null;
  79270. // Create a new mesh to contain the glTF hierarchy
  79271. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  79272. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  79273. var childMesh = null;
  79274. for (var i = 0; i < meshes.length; i++) {
  79275. var mesh = meshes[i];
  79276. if (!mesh.parent) {
  79277. // Exclude controller meshes from picking results
  79278. mesh.isPickable = false;
  79279. // Handle root node, attach to the new parentMesh
  79280. childMesh = mesh;
  79281. break;
  79282. }
  79283. }
  79284. if (childMesh) {
  79285. childMesh.setParent(parentMesh);
  79286. // Create our mesh info. Note that this method will always return non-null.
  79287. loadedMeshInfo = this.createMeshInfo(parentMesh);
  79288. }
  79289. else {
  79290. BABYLON.Tools.Warn('Could not find root node in model file.');
  79291. }
  79292. return loadedMeshInfo;
  79293. };
  79294. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  79295. var loadedMeshInfo = new LoadedMeshInfo();
  79296. var i;
  79297. loadedMeshInfo.rootNode = rootNode;
  79298. // Reset the caches
  79299. loadedMeshInfo.buttonMeshes = {};
  79300. loadedMeshInfo.axisMeshes = {};
  79301. // Button Meshes
  79302. for (i = 0; i < this._mapping.buttons.length; i++) {
  79303. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  79304. if (!buttonMeshName) {
  79305. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  79306. continue;
  79307. }
  79308. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  79309. if (!buttonMesh) {
  79310. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  79311. continue;
  79312. }
  79313. var buttonMeshInfo = {
  79314. index: i,
  79315. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  79316. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  79317. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  79318. };
  79319. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  79320. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  79321. }
  79322. else {
  79323. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  79324. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  79325. '(VALUE: ' + !!buttonMeshInfo.value +
  79326. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  79327. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  79328. ')');
  79329. }
  79330. }
  79331. // Axis Meshes
  79332. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  79333. var axisMeshName = this._mapping.axisMeshNames[i];
  79334. if (!axisMeshName) {
  79335. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  79336. continue;
  79337. }
  79338. var axisMesh = getChildByName(rootNode, axisMeshName);
  79339. if (!axisMesh) {
  79340. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  79341. continue;
  79342. }
  79343. var axisMeshInfo = {
  79344. index: i,
  79345. value: getImmediateChildByName(axisMesh, 'VALUE'),
  79346. min: getImmediateChildByName(axisMesh, 'MIN'),
  79347. max: getImmediateChildByName(axisMesh, 'MAX')
  79348. };
  79349. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  79350. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  79351. }
  79352. else {
  79353. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  79354. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  79355. '(VALUE: ' + !!axisMeshInfo.value +
  79356. ', MIN: ' + !!axisMeshInfo.min +
  79357. ', MAX:' + !!axisMeshInfo.max +
  79358. ')');
  79359. }
  79360. }
  79361. // Pointing Ray
  79362. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  79363. if (!loadedMeshInfo.pointingPoseNode) {
  79364. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  79365. }
  79366. else {
  79367. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  79368. }
  79369. return loadedMeshInfo;
  79370. // Look through all children recursively. This will return null if no mesh exists with the given name.
  79371. function getChildByName(node, name) {
  79372. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  79373. }
  79374. // Look through only immediate children. This will return null if no mesh exists with the given name.
  79375. function getImmediateChildByName(node, name) {
  79376. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  79377. }
  79378. };
  79379. /**
  79380. * Gets the ray of the controller in the direction the controller is pointing
  79381. * @param length the length the resulting ray should be
  79382. * @returns a ray in the direction the controller is pointing
  79383. */
  79384. WindowsMotionController.prototype.getForwardRay = function (length) {
  79385. if (length === void 0) { length = 100; }
  79386. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  79387. return _super.prototype.getForwardRay.call(this, length);
  79388. }
  79389. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  79390. var origin = m.getTranslation();
  79391. var forward = new BABYLON.Vector3(0, 0, -1);
  79392. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79393. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79394. return new BABYLON.Ray(origin, direction, length);
  79395. };
  79396. /**
  79397. * Disposes of the controller
  79398. */
  79399. WindowsMotionController.prototype.dispose = function () {
  79400. _super.prototype.dispose.call(this);
  79401. this.onTrackpadChangedObservable.clear();
  79402. };
  79403. /**
  79404. * The base url used to load the left and right controller models
  79405. */
  79406. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  79407. /**
  79408. * The name of the left controller model file
  79409. */
  79410. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  79411. /**
  79412. * The name of the right controller model file
  79413. */
  79414. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  79415. /**
  79416. * The controller name prefix for this controller type
  79417. */
  79418. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  79419. /**
  79420. * The controller id pattern for this controller type
  79421. */
  79422. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  79423. return WindowsMotionController;
  79424. }(BABYLON.WebVRController));
  79425. BABYLON.WindowsMotionController = WindowsMotionController;
  79426. })(BABYLON || (BABYLON = {}));
  79427. //# sourceMappingURL=babylon.windowsMotionController.js.map
  79428. var BABYLON;
  79429. (function (BABYLON) {
  79430. /**
  79431. * Gear VR Controller
  79432. */
  79433. var GearVRController = /** @class */ (function (_super) {
  79434. __extends(GearVRController, _super);
  79435. /**
  79436. * Creates a new GearVRController from a gamepad
  79437. * @param vrGamepad the gamepad that the controller should be created from
  79438. */
  79439. function GearVRController(vrGamepad) {
  79440. var _this = _super.call(this, vrGamepad) || this;
  79441. _this._buttonIndexToObservableNameMap = [
  79442. 'onTrackpadChangedObservable',
  79443. 'onTriggerStateChangedObservable' // Trigger
  79444. ];
  79445. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  79446. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  79447. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  79448. _this._disableTrackPosition(_this._calculatedPosition);
  79449. return _this;
  79450. }
  79451. /**
  79452. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79453. * @param scene scene in which to add meshes
  79454. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79455. */
  79456. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79457. var _this = this;
  79458. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  79459. // Offset the controller so it will rotate around the users wrist
  79460. var mesh = new BABYLON.Mesh("", scene);
  79461. newMeshes[1].parent = mesh;
  79462. newMeshes[1].position.z = -0.15;
  79463. _this._defaultModel = mesh;
  79464. _this.attachToMesh(_this._defaultModel);
  79465. if (meshLoaded) {
  79466. meshLoaded(_this._defaultModel);
  79467. }
  79468. });
  79469. };
  79470. /**
  79471. * Called once for each button that changed state since the last frame
  79472. * @param buttonIdx Which button index changed
  79473. * @param state New state of the button
  79474. * @param changes Which properties on the state changed since last frame
  79475. */
  79476. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79477. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  79478. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  79479. // Only emit events for buttons that we know how to map from index to observable
  79480. var observable = this[observableName];
  79481. if (observable) {
  79482. observable.notifyObservers(state);
  79483. }
  79484. }
  79485. };
  79486. /**
  79487. * Base Url for the controller model.
  79488. */
  79489. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79490. /**
  79491. * File name for the controller model.
  79492. */
  79493. GearVRController.MODEL_FILENAME = 'generic.babylon';
  79494. /**
  79495. * Gamepad Id prefix used to identify this controller.
  79496. */
  79497. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  79498. return GearVRController;
  79499. }(BABYLON.WebVRController));
  79500. BABYLON.GearVRController = GearVRController;
  79501. })(BABYLON || (BABYLON = {}));
  79502. //# sourceMappingURL=babylon.gearVRController.js.map
  79503. var BABYLON;
  79504. (function (BABYLON) {
  79505. /**
  79506. * Google Daydream controller
  79507. */
  79508. var DaydreamController = /** @class */ (function (_super) {
  79509. __extends(DaydreamController, _super);
  79510. /**
  79511. * Creates a new DaydreamController from a gamepad
  79512. * @param vrGamepad the gamepad that the controller should be created from
  79513. */
  79514. function DaydreamController(vrGamepad) {
  79515. var _this = _super.call(this, vrGamepad) || this;
  79516. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  79517. return _this;
  79518. }
  79519. /**
  79520. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79521. * @param scene scene in which to add meshes
  79522. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79523. */
  79524. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79525. var _this = this;
  79526. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  79527. _this._defaultModel = newMeshes[1];
  79528. _this.attachToMesh(_this._defaultModel);
  79529. if (meshLoaded) {
  79530. meshLoaded(_this._defaultModel);
  79531. }
  79532. });
  79533. };
  79534. /**
  79535. * Called once for each button that changed state since the last frame
  79536. * @param buttonIdx Which button index changed
  79537. * @param state New state of the button
  79538. * @param changes Which properties on the state changed since last frame
  79539. */
  79540. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79541. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79542. if (buttonIdx === 0) {
  79543. var observable = this.onTriggerStateChangedObservable;
  79544. if (observable) {
  79545. observable.notifyObservers(state);
  79546. }
  79547. }
  79548. else {
  79549. // If the app or home buttons are ever made available
  79550. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79551. }
  79552. };
  79553. /**
  79554. * Base Url for the controller model.
  79555. */
  79556. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79557. /**
  79558. * File name for the controller model.
  79559. */
  79560. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79561. /**
  79562. * Gamepad Id prefix used to identify Daydream Controller.
  79563. */
  79564. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79565. return DaydreamController;
  79566. }(BABYLON.WebVRController));
  79567. BABYLON.DaydreamController = DaydreamController;
  79568. })(BABYLON || (BABYLON = {}));
  79569. //# sourceMappingURL=babylon.daydreamController.js.map
  79570. var BABYLON;
  79571. (function (BABYLON) {
  79572. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79573. get: function () {
  79574. if (!this._gamepadManager) {
  79575. this._gamepadManager = new BABYLON.GamepadManager(this);
  79576. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79577. if (!component) {
  79578. component = new GamepadSystemSceneComponent(this);
  79579. this._addComponent(component);
  79580. }
  79581. }
  79582. return this._gamepadManager;
  79583. },
  79584. enumerable: true,
  79585. configurable: true
  79586. });
  79587. /**
  79588. * Adds a gamepad to the free camera inputs manager
  79589. */
  79590. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79591. this.add(new BABYLON.FreeCameraGamepadInput());
  79592. return this;
  79593. };
  79594. /**
  79595. * Adds a gamepad to the arc rotate camera inputs manager
  79596. */
  79597. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79598. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79599. return this;
  79600. };
  79601. /**
  79602. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79603. */
  79604. var GamepadSystemSceneComponent = /** @class */ (function () {
  79605. /**
  79606. * Creates a new instance of the component for the given scene
  79607. * @param scene Defines the scene to register the component in
  79608. */
  79609. function GamepadSystemSceneComponent(scene) {
  79610. /**
  79611. * The component name helpfull to identify the component in the list of scene components.
  79612. */
  79613. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79614. this.scene = scene;
  79615. }
  79616. /**
  79617. * Registers the component in a given scene
  79618. */
  79619. GamepadSystemSceneComponent.prototype.register = function () {
  79620. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79621. };
  79622. /**
  79623. * Rebuilds the elements related to this component in case of
  79624. * context lost for instance.
  79625. */
  79626. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79627. // Nothing to do for gamepads
  79628. };
  79629. /**
  79630. * Disposes the component and the associated ressources
  79631. */
  79632. GamepadSystemSceneComponent.prototype.dispose = function () {
  79633. var gamepadManager = this.scene._gamepadManager;
  79634. if (gamepadManager) {
  79635. gamepadManager.dispose();
  79636. this.scene._gamepadManager = null;
  79637. }
  79638. };
  79639. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79640. var gamepadManager = this.scene._gamepadManager;
  79641. if (gamepadManager && gamepadManager._isMonitoring) {
  79642. gamepadManager._checkGamepadsStatus();
  79643. }
  79644. };
  79645. return GamepadSystemSceneComponent;
  79646. }());
  79647. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79648. })(BABYLON || (BABYLON = {}));
  79649. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79650. var BABYLON;
  79651. (function (BABYLON) {
  79652. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79653. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79654. });
  79655. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79656. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79657. });
  79658. /**
  79659. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79660. * an arc rotate version arcFollowCamera are available.
  79661. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79662. */
  79663. var FollowCamera = /** @class */ (function (_super) {
  79664. __extends(FollowCamera, _super);
  79665. /**
  79666. * Instantiates the follow camera.
  79667. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79668. * @param name Define the name of the camera in the scene
  79669. * @param position Define the position of the camera
  79670. * @param scene Define the scene the camera belong to
  79671. * @param lockedTarget Define the target of the camera
  79672. */
  79673. function FollowCamera(name, position, scene, lockedTarget) {
  79674. if (lockedTarget === void 0) { lockedTarget = null; }
  79675. var _this = _super.call(this, name, position, scene) || this;
  79676. /**
  79677. * Distance the follow camera should follow an object at
  79678. */
  79679. _this.radius = 12;
  79680. /**
  79681. * Define a rotation offset between the camera and the object it follows
  79682. */
  79683. _this.rotationOffset = 0;
  79684. /**
  79685. * Define a height offset between the camera and the object it follows.
  79686. * It can help following an object from the top (like a car chaing a plane)
  79687. */
  79688. _this.heightOffset = 4;
  79689. /**
  79690. * Define how fast the camera can accelerate to follow it s target.
  79691. */
  79692. _this.cameraAcceleration = 0.05;
  79693. /**
  79694. * Define the speed limit of the camera following an object.
  79695. */
  79696. _this.maxCameraSpeed = 20;
  79697. _this.lockedTarget = lockedTarget;
  79698. return _this;
  79699. }
  79700. FollowCamera.prototype._follow = function (cameraTarget) {
  79701. if (!cameraTarget)
  79702. return;
  79703. var yRotation;
  79704. if (cameraTarget.rotationQuaternion) {
  79705. var rotMatrix = new BABYLON.Matrix();
  79706. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  79707. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  79708. }
  79709. else {
  79710. yRotation = cameraTarget.rotation.y;
  79711. }
  79712. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  79713. var targetPosition = cameraTarget.getAbsolutePosition();
  79714. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  79715. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  79716. var dx = targetX - this.position.x;
  79717. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  79718. var dz = (targetZ) - this.position.z;
  79719. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  79720. var vy = dy * this.cameraAcceleration;
  79721. var vz = dz * this.cameraAcceleration * 2;
  79722. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  79723. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79724. }
  79725. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  79726. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79727. }
  79728. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  79729. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79730. }
  79731. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  79732. this.setTarget(targetPosition);
  79733. };
  79734. /** @hidden */
  79735. FollowCamera.prototype._checkInputs = function () {
  79736. _super.prototype._checkInputs.call(this);
  79737. if (this.lockedTarget) {
  79738. this._follow(this.lockedTarget);
  79739. }
  79740. };
  79741. /**
  79742. * Gets the camera class name.
  79743. * @returns the class name
  79744. */
  79745. FollowCamera.prototype.getClassName = function () {
  79746. return "FollowCamera";
  79747. };
  79748. __decorate([
  79749. BABYLON.serialize()
  79750. ], FollowCamera.prototype, "radius", void 0);
  79751. __decorate([
  79752. BABYLON.serialize()
  79753. ], FollowCamera.prototype, "rotationOffset", void 0);
  79754. __decorate([
  79755. BABYLON.serialize()
  79756. ], FollowCamera.prototype, "heightOffset", void 0);
  79757. __decorate([
  79758. BABYLON.serialize()
  79759. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  79760. __decorate([
  79761. BABYLON.serialize()
  79762. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  79763. __decorate([
  79764. BABYLON.serializeAsMeshReference("lockedTargetId")
  79765. ], FollowCamera.prototype, "lockedTarget", void 0);
  79766. return FollowCamera;
  79767. }(BABYLON.TargetCamera));
  79768. BABYLON.FollowCamera = FollowCamera;
  79769. /**
  79770. * Arc Rotate version of the follow camera.
  79771. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  79772. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79773. */
  79774. var ArcFollowCamera = /** @class */ (function (_super) {
  79775. __extends(ArcFollowCamera, _super);
  79776. /**
  79777. * Instantiates a new ArcFollowCamera
  79778. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79779. * @param name Define the name of the camera
  79780. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  79781. * @param beta Define the rotation angle of the camera around the elevation axis
  79782. * @param radius Define the radius of the camera from its target point
  79783. * @param target Define the target of the camera
  79784. * @param scene Define the scene the camera belongs to
  79785. */
  79786. function ArcFollowCamera(name,
  79787. /** The longitudinal angle of the camera */
  79788. alpha,
  79789. /** The latitudinal angle of the camera */
  79790. beta,
  79791. /** The radius of the camera from its target */
  79792. radius,
  79793. /** Define the camera target (the messh it should follow) */
  79794. target, scene) {
  79795. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  79796. _this.alpha = alpha;
  79797. _this.beta = beta;
  79798. _this.radius = radius;
  79799. _this.target = target;
  79800. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  79801. _this._follow();
  79802. return _this;
  79803. }
  79804. ArcFollowCamera.prototype._follow = function () {
  79805. if (!this.target) {
  79806. return;
  79807. }
  79808. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  79809. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  79810. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  79811. var targetPosition = this.target.getAbsolutePosition();
  79812. this.position = targetPosition.add(this._cartesianCoordinates);
  79813. this.setTarget(targetPosition);
  79814. };
  79815. /** @hidden */
  79816. ArcFollowCamera.prototype._checkInputs = function () {
  79817. _super.prototype._checkInputs.call(this);
  79818. this._follow();
  79819. };
  79820. /**
  79821. * Returns the class name of the object.
  79822. * It is mostly used internally for serialization purposes.
  79823. */
  79824. ArcFollowCamera.prototype.getClassName = function () {
  79825. return "ArcFollowCamera";
  79826. };
  79827. return ArcFollowCamera;
  79828. }(BABYLON.TargetCamera));
  79829. BABYLON.ArcFollowCamera = ArcFollowCamera;
  79830. })(BABYLON || (BABYLON = {}));
  79831. //# sourceMappingURL=babylon.followCamera.js.map
  79832. var BABYLON;
  79833. (function (BABYLON) {
  79834. /**
  79835. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  79836. * which still works and will still be found in many Playgrounds.
  79837. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79838. */
  79839. var UniversalCamera = /** @class */ (function (_super) {
  79840. __extends(UniversalCamera, _super);
  79841. /**
  79842. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  79843. * which still works and will still be found in many Playgrounds.
  79844. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79845. * @param name Define the name of the camera in the scene
  79846. * @param position Define the start position of the camera in the scene
  79847. * @param scene Define the scene the camera belongs to
  79848. */
  79849. function UniversalCamera(name, position, scene) {
  79850. var _this = _super.call(this, name, position, scene) || this;
  79851. _this.inputs.addGamepad();
  79852. return _this;
  79853. }
  79854. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  79855. /**
  79856. * Defines the gamepad rotation sensiblity.
  79857. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79858. */
  79859. get: function () {
  79860. var gamepad = this.inputs.attached["gamepad"];
  79861. if (gamepad)
  79862. return gamepad.gamepadAngularSensibility;
  79863. return 0;
  79864. },
  79865. set: function (value) {
  79866. var gamepad = this.inputs.attached["gamepad"];
  79867. if (gamepad)
  79868. gamepad.gamepadAngularSensibility = value;
  79869. },
  79870. enumerable: true,
  79871. configurable: true
  79872. });
  79873. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  79874. /**
  79875. * Defines the gamepad move sensiblity.
  79876. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79877. */
  79878. get: function () {
  79879. var gamepad = this.inputs.attached["gamepad"];
  79880. if (gamepad)
  79881. return gamepad.gamepadMoveSensibility;
  79882. return 0;
  79883. },
  79884. set: function (value) {
  79885. var gamepad = this.inputs.attached["gamepad"];
  79886. if (gamepad)
  79887. gamepad.gamepadMoveSensibility = value;
  79888. },
  79889. enumerable: true,
  79890. configurable: true
  79891. });
  79892. /**
  79893. * Gets the current object class name.
  79894. * @return the class name
  79895. */
  79896. UniversalCamera.prototype.getClassName = function () {
  79897. return "UniversalCamera";
  79898. };
  79899. return UniversalCamera;
  79900. }(BABYLON.TouchCamera));
  79901. BABYLON.UniversalCamera = UniversalCamera;
  79902. })(BABYLON || (BABYLON = {}));
  79903. //# sourceMappingURL=babylon.universalCamera.js.map
  79904. var BABYLON;
  79905. (function (BABYLON) {
  79906. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79907. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79908. });
  79909. /**
  79910. * This represents a FPS type of camera. This is only here for back compat purpose.
  79911. * Please use the UniversalCamera instead as both are identical.
  79912. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79913. */
  79914. var GamepadCamera = /** @class */ (function (_super) {
  79915. __extends(GamepadCamera, _super);
  79916. /**
  79917. * Instantiates a new Gamepad Camera
  79918. * This represents a FPS type of camera. This is only here for back compat purpose.
  79919. * Please use the UniversalCamera instead as both are identical.
  79920. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79921. * @param name Define the name of the camera in the scene
  79922. * @param position Define the start position of the camera in the scene
  79923. * @param scene Define the scene the camera belongs to
  79924. */
  79925. function GamepadCamera(name, position, scene) {
  79926. return _super.call(this, name, position, scene) || this;
  79927. }
  79928. /**
  79929. * Gets the current object class name.
  79930. * @return the class name
  79931. */
  79932. GamepadCamera.prototype.getClassName = function () {
  79933. return "GamepadCamera";
  79934. };
  79935. return GamepadCamera;
  79936. }(BABYLON.UniversalCamera));
  79937. BABYLON.GamepadCamera = GamepadCamera;
  79938. })(BABYLON || (BABYLON = {}));
  79939. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79940. var BABYLON;
  79941. (function (BABYLON) {
  79942. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79943. function PostProcessRenderPipelineManager() {
  79944. this._renderPipelines = {};
  79945. }
  79946. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79947. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79948. };
  79949. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79950. if (unique === void 0) { unique = false; }
  79951. var renderPipeline = this._renderPipelines[renderPipelineName];
  79952. if (!renderPipeline) {
  79953. return;
  79954. }
  79955. renderPipeline._attachCameras(cameras, unique);
  79956. };
  79957. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79958. var renderPipeline = this._renderPipelines[renderPipelineName];
  79959. if (!renderPipeline) {
  79960. return;
  79961. }
  79962. renderPipeline._detachCameras(cameras);
  79963. };
  79964. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79965. var renderPipeline = this._renderPipelines[renderPipelineName];
  79966. if (!renderPipeline) {
  79967. return;
  79968. }
  79969. renderPipeline._enableEffect(renderEffectName, cameras);
  79970. };
  79971. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79972. var renderPipeline = this._renderPipelines[renderPipelineName];
  79973. if (!renderPipeline) {
  79974. return;
  79975. }
  79976. renderPipeline._disableEffect(renderEffectName, cameras);
  79977. };
  79978. PostProcessRenderPipelineManager.prototype.update = function () {
  79979. for (var renderPipelineName in this._renderPipelines) {
  79980. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79981. var pipeline = this._renderPipelines[renderPipelineName];
  79982. if (!pipeline.isSupported) {
  79983. pipeline.dispose();
  79984. delete this._renderPipelines[renderPipelineName];
  79985. }
  79986. else {
  79987. pipeline._update();
  79988. }
  79989. }
  79990. }
  79991. };
  79992. /** @hidden */
  79993. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79994. for (var renderPipelineName in this._renderPipelines) {
  79995. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79996. var pipeline = this._renderPipelines[renderPipelineName];
  79997. pipeline._rebuild();
  79998. }
  79999. }
  80000. };
  80001. PostProcessRenderPipelineManager.prototype.dispose = function () {
  80002. for (var renderPipelineName in this._renderPipelines) {
  80003. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80004. var pipeline = this._renderPipelines[renderPipelineName];
  80005. pipeline.dispose();
  80006. }
  80007. }
  80008. };
  80009. return PostProcessRenderPipelineManager;
  80010. }());
  80011. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  80012. })(BABYLON || (BABYLON = {}));
  80013. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  80014. var BABYLON;
  80015. (function (BABYLON) {
  80016. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  80017. get: function () {
  80018. if (!this._postProcessRenderPipelineManager) {
  80019. // Register the G Buffer component to the scene.
  80020. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  80021. if (!component) {
  80022. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  80023. this._addComponent(component);
  80024. }
  80025. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  80026. }
  80027. return this._postProcessRenderPipelineManager;
  80028. },
  80029. enumerable: true,
  80030. configurable: true
  80031. });
  80032. /**
  80033. * Defines the Render Pipeline scene component responsible to rendering pipelines
  80034. */
  80035. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  80036. /**
  80037. * Creates a new instance of the component for the given scene
  80038. * @param scene Defines the scene to register the component in
  80039. */
  80040. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  80041. /**
  80042. * The component name helpfull to identify the component in the list of scene components.
  80043. */
  80044. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  80045. this.scene = scene;
  80046. }
  80047. /**
  80048. * Registers the component in a given scene
  80049. */
  80050. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  80051. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  80052. };
  80053. /**
  80054. * Rebuilds the elements related to this component in case of
  80055. * context lost for instance.
  80056. */
  80057. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  80058. if (this.scene._postProcessRenderPipelineManager) {
  80059. this.scene._postProcessRenderPipelineManager._rebuild();
  80060. }
  80061. };
  80062. /**
  80063. * Disposes the component and the associated ressources
  80064. */
  80065. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  80066. if (this.scene._postProcessRenderPipelineManager) {
  80067. this.scene._postProcessRenderPipelineManager.dispose();
  80068. }
  80069. };
  80070. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80071. if (this.scene._postProcessRenderPipelineManager) {
  80072. this.scene._postProcessRenderPipelineManager.update();
  80073. }
  80074. };
  80075. return PostProcessRenderPipelineManagerSceneComponent;
  80076. }());
  80077. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  80078. })(BABYLON || (BABYLON = {}));
  80079. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  80080. var BABYLON;
  80081. (function (BABYLON) {
  80082. /**
  80083. * This represents a set of one or more post processes in Babylon.
  80084. * A post process can be used to apply a shader to a texture after it is rendered.
  80085. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  80086. */
  80087. var PostProcessRenderEffect = /** @class */ (function () {
  80088. /**
  80089. * Instantiates a post process render effect.
  80090. * A post process can be used to apply a shader to a texture after it is rendered.
  80091. * @param engine The engine the effect is tied to
  80092. * @param name The name of the effect
  80093. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  80094. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  80095. */
  80096. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  80097. this._name = name;
  80098. this._singleInstance = singleInstance || true;
  80099. this._getPostProcesses = getPostProcesses;
  80100. this._cameras = {};
  80101. this._indicesForCamera = {};
  80102. this._postProcesses = {};
  80103. }
  80104. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  80105. /**
  80106. * Checks if all the post processes in the effect are supported.
  80107. */
  80108. get: function () {
  80109. for (var index in this._postProcesses) {
  80110. if (this._postProcesses.hasOwnProperty(index)) {
  80111. var pps = this._postProcesses[index];
  80112. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  80113. if (!pps[ppIndex].isSupported) {
  80114. return false;
  80115. }
  80116. }
  80117. }
  80118. }
  80119. return true;
  80120. },
  80121. enumerable: true,
  80122. configurable: true
  80123. });
  80124. /**
  80125. * Updates the current state of the effect
  80126. * @hidden
  80127. */
  80128. PostProcessRenderEffect.prototype._update = function () {
  80129. };
  80130. /**
  80131. * Attaches the effect on cameras
  80132. * @param cameras The camera to attach to.
  80133. * @hidden
  80134. */
  80135. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  80136. var _this = this;
  80137. var cameraKey;
  80138. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80139. if (!cams) {
  80140. return;
  80141. }
  80142. for (var i = 0; i < cams.length; i++) {
  80143. var camera = cams[i];
  80144. var cameraName = camera.name;
  80145. if (this._singleInstance) {
  80146. cameraKey = 0;
  80147. }
  80148. else {
  80149. cameraKey = cameraName;
  80150. }
  80151. if (!this._postProcesses[cameraKey]) {
  80152. var postProcess = this._getPostProcesses();
  80153. if (postProcess) {
  80154. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  80155. }
  80156. }
  80157. if (!this._indicesForCamera[cameraName]) {
  80158. this._indicesForCamera[cameraName] = [];
  80159. }
  80160. this._postProcesses[cameraKey].forEach(function (postProcess) {
  80161. var index = camera.attachPostProcess(postProcess);
  80162. _this._indicesForCamera[cameraName].push(index);
  80163. });
  80164. if (!this._cameras[cameraName]) {
  80165. this._cameras[cameraName] = camera;
  80166. }
  80167. }
  80168. };
  80169. /**
  80170. * Detatches the effect on cameras
  80171. * @param cameras The camera to detatch from.
  80172. * @hidden
  80173. */
  80174. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  80175. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80176. if (!cams) {
  80177. return;
  80178. }
  80179. for (var i = 0; i < cams.length; i++) {
  80180. var camera = cams[i];
  80181. var cameraName = camera.name;
  80182. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80183. camera.detachPostProcess(postProcess);
  80184. });
  80185. if (this._cameras[cameraName]) {
  80186. //this._indicesForCamera.splice(index, 1);
  80187. this._cameras[cameraName] = null;
  80188. }
  80189. }
  80190. };
  80191. /**
  80192. * Enables the effect on given cameras
  80193. * @param cameras The camera to enable.
  80194. * @hidden
  80195. */
  80196. PostProcessRenderEffect.prototype._enable = function (cameras) {
  80197. var _this = this;
  80198. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80199. if (!cams) {
  80200. return;
  80201. }
  80202. for (var i = 0; i < cams.length; i++) {
  80203. var camera = cams[i];
  80204. var cameraName = camera.name;
  80205. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  80206. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  80207. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80208. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  80209. });
  80210. }
  80211. }
  80212. }
  80213. };
  80214. /**
  80215. * Disables the effect on the given cameras
  80216. * @param cameras The camera to disable.
  80217. * @hidden
  80218. */
  80219. PostProcessRenderEffect.prototype._disable = function (cameras) {
  80220. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80221. if (!cams) {
  80222. return;
  80223. }
  80224. for (var i = 0; i < cams.length; i++) {
  80225. var camera = cams[i];
  80226. var cameraName = camera.name;
  80227. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80228. camera.detachPostProcess(postProcess);
  80229. });
  80230. }
  80231. };
  80232. /**
  80233. * Gets a list of the post processes contained in the effect.
  80234. * @param camera The camera to get the post processes on.
  80235. * @returns The list of the post processes in the effect.
  80236. */
  80237. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  80238. if (this._singleInstance) {
  80239. return this._postProcesses[0];
  80240. }
  80241. else {
  80242. if (!camera) {
  80243. return null;
  80244. }
  80245. return this._postProcesses[camera.name];
  80246. }
  80247. };
  80248. return PostProcessRenderEffect;
  80249. }());
  80250. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  80251. })(BABYLON || (BABYLON = {}));
  80252. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  80253. var BABYLON;
  80254. (function (BABYLON) {
  80255. var PostProcessRenderPipeline = /** @class */ (function () {
  80256. function PostProcessRenderPipeline(engine, name) {
  80257. this.engine = engine;
  80258. this._name = name;
  80259. this._renderEffects = {};
  80260. this._renderEffectsForIsolatedPass = new Array();
  80261. this._cameras = [];
  80262. }
  80263. PostProcessRenderPipeline.prototype.getClassName = function () {
  80264. return "PostProcessRenderPipeline";
  80265. };
  80266. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  80267. get: function () {
  80268. for (var renderEffectName in this._renderEffects) {
  80269. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80270. if (!this._renderEffects[renderEffectName].isSupported) {
  80271. return false;
  80272. }
  80273. }
  80274. }
  80275. return true;
  80276. },
  80277. enumerable: true,
  80278. configurable: true
  80279. });
  80280. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  80281. this._renderEffects[renderEffect._name] = renderEffect;
  80282. };
  80283. // private
  80284. /** @hidden */
  80285. PostProcessRenderPipeline.prototype._rebuild = function () {
  80286. };
  80287. /** @hidden */
  80288. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  80289. var renderEffects = this._renderEffects[renderEffectName];
  80290. if (!renderEffects) {
  80291. return;
  80292. }
  80293. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80294. };
  80295. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  80296. var renderEffects = this._renderEffects[renderEffectName];
  80297. if (!renderEffects) {
  80298. return;
  80299. }
  80300. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80301. };
  80302. /** @hidden */
  80303. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  80304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80305. if (!cams) {
  80306. return;
  80307. }
  80308. var indicesToDelete = [];
  80309. var i;
  80310. for (i = 0; i < cams.length; i++) {
  80311. var camera = cams[i];
  80312. var cameraName = camera.name;
  80313. if (this._cameras.indexOf(camera) === -1) {
  80314. this._cameras[cameraName] = camera;
  80315. }
  80316. else if (unique) {
  80317. indicesToDelete.push(i);
  80318. }
  80319. }
  80320. for (i = 0; i < indicesToDelete.length; i++) {
  80321. cameras.splice(indicesToDelete[i], 1);
  80322. }
  80323. for (var renderEffectName in this._renderEffects) {
  80324. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80325. this._renderEffects[renderEffectName]._attachCameras(cams);
  80326. }
  80327. }
  80328. };
  80329. /** @hidden */
  80330. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  80331. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80332. if (!cams) {
  80333. return;
  80334. }
  80335. for (var renderEffectName in this._renderEffects) {
  80336. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80337. this._renderEffects[renderEffectName]._detachCameras(cams);
  80338. }
  80339. }
  80340. for (var i = 0; i < cams.length; i++) {
  80341. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  80342. }
  80343. };
  80344. /** @hidden */
  80345. PostProcessRenderPipeline.prototype._update = function () {
  80346. for (var renderEffectName in this._renderEffects) {
  80347. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80348. this._renderEffects[renderEffectName]._update();
  80349. }
  80350. }
  80351. for (var i = 0; i < this._cameras.length; i++) {
  80352. var cameraName = this._cameras[i].name;
  80353. if (this._renderEffectsForIsolatedPass[cameraName]) {
  80354. this._renderEffectsForIsolatedPass[cameraName]._update();
  80355. }
  80356. }
  80357. };
  80358. /** @hidden */
  80359. PostProcessRenderPipeline.prototype._reset = function () {
  80360. this._renderEffects = {};
  80361. this._renderEffectsForIsolatedPass = new Array();
  80362. };
  80363. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  80364. // 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)
  80365. var effectKeys = Object.keys(this._renderEffects);
  80366. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  80367. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  80368. if (postProcesses) {
  80369. postProcesses[0].samples = sampleCount;
  80370. return true;
  80371. }
  80372. }
  80373. return false;
  80374. };
  80375. PostProcessRenderPipeline.prototype.dispose = function () {
  80376. // Must be implemented by children
  80377. };
  80378. __decorate([
  80379. BABYLON.serialize()
  80380. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  80381. return PostProcessRenderPipeline;
  80382. }());
  80383. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  80384. })(BABYLON || (BABYLON = {}));
  80385. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  80386. var BABYLON;
  80387. (function (BABYLON) {
  80388. /**
  80389. * This represents a depth renderer in Babylon.
  80390. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  80391. */
  80392. var DepthRenderer = /** @class */ (function () {
  80393. /**
  80394. * Instantiates a depth renderer
  80395. * @param scene The scene the renderer belongs to
  80396. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  80397. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  80398. */
  80399. function DepthRenderer(scene, type, camera) {
  80400. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  80401. if (camera === void 0) { camera = null; }
  80402. var _this = this;
  80403. /**
  80404. * Specifiess that the depth renderer will only be used within
  80405. * the camera it is created for.
  80406. * This can help forcing its rendering during the camera processing.
  80407. */
  80408. this.useOnlyInActiveCamera = false;
  80409. this._scene = scene;
  80410. // Register the G Buffer component to the scene.
  80411. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  80412. if (!component) {
  80413. component = new BABYLON.DepthRendererSceneComponent(scene);
  80414. scene._addComponent(component);
  80415. }
  80416. this._camera = camera;
  80417. var engine = scene.getEngine();
  80418. // Render target
  80419. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  80420. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80421. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80422. this._depthMap.refreshRate = 1;
  80423. this._depthMap.renderParticles = false;
  80424. this._depthMap.renderList = null;
  80425. // Camera to get depth map from to support multiple concurrent cameras
  80426. this._depthMap.activeCamera = this._camera;
  80427. this._depthMap.ignoreCameraViewport = true;
  80428. this._depthMap.useCameraPostProcesses = false;
  80429. // set default depth value to 1.0 (far away)
  80430. this._depthMap.onClearObservable.add(function (engine) {
  80431. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  80432. });
  80433. // Custom render function
  80434. var renderSubMesh = function (subMesh) {
  80435. var mesh = subMesh.getRenderingMesh();
  80436. var scene = _this._scene;
  80437. var engine = scene.getEngine();
  80438. var material = subMesh.getMaterial();
  80439. if (!material) {
  80440. return;
  80441. }
  80442. // Culling and reverse (right handed system)
  80443. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80444. // Managing instances
  80445. var batch = mesh._getInstancesRenderList(subMesh._id);
  80446. if (batch.mustReturn) {
  80447. return;
  80448. }
  80449. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80450. var camera = _this._camera || scene.activeCamera;
  80451. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  80452. engine.enableEffect(_this._effect);
  80453. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80454. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80455. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  80456. // Alpha test
  80457. if (material && material.needAlphaTesting()) {
  80458. var alphaTexture = material.getAlphaTestTexture();
  80459. if (alphaTexture) {
  80460. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80461. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80462. }
  80463. }
  80464. // Bones
  80465. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80466. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80467. }
  80468. // Draw
  80469. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80470. }
  80471. };
  80472. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80473. var index;
  80474. if (depthOnlySubMeshes.length) {
  80475. engine.setColorWrite(false);
  80476. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80477. renderSubMesh(depthOnlySubMeshes.data[index]);
  80478. }
  80479. engine.setColorWrite(true);
  80480. }
  80481. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80482. renderSubMesh(opaqueSubMeshes.data[index]);
  80483. }
  80484. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80485. renderSubMesh(alphaTestSubMeshes.data[index]);
  80486. }
  80487. };
  80488. }
  80489. /**
  80490. * Creates the depth rendering effect and checks if the effect is ready.
  80491. * @param subMesh The submesh to be used to render the depth map of
  80492. * @param useInstances If multiple world instances should be used
  80493. * @returns if the depth renderer is ready to render the depth map
  80494. */
  80495. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  80496. var material = subMesh.getMaterial();
  80497. if (material.disableDepthWrite) {
  80498. return false;
  80499. }
  80500. var defines = [];
  80501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80502. var mesh = subMesh.getMesh();
  80503. // Alpha test
  80504. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  80505. defines.push("#define ALPHATEST");
  80506. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80507. attribs.push(BABYLON.VertexBuffer.UVKind);
  80508. defines.push("#define UV1");
  80509. }
  80510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80511. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80512. defines.push("#define UV2");
  80513. }
  80514. }
  80515. // Bones
  80516. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80517. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80518. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80519. if (mesh.numBoneInfluencers > 4) {
  80520. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80521. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80522. }
  80523. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80524. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80525. }
  80526. else {
  80527. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80528. }
  80529. // Instances
  80530. if (useInstances) {
  80531. defines.push("#define INSTANCES");
  80532. attribs.push("world0");
  80533. attribs.push("world1");
  80534. attribs.push("world2");
  80535. attribs.push("world3");
  80536. }
  80537. // Get correct effect
  80538. var join = defines.join("\n");
  80539. if (this._cachedDefines !== join) {
  80540. this._cachedDefines = join;
  80541. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80542. }
  80543. return this._effect.isReady();
  80544. };
  80545. /**
  80546. * Gets the texture which the depth map will be written to.
  80547. * @returns The depth map texture
  80548. */
  80549. DepthRenderer.prototype.getDepthMap = function () {
  80550. return this._depthMap;
  80551. };
  80552. /**
  80553. * Disposes of the depth renderer.
  80554. */
  80555. DepthRenderer.prototype.dispose = function () {
  80556. this._depthMap.dispose();
  80557. };
  80558. return DepthRenderer;
  80559. }());
  80560. BABYLON.DepthRenderer = DepthRenderer;
  80561. })(BABYLON || (BABYLON = {}));
  80562. //# sourceMappingURL=babylon.depthRenderer.js.map
  80563. var BABYLON;
  80564. (function (BABYLON) {
  80565. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80566. camera = camera || this.activeCamera;
  80567. if (!camera) {
  80568. throw "No camera available to enable depth renderer";
  80569. }
  80570. if (!this._depthRenderer) {
  80571. this._depthRenderer = {};
  80572. }
  80573. if (!this._depthRenderer[camera.id]) {
  80574. var textureType = 0;
  80575. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80576. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80577. }
  80578. else if (this.getEngine().getCaps().textureFloatRender) {
  80579. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80580. }
  80581. else {
  80582. throw "Depth renderer does not support int texture type";
  80583. }
  80584. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80585. }
  80586. return this._depthRenderer[camera.id];
  80587. };
  80588. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80589. camera = camera || this.activeCamera;
  80590. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80591. return;
  80592. }
  80593. this._depthRenderer[camera.id].dispose();
  80594. delete this._depthRenderer[camera.id];
  80595. };
  80596. /**
  80597. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80598. * in several rendering techniques.
  80599. */
  80600. var DepthRendererSceneComponent = /** @class */ (function () {
  80601. /**
  80602. * Creates a new instance of the component for the given scene
  80603. * @param scene Defines the scene to register the component in
  80604. */
  80605. function DepthRendererSceneComponent(scene) {
  80606. /**
  80607. * The component name helpfull to identify the component in the list of scene components.
  80608. */
  80609. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80610. this.scene = scene;
  80611. }
  80612. /**
  80613. * Registers the component in a given scene
  80614. */
  80615. DepthRendererSceneComponent.prototype.register = function () {
  80616. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80617. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80618. };
  80619. /**
  80620. * Rebuilds the elements related to this component in case of
  80621. * context lost for instance.
  80622. */
  80623. DepthRendererSceneComponent.prototype.rebuild = function () {
  80624. // Nothing to do for this component
  80625. };
  80626. /**
  80627. * Disposes the component and the associated ressources
  80628. */
  80629. DepthRendererSceneComponent.prototype.dispose = function () {
  80630. for (var key in this.scene._depthRenderer) {
  80631. this.scene._depthRenderer[key].dispose();
  80632. }
  80633. };
  80634. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80635. if (this.scene._depthRenderer) {
  80636. for (var key in this.scene._depthRenderer) {
  80637. var depthRenderer = this.scene._depthRenderer[key];
  80638. if (!depthRenderer.useOnlyInActiveCamera) {
  80639. renderTargets.push(depthRenderer.getDepthMap());
  80640. }
  80641. }
  80642. }
  80643. };
  80644. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80645. if (this.scene._depthRenderer) {
  80646. for (var key in this.scene._depthRenderer) {
  80647. var depthRenderer = this.scene._depthRenderer[key];
  80648. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80649. renderTargets.push(depthRenderer.getDepthMap());
  80650. }
  80651. }
  80652. }
  80653. };
  80654. return DepthRendererSceneComponent;
  80655. }());
  80656. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80657. })(BABYLON || (BABYLON = {}));
  80658. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80659. var BABYLON;
  80660. (function (BABYLON) {
  80661. /**
  80662. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80663. */
  80664. var GeometryBufferRenderer = /** @class */ (function () {
  80665. /**
  80666. * Creates a new G Buffer for the scene
  80667. * @param scene The scene the buffer belongs to
  80668. * @param ratio How big is the buffer related to the main canvas.
  80669. */
  80670. function GeometryBufferRenderer(scene, ratio) {
  80671. if (ratio === void 0) { ratio = 1; }
  80672. this._enablePosition = false;
  80673. this._scene = scene;
  80674. this._ratio = ratio;
  80675. // Register the G Buffer component to the scene.
  80676. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  80677. if (!component) {
  80678. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  80679. scene._addComponent(component);
  80680. }
  80681. // Render target
  80682. this._createRenderTargets();
  80683. }
  80684. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  80685. /**
  80686. * Set the render list (meshes to be rendered) used in the G buffer.
  80687. */
  80688. set: function (meshes) {
  80689. this._multiRenderTarget.renderList = meshes;
  80690. },
  80691. enumerable: true,
  80692. configurable: true
  80693. });
  80694. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  80695. /**
  80696. * Gets wether or not G buffer are supported by the running hardware.
  80697. * This requires draw buffer supports
  80698. */
  80699. get: function () {
  80700. return this._multiRenderTarget.isSupported;
  80701. },
  80702. enumerable: true,
  80703. configurable: true
  80704. });
  80705. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  80706. /**
  80707. * Gets wether or not position are enabled for the G buffer.
  80708. */
  80709. get: function () {
  80710. return this._enablePosition;
  80711. },
  80712. /**
  80713. * Sets wether or not position are enabled for the G buffer.
  80714. */
  80715. set: function (enable) {
  80716. this._enablePosition = enable;
  80717. this.dispose();
  80718. this._createRenderTargets();
  80719. },
  80720. enumerable: true,
  80721. configurable: true
  80722. });
  80723. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  80724. /**
  80725. * Gets the scene associated with the buffer.
  80726. */
  80727. get: function () {
  80728. return this._scene;
  80729. },
  80730. enumerable: true,
  80731. configurable: true
  80732. });
  80733. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  80734. /**
  80735. * Gets the ratio used by the buffer during its creation.
  80736. * How big is the buffer related to the main canvas.
  80737. */
  80738. get: function () {
  80739. return this._ratio;
  80740. },
  80741. enumerable: true,
  80742. configurable: true
  80743. });
  80744. /**
  80745. * Checks wether everything is ready to render a submesh to the G buffer.
  80746. * @param subMesh the submesh to check readiness for
  80747. * @param useInstances is the mesh drawn using instance or not
  80748. * @returns true if ready otherwise false
  80749. */
  80750. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  80751. var material = subMesh.getMaterial();
  80752. if (material && material.disableDepthWrite) {
  80753. return false;
  80754. }
  80755. var defines = [];
  80756. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80757. var mesh = subMesh.getMesh();
  80758. // Alpha test
  80759. if (material && material.needAlphaTesting()) {
  80760. defines.push("#define ALPHATEST");
  80761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80762. attribs.push(BABYLON.VertexBuffer.UVKind);
  80763. defines.push("#define UV1");
  80764. }
  80765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80766. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80767. defines.push("#define UV2");
  80768. }
  80769. }
  80770. // Buffers
  80771. if (this._enablePosition) {
  80772. defines.push("#define POSITION");
  80773. }
  80774. // Bones
  80775. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80778. if (mesh.numBoneInfluencers > 4) {
  80779. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80780. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80781. }
  80782. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80783. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80784. }
  80785. else {
  80786. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80787. }
  80788. // Instances
  80789. if (useInstances) {
  80790. defines.push("#define INSTANCES");
  80791. attribs.push("world0");
  80792. attribs.push("world1");
  80793. attribs.push("world2");
  80794. attribs.push("world3");
  80795. }
  80796. // Get correct effect
  80797. var join = defines.join("\n");
  80798. if (this._cachedDefines !== join) {
  80799. this._cachedDefines = join;
  80800. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  80801. }
  80802. return this._effect.isReady();
  80803. };
  80804. /**
  80805. * Gets the current underlying G Buffer.
  80806. * @returns the buffer
  80807. */
  80808. GeometryBufferRenderer.prototype.getGBuffer = function () {
  80809. return this._multiRenderTarget;
  80810. };
  80811. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  80812. /**
  80813. * Gets the number of samples used to render the buffer (anti aliasing).
  80814. */
  80815. get: function () {
  80816. return this._multiRenderTarget.samples;
  80817. },
  80818. /**
  80819. * Sets the number of samples used to render the buffer (anti aliasing).
  80820. */
  80821. set: function (value) {
  80822. this._multiRenderTarget.samples = value;
  80823. },
  80824. enumerable: true,
  80825. configurable: true
  80826. });
  80827. /**
  80828. * Disposes the renderer and frees up associated resources.
  80829. */
  80830. GeometryBufferRenderer.prototype.dispose = function () {
  80831. this.getGBuffer().dispose();
  80832. };
  80833. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  80834. var _this = this;
  80835. var engine = this._scene.getEngine();
  80836. var count = this._enablePosition ? 3 : 2;
  80837. 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 });
  80838. if (!this.isSupported) {
  80839. return;
  80840. }
  80841. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80842. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80843. this._multiRenderTarget.refreshRate = 1;
  80844. this._multiRenderTarget.renderParticles = false;
  80845. this._multiRenderTarget.renderList = null;
  80846. // set default depth value to 1.0 (far away)
  80847. this._multiRenderTarget.onClearObservable.add(function (engine) {
  80848. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  80849. });
  80850. // Custom render function
  80851. var renderSubMesh = function (subMesh) {
  80852. var mesh = subMesh.getRenderingMesh();
  80853. var scene = _this._scene;
  80854. var engine = scene.getEngine();
  80855. var material = subMesh.getMaterial();
  80856. if (!material) {
  80857. return;
  80858. }
  80859. // Culling
  80860. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80861. // Managing instances
  80862. var batch = mesh._getInstancesRenderList(subMesh._id);
  80863. if (batch.mustReturn) {
  80864. return;
  80865. }
  80866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80867. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  80868. engine.enableEffect(_this._effect);
  80869. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80870. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80871. _this._effect.setMatrix("view", scene.getViewMatrix());
  80872. // Alpha test
  80873. if (material && material.needAlphaTesting()) {
  80874. var alphaTexture = material.getAlphaTestTexture();
  80875. if (alphaTexture) {
  80876. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80877. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80878. }
  80879. }
  80880. // Bones
  80881. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80882. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80883. }
  80884. // Draw
  80885. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80886. }
  80887. };
  80888. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80889. var index;
  80890. if (depthOnlySubMeshes.length) {
  80891. engine.setColorWrite(false);
  80892. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80893. renderSubMesh(depthOnlySubMeshes.data[index]);
  80894. }
  80895. engine.setColorWrite(true);
  80896. }
  80897. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80898. renderSubMesh(opaqueSubMeshes.data[index]);
  80899. }
  80900. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80901. renderSubMesh(alphaTestSubMeshes.data[index]);
  80902. }
  80903. };
  80904. };
  80905. return GeometryBufferRenderer;
  80906. }());
  80907. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80908. })(BABYLON || (BABYLON = {}));
  80909. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80910. var BABYLON;
  80911. (function (BABYLON) {
  80912. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80913. get: function () {
  80914. this._geometryBufferRenderer;
  80915. },
  80916. set: function (value) {
  80917. if (value && value.isSupported) {
  80918. this._geometryBufferRenderer = value;
  80919. }
  80920. ;
  80921. },
  80922. enumerable: true,
  80923. configurable: true
  80924. });
  80925. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80926. if (ratio === void 0) { ratio = 1; }
  80927. if (this._geometryBufferRenderer) {
  80928. return this._geometryBufferRenderer;
  80929. }
  80930. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80931. if (!this._geometryBufferRenderer.isSupported) {
  80932. this._geometryBufferRenderer = null;
  80933. }
  80934. return this._geometryBufferRenderer;
  80935. };
  80936. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80937. if (!this._geometryBufferRenderer) {
  80938. return;
  80939. }
  80940. this._geometryBufferRenderer.dispose();
  80941. this._geometryBufferRenderer = null;
  80942. };
  80943. /**
  80944. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80945. * in several rendering techniques.
  80946. */
  80947. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80948. /**
  80949. * Creates a new instance of the component for the given scene
  80950. * @param scene Defines the scene to register the component in
  80951. */
  80952. function GeometryBufferRendererSceneComponent(scene) {
  80953. /**
  80954. * The component name helpful to identify the component in the list of scene components.
  80955. */
  80956. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80957. this.scene = scene;
  80958. }
  80959. /**
  80960. * Registers the component in a given scene
  80961. */
  80962. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80963. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80964. };
  80965. /**
  80966. * Rebuilds the elements related to this component in case of
  80967. * context lost for instance.
  80968. */
  80969. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80970. // Nothing to do for this component
  80971. };
  80972. /**
  80973. * Disposes the component and the associated ressources
  80974. */
  80975. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80976. // Nothing to do for this component
  80977. };
  80978. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80979. if (this.scene._geometryBufferRenderer) {
  80980. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80981. }
  80982. };
  80983. return GeometryBufferRendererSceneComponent;
  80984. }());
  80985. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80986. })(BABYLON || (BABYLON = {}));
  80987. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80988. var BABYLON;
  80989. (function (BABYLON) {
  80990. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80991. __extends(SSAORenderingPipeline, _super);
  80992. /**
  80993. * @constructor
  80994. * @param {string} name - The rendering pipeline name
  80995. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80996. * @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 }
  80997. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80998. */
  80999. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  81000. var _this = _super.call(this, scene.getEngine(), name) || this;
  81001. // Members
  81002. /**
  81003. * The PassPostProcess id in the pipeline that contains the original scene color
  81004. */
  81005. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81006. /**
  81007. * The SSAO PostProcess id in the pipeline
  81008. */
  81009. _this.SSAORenderEffect = "SSAORenderEffect";
  81010. /**
  81011. * The horizontal blur PostProcess id in the pipeline
  81012. */
  81013. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81014. /**
  81015. * The vertical blur PostProcess id in the pipeline
  81016. */
  81017. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81018. /**
  81019. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81020. */
  81021. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81022. /**
  81023. * The output strength of the SSAO post-process. Default value is 1.0.
  81024. */
  81025. _this.totalStrength = 1.0;
  81026. /**
  81027. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  81028. */
  81029. _this.radius = 0.0001;
  81030. /**
  81031. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  81032. * Must not be equal to fallOff and superior to fallOff.
  81033. * Default value is 0.975
  81034. */
  81035. _this.area = 0.0075;
  81036. /**
  81037. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  81038. * Must not be equal to area and inferior to area.
  81039. * Default value is 0.0
  81040. */
  81041. _this.fallOff = 0.000001;
  81042. /**
  81043. * The base color of the SSAO post-process
  81044. * The final result is "base + ssao" between [0, 1]
  81045. */
  81046. _this.base = 0.5;
  81047. _this._firstUpdate = true;
  81048. _this._scene = scene;
  81049. // Set up assets
  81050. _this._createRandomTexture();
  81051. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81052. var ssaoRatio = ratio.ssaoRatio || ratio;
  81053. var combineRatio = ratio.combineRatio || ratio;
  81054. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81055. _this._createSSAOPostProcess(ssaoRatio);
  81056. _this._createBlurPostProcess(ssaoRatio);
  81057. _this._createSSAOCombinePostProcess(combineRatio);
  81058. // Set up pipeline
  81059. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81064. // Finish
  81065. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81066. if (cameras)
  81067. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81068. return _this;
  81069. }
  81070. // Public Methods
  81071. /**
  81072. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81073. */
  81074. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81075. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81076. for (var i = 0; i < this._scene.cameras.length; i++) {
  81077. var camera = this._scene.cameras[i];
  81078. this._originalColorPostProcess.dispose(camera);
  81079. this._ssaoPostProcess.dispose(camera);
  81080. this._blurHPostProcess.dispose(camera);
  81081. this._blurVPostProcess.dispose(camera);
  81082. this._ssaoCombinePostProcess.dispose(camera);
  81083. }
  81084. this._randomTexture.dispose();
  81085. if (disableDepthRender)
  81086. this._scene.disableDepthRenderer();
  81087. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81088. _super.prototype.dispose.call(this);
  81089. };
  81090. // Private Methods
  81091. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  81092. var _this = this;
  81093. var size = 16;
  81094. 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);
  81095. 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);
  81096. this._blurHPostProcess.onActivateObservable.add(function () {
  81097. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  81098. _this._blurHPostProcess.kernel = size * dw;
  81099. });
  81100. this._blurVPostProcess.onActivateObservable.add(function () {
  81101. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  81102. _this._blurVPostProcess.kernel = size * dw;
  81103. });
  81104. };
  81105. /** @hidden */
  81106. SSAORenderingPipeline.prototype._rebuild = function () {
  81107. this._firstUpdate = true;
  81108. _super.prototype._rebuild.call(this);
  81109. };
  81110. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81111. var _this = this;
  81112. var numSamples = 16;
  81113. var sampleSphere = [
  81114. 0.5381, 0.1856, -0.4319,
  81115. 0.1379, 0.2486, 0.4430,
  81116. 0.3371, 0.5679, -0.0057,
  81117. -0.6999, -0.0451, -0.0019,
  81118. 0.0689, -0.1598, -0.8547,
  81119. 0.0560, 0.0069, -0.1843,
  81120. -0.0146, 0.1402, 0.0762,
  81121. 0.0100, -0.1924, -0.0344,
  81122. -0.3577, -0.5301, -0.4358,
  81123. -0.3169, 0.1063, 0.0158,
  81124. 0.0103, -0.5869, 0.0046,
  81125. -0.0897, -0.4940, 0.3287,
  81126. 0.7119, -0.0154, -0.0918,
  81127. -0.0533, 0.0596, -0.5411,
  81128. 0.0352, -0.0631, 0.5460,
  81129. -0.4776, 0.2847, -0.0271
  81130. ];
  81131. var samplesFactor = 1.0 / numSamples;
  81132. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  81133. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81134. "area", "fallOff", "base", "range", "viewport"
  81135. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81136. this._ssaoPostProcess.onApply = function (effect) {
  81137. if (_this._firstUpdate) {
  81138. effect.setArray3("sampleSphere", sampleSphere);
  81139. effect.setFloat("samplesFactor", samplesFactor);
  81140. effect.setFloat("randTextureTiles", 4.0);
  81141. }
  81142. effect.setFloat("totalStrength", _this.totalStrength);
  81143. effect.setFloat("radius", _this.radius);
  81144. effect.setFloat("area", _this.area);
  81145. effect.setFloat("fallOff", _this.fallOff);
  81146. effect.setFloat("base", _this.base);
  81147. effect.setTexture("textureSampler", _this._depthTexture);
  81148. effect.setTexture("randomSampler", _this._randomTexture);
  81149. };
  81150. };
  81151. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81152. var _this = this;
  81153. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81154. this._ssaoCombinePostProcess.onApply = function (effect) {
  81155. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  81156. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81157. };
  81158. };
  81159. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  81160. var size = 512;
  81161. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81162. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81163. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81164. var context = this._randomTexture.getContext();
  81165. var rand = function (min, max) {
  81166. return Math.random() * (max - min) + min;
  81167. };
  81168. var randVector = BABYLON.Vector3.Zero();
  81169. for (var x = 0; x < size; x++) {
  81170. for (var y = 0; y < size; y++) {
  81171. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  81172. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  81173. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  81174. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81175. context.fillRect(x, y, 1, 1);
  81176. }
  81177. }
  81178. this._randomTexture.update(false);
  81179. };
  81180. __decorate([
  81181. BABYLON.serialize()
  81182. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  81183. __decorate([
  81184. BABYLON.serialize()
  81185. ], SSAORenderingPipeline.prototype, "radius", void 0);
  81186. __decorate([
  81187. BABYLON.serialize()
  81188. ], SSAORenderingPipeline.prototype, "area", void 0);
  81189. __decorate([
  81190. BABYLON.serialize()
  81191. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  81192. __decorate([
  81193. BABYLON.serialize()
  81194. ], SSAORenderingPipeline.prototype, "base", void 0);
  81195. return SSAORenderingPipeline;
  81196. }(BABYLON.PostProcessRenderPipeline));
  81197. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  81198. })(BABYLON || (BABYLON = {}));
  81199. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  81200. var BABYLON;
  81201. (function (BABYLON) {
  81202. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  81203. __extends(SSAO2RenderingPipeline, _super);
  81204. /**
  81205. * @constructor
  81206. * @param {string} name - The rendering pipeline name
  81207. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81208. * @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 }
  81209. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81210. */
  81211. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  81212. var _this = _super.call(this, scene.getEngine(), name) || this;
  81213. // Members
  81214. /**
  81215. * The PassPostProcess id in the pipeline that contains the original scene color
  81216. */
  81217. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81218. /**
  81219. * The SSAO PostProcess id in the pipeline
  81220. */
  81221. _this.SSAORenderEffect = "SSAORenderEffect";
  81222. /**
  81223. * The horizontal blur PostProcess id in the pipeline
  81224. */
  81225. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81226. /**
  81227. * The vertical blur PostProcess id in the pipeline
  81228. */
  81229. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81230. /**
  81231. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81232. */
  81233. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81234. /**
  81235. * The output strength of the SSAO post-process. Default value is 1.0.
  81236. */
  81237. _this.totalStrength = 1.0;
  81238. /**
  81239. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  81240. */
  81241. _this.maxZ = 100.0;
  81242. /**
  81243. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  81244. */
  81245. _this.minZAspect = 0.2;
  81246. _this._samples = 8;
  81247. _this._textureSamples = 1;
  81248. /**
  81249. * Are we using bilateral blur ?
  81250. */
  81251. _this._expensiveBlur = true;
  81252. /**
  81253. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  81254. */
  81255. _this.radius = 2.0;
  81256. /**
  81257. * The base color of the SSAO post-process
  81258. * The final result is "base + ssao" between [0, 1]
  81259. */
  81260. _this.base = 0;
  81261. _this._firstUpdate = true;
  81262. _this._bits = new Uint32Array(1);
  81263. _this._scene = scene;
  81264. _this._ratio = ratio;
  81265. if (!_this.isSupported) {
  81266. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  81267. return _this;
  81268. }
  81269. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  81270. var blurRatio = _this._ratio.blurRatio || ratio;
  81271. // Set up assets
  81272. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  81273. _this._createRandomTexture();
  81274. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  81275. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  81276. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81277. _this._originalColorPostProcess.samples = _this.textureSamples;
  81278. _this._createSSAOPostProcess(1.0);
  81279. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  81280. _this._createSSAOCombinePostProcess(blurRatio);
  81281. // Set up pipeline
  81282. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81283. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81284. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81285. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81286. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81287. // Finish
  81288. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81289. if (cameras)
  81290. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81291. return _this;
  81292. }
  81293. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  81294. get: function () {
  81295. return this._samples;
  81296. },
  81297. /**
  81298. * Number of samples used for the SSAO calculations. Default value is 8
  81299. */
  81300. set: function (n) {
  81301. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  81302. this._samples = n;
  81303. this._sampleSphere = this._generateHemisphere();
  81304. this._firstUpdate = true;
  81305. },
  81306. enumerable: true,
  81307. configurable: true
  81308. });
  81309. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  81310. get: function () {
  81311. return this._textureSamples;
  81312. },
  81313. /**
  81314. * Number of samples to use for antialiasing
  81315. */
  81316. set: function (n) {
  81317. this._textureSamples = n;
  81318. this._originalColorPostProcess.samples = n;
  81319. this._blurHPostProcess.samples = n;
  81320. this._blurVPostProcess.samples = n;
  81321. this._ssaoPostProcess.samples = n;
  81322. this._ssaoCombinePostProcess.samples = n;
  81323. },
  81324. enumerable: true,
  81325. configurable: true
  81326. });
  81327. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  81328. get: function () {
  81329. return this._expensiveBlur;
  81330. },
  81331. set: function (b) {
  81332. 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"]);
  81333. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  81334. this._expensiveBlur = b;
  81335. this._firstUpdate = true;
  81336. },
  81337. enumerable: true,
  81338. configurable: true
  81339. });
  81340. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  81341. /**
  81342. * Support test.
  81343. */
  81344. get: function () {
  81345. var engine = BABYLON.Engine.LastCreatedEngine;
  81346. if (!engine) {
  81347. return false;
  81348. }
  81349. return engine.getCaps().drawBuffersExtension;
  81350. },
  81351. enumerable: true,
  81352. configurable: true
  81353. });
  81354. // Public Methods
  81355. /**
  81356. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81357. */
  81358. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  81359. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  81360. for (var i = 0; i < this._scene.cameras.length; i++) {
  81361. var camera = this._scene.cameras[i];
  81362. this._originalColorPostProcess.dispose(camera);
  81363. this._ssaoPostProcess.dispose(camera);
  81364. this._blurHPostProcess.dispose(camera);
  81365. this._blurVPostProcess.dispose(camera);
  81366. this._ssaoCombinePostProcess.dispose(camera);
  81367. }
  81368. this._randomTexture.dispose();
  81369. if (disableGeometryBufferRenderer)
  81370. this._scene.disableGeometryBufferRenderer();
  81371. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81372. _super.prototype.dispose.call(this);
  81373. };
  81374. // Private Methods
  81375. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  81376. var _this = this;
  81377. this._samplerOffsets = [];
  81378. var expensive = this.expensiveBlur;
  81379. for (var i = -8; i < 8; i++) {
  81380. this._samplerOffsets.push(i * 2 + 0.5);
  81381. }
  81382. 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");
  81383. this._blurHPostProcess.onApply = function (effect) {
  81384. if (!_this._scene.activeCamera) {
  81385. return;
  81386. }
  81387. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  81388. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81389. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81390. effect.setFloat("radius", _this.radius);
  81391. effect.setTexture("depthSampler", _this._depthTexture);
  81392. if (_this._firstUpdate) {
  81393. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81394. }
  81395. };
  81396. 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");
  81397. this._blurVPostProcess.onApply = function (effect) {
  81398. if (!_this._scene.activeCamera) {
  81399. return;
  81400. }
  81401. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  81402. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81403. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81404. effect.setFloat("radius", _this.radius);
  81405. effect.setTexture("depthSampler", _this._depthTexture);
  81406. if (_this._firstUpdate) {
  81407. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81408. _this._firstUpdate = false;
  81409. }
  81410. };
  81411. this._blurHPostProcess.samples = this.textureSamples;
  81412. this._blurVPostProcess.samples = this.textureSamples;
  81413. };
  81414. /** @hidden */
  81415. SSAO2RenderingPipeline.prototype._rebuild = function () {
  81416. this._firstUpdate = true;
  81417. _super.prototype._rebuild.call(this);
  81418. };
  81419. //Van der Corput radical inverse
  81420. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  81421. this._bits[0] = i;
  81422. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  81423. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  81424. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  81425. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  81426. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  81427. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  81428. };
  81429. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  81430. return [i / n, this._radicalInverse_VdC(i)];
  81431. };
  81432. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  81433. var phi = v * 2.0 * Math.PI;
  81434. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  81435. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  81436. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  81437. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  81438. };
  81439. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  81440. var numSamples = this.samples;
  81441. var result = [];
  81442. var vector;
  81443. var i = 0;
  81444. while (i < numSamples) {
  81445. if (numSamples < 16) {
  81446. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  81447. }
  81448. else {
  81449. var rand = this._hammersley(i, numSamples);
  81450. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  81451. }
  81452. result.push(vector.x, vector.y, vector.z);
  81453. i++;
  81454. }
  81455. return result;
  81456. };
  81457. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81458. var _this = this;
  81459. var numSamples = this.samples;
  81460. this._sampleSphere = this._generateHemisphere();
  81461. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  81462. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81463. "base", "range", "projection", "near", "far", "texelSize",
  81464. "xViewport", "yViewport", "maxZ", "minZAspect"
  81465. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81466. this._ssaoPostProcess.onApply = function (effect) {
  81467. if (_this._firstUpdate) {
  81468. effect.setArray3("sampleSphere", _this._sampleSphere);
  81469. effect.setFloat("randTextureTiles", 32.0);
  81470. }
  81471. if (!_this._scene.activeCamera) {
  81472. return;
  81473. }
  81474. effect.setFloat("samplesFactor", 1 / _this.samples);
  81475. effect.setFloat("totalStrength", _this.totalStrength);
  81476. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  81477. effect.setFloat("radius", _this.radius);
  81478. effect.setFloat("maxZ", _this.maxZ);
  81479. effect.setFloat("minZAspect", _this.minZAspect);
  81480. effect.setFloat("base", _this.base);
  81481. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81482. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81483. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  81484. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  81485. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  81486. effect.setTexture("textureSampler", _this._depthTexture);
  81487. effect.setTexture("normalSampler", _this._normalTexture);
  81488. effect.setTexture("randomSampler", _this._randomTexture);
  81489. };
  81490. this._ssaoPostProcess.samples = this.textureSamples;
  81491. };
  81492. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81493. var _this = this;
  81494. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81495. this._ssaoCombinePostProcess.onApply = function (effect) {
  81496. var viewport = _this._scene.activeCamera.viewport;
  81497. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  81498. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81499. };
  81500. this._ssaoCombinePostProcess.samples = this.textureSamples;
  81501. };
  81502. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  81503. var size = 128;
  81504. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81505. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81506. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81507. var context = this._randomTexture.getContext();
  81508. var rand = function (min, max) {
  81509. return Math.random() * (max - min) + min;
  81510. };
  81511. var randVector = BABYLON.Vector3.Zero();
  81512. for (var x = 0; x < size; x++) {
  81513. for (var y = 0; y < size; y++) {
  81514. randVector.x = rand(0.0, 1.0);
  81515. randVector.y = rand(0.0, 1.0);
  81516. randVector.z = 0.0;
  81517. randVector.normalize();
  81518. randVector.scaleInPlace(255);
  81519. randVector.x = Math.floor(randVector.x);
  81520. randVector.y = Math.floor(randVector.y);
  81521. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81522. context.fillRect(x, y, 1, 1);
  81523. }
  81524. }
  81525. this._randomTexture.update(false);
  81526. };
  81527. /**
  81528. * Serialize the rendering pipeline (Used when exporting)
  81529. * @returns the serialized object
  81530. */
  81531. SSAO2RenderingPipeline.prototype.serialize = function () {
  81532. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81533. serializationObject.customType = "SSAO2RenderingPipeline";
  81534. return serializationObject;
  81535. };
  81536. /**
  81537. * Parse the serialized pipeline
  81538. * @param source Source pipeline.
  81539. * @param scene The scene to load the pipeline to.
  81540. * @param rootUrl The URL of the serialized pipeline.
  81541. * @returns An instantiated pipeline from the serialized object.
  81542. */
  81543. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81544. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81545. };
  81546. __decorate([
  81547. BABYLON.serialize()
  81548. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81549. __decorate([
  81550. BABYLON.serialize()
  81551. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81552. __decorate([
  81553. BABYLON.serialize()
  81554. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81555. __decorate([
  81556. BABYLON.serialize("samples")
  81557. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81558. __decorate([
  81559. BABYLON.serialize("textureSamples")
  81560. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81561. __decorate([
  81562. BABYLON.serialize()
  81563. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81564. __decorate([
  81565. BABYLON.serialize("expensiveBlur")
  81566. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81567. __decorate([
  81568. BABYLON.serialize()
  81569. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81570. __decorate([
  81571. BABYLON.serialize()
  81572. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81573. return SSAO2RenderingPipeline;
  81574. }(BABYLON.PostProcessRenderPipeline));
  81575. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81576. })(BABYLON || (BABYLON = {}));
  81577. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81578. // BABYLON.JS Chromatic Aberration GLSL Shader
  81579. // Author: Olivier Guyot
  81580. // Separates very slightly R, G and B colors on the edges of the screen
  81581. // Inspired by Francois Tarlier & Martins Upitis
  81582. var BABYLON;
  81583. (function (BABYLON) {
  81584. var LensRenderingPipeline = /** @class */ (function (_super) {
  81585. __extends(LensRenderingPipeline, _super);
  81586. /**
  81587. * @constructor
  81588. *
  81589. * Effect parameters are as follow:
  81590. * {
  81591. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81592. * edge_blur: number; // from 0 to x (1 for realism)
  81593. * distortion: number; // from 0 to x (1 for realism)
  81594. * grain_amount: number; // from 0 to 1
  81595. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81596. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81597. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81598. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81599. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81600. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81601. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81602. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81603. * }
  81604. * Note: if an effect parameter is unset, effect is disabled
  81605. *
  81606. * @param {string} name - The rendering pipeline name
  81607. * @param {object} parameters - An object containing all parameters (see above)
  81608. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81609. * @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)
  81610. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81611. */
  81612. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81613. if (ratio === void 0) { ratio = 1.0; }
  81614. var _this = _super.call(this, scene.getEngine(), name) || this;
  81615. // Lens effects can be of the following:
  81616. // - chromatic aberration (slight shift of RGB colors)
  81617. // - blur on the edge of the lens
  81618. // - lens distortion
  81619. // - depth-of-field blur & highlights enhancing
  81620. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81621. // - grain effect (noise or custom texture)
  81622. // Two additional texture samplers are needed:
  81623. // - depth map (for depth-of-field)
  81624. // - grain texture
  81625. /**
  81626. * The chromatic aberration PostProcess id in the pipeline
  81627. */
  81628. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81629. /**
  81630. * The highlights enhancing PostProcess id in the pipeline
  81631. */
  81632. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81633. /**
  81634. * The depth-of-field PostProcess id in the pipeline
  81635. */
  81636. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81637. _this._scene = scene;
  81638. // Fetch texture samplers
  81639. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81640. if (parameters.grain_texture) {
  81641. _this._grainTexture = parameters.grain_texture;
  81642. }
  81643. else {
  81644. _this._createGrainTexture();
  81645. }
  81646. // save parameters
  81647. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81648. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81649. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81650. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81651. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81652. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81653. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81654. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81655. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81656. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81657. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81658. // Create effects
  81659. _this._createChromaticAberrationPostProcess(ratio);
  81660. _this._createHighlightsPostProcess(ratio);
  81661. _this._createDepthOfFieldPostProcess(ratio / 4);
  81662. // Set up pipeline
  81663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  81664. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  81665. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  81666. if (_this._highlightsGain === -1) {
  81667. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  81668. }
  81669. // Finish
  81670. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81671. if (cameras) {
  81672. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81673. }
  81674. return _this;
  81675. }
  81676. // public methods (self explanatory)
  81677. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  81678. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  81679. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  81680. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  81681. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  81682. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  81683. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  81684. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  81685. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  81686. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  81687. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  81688. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  81689. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  81690. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  81691. };
  81692. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  81693. this._highlightsPostProcess.updateEffect();
  81694. };
  81695. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  81696. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  81697. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  81698. this._highlightsGain = amount;
  81699. };
  81700. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  81701. if (this._highlightsGain === -1) {
  81702. this._highlightsGain = 1.0;
  81703. }
  81704. this._highlightsThreshold = amount;
  81705. };
  81706. LensRenderingPipeline.prototype.disableHighlights = function () {
  81707. this._highlightsGain = -1;
  81708. };
  81709. /**
  81710. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  81711. */
  81712. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81713. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81714. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81715. this._chromaticAberrationPostProcess = null;
  81716. this._highlightsPostProcess = null;
  81717. this._depthOfFieldPostProcess = null;
  81718. this._grainTexture.dispose();
  81719. if (disableDepthRender)
  81720. this._scene.disableDepthRenderer();
  81721. };
  81722. // colors shifting and distortion
  81723. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  81724. var _this = this;
  81725. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  81726. [], // samplers
  81727. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81728. this._chromaticAberrationPostProcess.onApply = function (effect) {
  81729. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  81730. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81731. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81732. effect.setFloat('radialIntensity', 1);
  81733. effect.setFloat2('direction', 17, 17);
  81734. effect.setFloat2('centerPosition', 0.5, 0.5);
  81735. };
  81736. };
  81737. // highlights enhancing
  81738. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  81739. var _this = this;
  81740. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  81741. [], // samplers
  81742. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  81743. this._highlightsPostProcess.onApply = function (effect) {
  81744. effect.setFloat('gain', _this._highlightsGain);
  81745. effect.setFloat('threshold', _this._highlightsThreshold);
  81746. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  81747. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81748. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81749. };
  81750. };
  81751. // colors shifting and distortion
  81752. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  81753. var _this = this;
  81754. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  81755. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  81756. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  81757. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81758. this._depthOfFieldPostProcess.onApply = function (effect) {
  81759. effect.setTexture("depthSampler", _this._depthTexture);
  81760. effect.setTexture("grainSampler", _this._grainTexture);
  81761. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  81762. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  81763. effect.setFloat('grain_amount', _this._grainAmount);
  81764. effect.setBool('blur_noise', _this._blurNoise);
  81765. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81766. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81767. effect.setFloat('distortion', _this._distortion);
  81768. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  81769. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  81770. effect.setFloat('aperture', _this._dofAperture);
  81771. effect.setFloat('darken', _this._dofDarken);
  81772. effect.setFloat('edge_blur', _this._edgeBlur);
  81773. effect.setBool('highlights', (_this._highlightsGain !== -1));
  81774. if (_this._scene.activeCamera) {
  81775. effect.setFloat('near', _this._scene.activeCamera.minZ);
  81776. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  81777. }
  81778. };
  81779. };
  81780. // creates a black and white random noise texture, 512x512
  81781. LensRenderingPipeline.prototype._createGrainTexture = function () {
  81782. var size = 512;
  81783. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81784. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81785. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81786. var context = this._grainTexture.getContext();
  81787. var rand = function (min, max) {
  81788. return Math.random() * (max - min) + min;
  81789. };
  81790. var value;
  81791. for (var x = 0; x < size; x++) {
  81792. for (var y = 0; y < size; y++) {
  81793. value = Math.floor(rand(0.42, 0.58) * 255);
  81794. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  81795. context.fillRect(x, y, 1, 1);
  81796. }
  81797. }
  81798. this._grainTexture.update(false);
  81799. };
  81800. return LensRenderingPipeline;
  81801. }(BABYLON.PostProcessRenderPipeline));
  81802. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  81803. })(BABYLON || (BABYLON = {}));
  81804. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  81805. var BABYLON;
  81806. (function (BABYLON) {
  81807. var StandardRenderingPipeline = /** @class */ (function (_super) {
  81808. __extends(StandardRenderingPipeline, _super);
  81809. /**
  81810. * @constructor
  81811. * @param {string} name - The rendering pipeline name
  81812. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81813. * @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)
  81814. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  81815. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81816. */
  81817. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  81818. if (originalPostProcess === void 0) { originalPostProcess = null; }
  81819. var _this = _super.call(this, scene.getEngine(), name) || this;
  81820. /**
  81821. * Post-process used to down scale an image x4
  81822. */
  81823. _this.downSampleX4PostProcess = null;
  81824. /**
  81825. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  81826. */
  81827. _this.brightPassPostProcess = null;
  81828. /**
  81829. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  81830. */
  81831. _this.blurHPostProcesses = [];
  81832. /**
  81833. * Post-process array storing all the vertical blur post-processes used by the pipeline
  81834. */
  81835. _this.blurVPostProcesses = [];
  81836. /**
  81837. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  81838. */
  81839. _this.textureAdderPostProcess = null;
  81840. /**
  81841. * Post-process used to create volumetric lighting effect
  81842. */
  81843. _this.volumetricLightPostProcess = null;
  81844. /**
  81845. * Post-process used to smooth the previous volumetric light post-process on the X axis
  81846. */
  81847. _this.volumetricLightSmoothXPostProcess = null;
  81848. /**
  81849. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  81850. */
  81851. _this.volumetricLightSmoothYPostProcess = null;
  81852. /**
  81853. * Post-process used to merge the volumetric light effect and the real scene color
  81854. */
  81855. _this.volumetricLightMergePostProces = null;
  81856. /**
  81857. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  81858. */
  81859. _this.volumetricLightFinalPostProcess = null;
  81860. /**
  81861. * Base post-process used to calculate the average luminance of the final image for HDR
  81862. */
  81863. _this.luminancePostProcess = null;
  81864. /**
  81865. * Post-processes used to create down sample post-processes in order to get
  81866. * the average luminance of the final image for HDR
  81867. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  81868. */
  81869. _this.luminanceDownSamplePostProcesses = [];
  81870. /**
  81871. * Post-process used to create a HDR effect (light adaptation)
  81872. */
  81873. _this.hdrPostProcess = null;
  81874. /**
  81875. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  81876. */
  81877. _this.textureAdderFinalPostProcess = null;
  81878. /**
  81879. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  81880. */
  81881. _this.lensFlareFinalPostProcess = null;
  81882. /**
  81883. * Post-process used to merge the final HDR post-process and the real scene color
  81884. */
  81885. _this.hdrFinalPostProcess = null;
  81886. /**
  81887. * Post-process used to create a lens flare effect
  81888. */
  81889. _this.lensFlarePostProcess = null;
  81890. /**
  81891. * Post-process that merges the result of the lens flare post-process and the real scene color
  81892. */
  81893. _this.lensFlareComposePostProcess = null;
  81894. /**
  81895. * Post-process used to create a motion blur effect
  81896. */
  81897. _this.motionBlurPostProcess = null;
  81898. /**
  81899. * Post-process used to create a depth of field effect
  81900. */
  81901. _this.depthOfFieldPostProcess = null;
  81902. /**
  81903. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81904. */
  81905. _this.fxaaPostProcess = null;
  81906. // Values
  81907. /**
  81908. * Represents the brightness threshold in order to configure the illuminated surfaces
  81909. */
  81910. _this.brightThreshold = 1.0;
  81911. /**
  81912. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81913. */
  81914. _this.blurWidth = 512.0;
  81915. /**
  81916. * Sets if the blur for highlighted surfaces must be only horizontal
  81917. */
  81918. _this.horizontalBlur = false;
  81919. /**
  81920. * Sets the overall exposure used by the pipeline
  81921. */
  81922. _this.exposure = 1.0;
  81923. /**
  81924. * Texture used typically to simulate "dirty" on camera lens
  81925. */
  81926. _this.lensTexture = null;
  81927. /**
  81928. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81929. */
  81930. _this.volumetricLightCoefficient = 0.2;
  81931. /**
  81932. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81933. */
  81934. _this.volumetricLightPower = 4.0;
  81935. /**
  81936. * Used the set the blur intensity to smooth the volumetric lights
  81937. */
  81938. _this.volumetricLightBlurScale = 64.0;
  81939. /**
  81940. * Light (spot or directional) used to generate the volumetric lights rays
  81941. * The source light must have a shadow generate so the pipeline can get its
  81942. * depth map
  81943. */
  81944. _this.sourceLight = null;
  81945. /**
  81946. * For eye adaptation, represents the minimum luminance the eye can see
  81947. */
  81948. _this.hdrMinimumLuminance = 1.0;
  81949. /**
  81950. * For eye adaptation, represents the decrease luminance speed
  81951. */
  81952. _this.hdrDecreaseRate = 0.5;
  81953. /**
  81954. * For eye adaptation, represents the increase luminance speed
  81955. */
  81956. _this.hdrIncreaseRate = 0.5;
  81957. /**
  81958. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81959. */
  81960. _this.lensColorTexture = null;
  81961. /**
  81962. * The overall strengh for the lens flare effect
  81963. */
  81964. _this.lensFlareStrength = 20.0;
  81965. /**
  81966. * Dispersion coefficient for lens flare ghosts
  81967. */
  81968. _this.lensFlareGhostDispersal = 1.4;
  81969. /**
  81970. * Main lens flare halo width
  81971. */
  81972. _this.lensFlareHaloWidth = 0.7;
  81973. /**
  81974. * Based on the lens distortion effect, defines how much the lens flare result
  81975. * is distorted
  81976. */
  81977. _this.lensFlareDistortionStrength = 16.0;
  81978. /**
  81979. * Lens star texture must be used to simulate rays on the flares and is available
  81980. * in the documentation
  81981. */
  81982. _this.lensStarTexture = null;
  81983. /**
  81984. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81985. * flare effect by taking account of the dirt texture
  81986. */
  81987. _this.lensFlareDirtTexture = null;
  81988. /**
  81989. * Represents the focal length for the depth of field effect
  81990. */
  81991. _this.depthOfFieldDistance = 10.0;
  81992. /**
  81993. * Represents the blur intensity for the blurred part of the depth of field effect
  81994. */
  81995. _this.depthOfFieldBlurWidth = 64.0;
  81996. /**
  81997. * For motion blur, defines how much the image is blurred by the movement
  81998. */
  81999. _this.motionStrength = 1.0;
  82000. /**
  82001. * List of animations for the pipeline (IAnimatable implementation)
  82002. */
  82003. _this.animations = [];
  82004. _this._currentDepthOfFieldSource = null;
  82005. _this._hdrCurrentLuminance = 1.0;
  82006. // Getters and setters
  82007. _this._bloomEnabled = false;
  82008. _this._depthOfFieldEnabled = false;
  82009. _this._vlsEnabled = false;
  82010. _this._lensFlareEnabled = false;
  82011. _this._hdrEnabled = false;
  82012. _this._motionBlurEnabled = false;
  82013. _this._fxaaEnabled = false;
  82014. _this._motionBlurSamples = 64.0;
  82015. _this._volumetricLightStepsCount = 50.0;
  82016. _this._samples = 1;
  82017. _this._cameras = cameras || [];
  82018. // Initialize
  82019. _this._scene = scene;
  82020. _this._basePostProcess = originalPostProcess;
  82021. _this._ratio = ratio;
  82022. // Misc
  82023. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82024. // Finish
  82025. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82026. _this._buildPipeline();
  82027. return _this;
  82028. }
  82029. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  82030. /**
  82031. * Specifies if the bloom pipeline is enabled
  82032. */
  82033. get: function () {
  82034. return this._bloomEnabled;
  82035. },
  82036. set: function (enabled) {
  82037. if (this._bloomEnabled === enabled) {
  82038. return;
  82039. }
  82040. this._bloomEnabled = enabled;
  82041. this._buildPipeline();
  82042. },
  82043. enumerable: true,
  82044. configurable: true
  82045. });
  82046. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  82047. /**
  82048. * Specifies if the depth of field pipeline is enabed
  82049. */
  82050. get: function () {
  82051. return this._depthOfFieldEnabled;
  82052. },
  82053. set: function (enabled) {
  82054. if (this._depthOfFieldEnabled === enabled) {
  82055. return;
  82056. }
  82057. this._depthOfFieldEnabled = enabled;
  82058. this._buildPipeline();
  82059. },
  82060. enumerable: true,
  82061. configurable: true
  82062. });
  82063. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  82064. /**
  82065. * Specifies if the lens flare pipeline is enabed
  82066. */
  82067. get: function () {
  82068. return this._lensFlareEnabled;
  82069. },
  82070. set: function (enabled) {
  82071. if (this._lensFlareEnabled === enabled) {
  82072. return;
  82073. }
  82074. this._lensFlareEnabled = enabled;
  82075. this._buildPipeline();
  82076. },
  82077. enumerable: true,
  82078. configurable: true
  82079. });
  82080. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  82081. /**
  82082. * Specifies if the HDR pipeline is enabled
  82083. */
  82084. get: function () {
  82085. return this._hdrEnabled;
  82086. },
  82087. set: function (enabled) {
  82088. if (this._hdrEnabled === enabled) {
  82089. return;
  82090. }
  82091. this._hdrEnabled = enabled;
  82092. this._buildPipeline();
  82093. },
  82094. enumerable: true,
  82095. configurable: true
  82096. });
  82097. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  82098. /**
  82099. * Specifies if the volumetric lights scattering effect is enabled
  82100. */
  82101. get: function () {
  82102. return this._vlsEnabled;
  82103. },
  82104. set: function (enabled) {
  82105. if (this._vlsEnabled === enabled) {
  82106. return;
  82107. }
  82108. if (enabled) {
  82109. var geometry = this._scene.enableGeometryBufferRenderer();
  82110. if (!geometry) {
  82111. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  82112. return;
  82113. }
  82114. }
  82115. this._vlsEnabled = enabled;
  82116. this._buildPipeline();
  82117. },
  82118. enumerable: true,
  82119. configurable: true
  82120. });
  82121. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  82122. /**
  82123. * Specifies if the motion blur effect is enabled
  82124. */
  82125. get: function () {
  82126. return this._motionBlurEnabled;
  82127. },
  82128. set: function (enabled) {
  82129. if (this._motionBlurEnabled === enabled) {
  82130. return;
  82131. }
  82132. this._motionBlurEnabled = enabled;
  82133. this._buildPipeline();
  82134. },
  82135. enumerable: true,
  82136. configurable: true
  82137. });
  82138. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  82139. /**
  82140. * Specifies if anti-aliasing is enabled
  82141. */
  82142. get: function () {
  82143. return this._fxaaEnabled;
  82144. },
  82145. set: function (enabled) {
  82146. if (this._fxaaEnabled === enabled) {
  82147. return;
  82148. }
  82149. this._fxaaEnabled = enabled;
  82150. this._buildPipeline();
  82151. },
  82152. enumerable: true,
  82153. configurable: true
  82154. });
  82155. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  82156. /**
  82157. * Specifies the number of steps used to calculate the volumetric lights
  82158. * Typically in interval [50, 200]
  82159. */
  82160. get: function () {
  82161. return this._volumetricLightStepsCount;
  82162. },
  82163. set: function (count) {
  82164. if (this.volumetricLightPostProcess) {
  82165. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  82166. }
  82167. this._volumetricLightStepsCount = count;
  82168. },
  82169. enumerable: true,
  82170. configurable: true
  82171. });
  82172. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  82173. /**
  82174. * Specifies the number of samples used for the motion blur effect
  82175. * Typically in interval [16, 64]
  82176. */
  82177. get: function () {
  82178. return this._motionBlurSamples;
  82179. },
  82180. set: function (samples) {
  82181. if (this.motionBlurPostProcess) {
  82182. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  82183. }
  82184. this._motionBlurSamples = samples;
  82185. },
  82186. enumerable: true,
  82187. configurable: true
  82188. });
  82189. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  82190. /**
  82191. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  82192. */
  82193. get: function () {
  82194. return this._samples;
  82195. },
  82196. set: function (sampleCount) {
  82197. if (this._samples === sampleCount) {
  82198. return;
  82199. }
  82200. this._samples = sampleCount;
  82201. this._buildPipeline();
  82202. },
  82203. enumerable: true,
  82204. configurable: true
  82205. });
  82206. StandardRenderingPipeline.prototype._buildPipeline = function () {
  82207. var _this = this;
  82208. var ratio = this._ratio;
  82209. var scene = this._scene;
  82210. this._disposePostProcesses();
  82211. this._reset();
  82212. // Create pass post-process
  82213. if (!this._basePostProcess) {
  82214. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  82215. this.originalPostProcess.onApply = function (effect) {
  82216. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  82217. };
  82218. }
  82219. else {
  82220. this.originalPostProcess = this._basePostProcess;
  82221. }
  82222. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  82223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  82224. }
  82225. this._currentDepthOfFieldSource = this.originalPostProcess;
  82226. if (this._bloomEnabled) {
  82227. // Create down sample X4 post-process
  82228. this._createDownSampleX4PostProcess(scene, ratio / 2);
  82229. // Create bright pass post-process
  82230. this._createBrightPassPostProcess(scene, ratio / 2);
  82231. // Create gaussian blur post-processes (down sampling blurs)
  82232. this._createBlurPostProcesses(scene, ratio / 4, 1);
  82233. // Create texture adder post-process
  82234. this._createTextureAdderPostProcess(scene, ratio);
  82235. // Create depth-of-field source post-process
  82236. 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);
  82237. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  82238. }
  82239. if (this._vlsEnabled) {
  82240. // Create volumetric light
  82241. this._createVolumetricLightPostProcess(scene, ratio);
  82242. // Create volumetric light final post-process
  82243. 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);
  82244. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  82245. }
  82246. if (this._lensFlareEnabled) {
  82247. // Create lens flare post-process
  82248. this._createLensFlarePostProcess(scene, ratio);
  82249. // Create depth-of-field source post-process post lens-flare and disable it now
  82250. 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);
  82251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  82252. }
  82253. if (this._hdrEnabled) {
  82254. // Create luminance
  82255. this._createLuminancePostProcesses(scene, this._floatTextureType);
  82256. // Create HDR
  82257. this._createHdrPostProcess(scene, ratio);
  82258. // Create depth-of-field source post-process post hdr and disable it now
  82259. 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);
  82260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  82261. }
  82262. if (this._depthOfFieldEnabled) {
  82263. // Create gaussian blur used by depth-of-field
  82264. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  82265. // Create depth-of-field post-process
  82266. this._createDepthOfFieldPostProcess(scene, ratio);
  82267. }
  82268. if (this._motionBlurEnabled) {
  82269. // Create motion blur post-process
  82270. this._createMotionBlurPostProcess(scene, ratio);
  82271. }
  82272. if (this._fxaaEnabled) {
  82273. // Create fxaa post-process
  82274. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  82276. }
  82277. if (this._cameras !== null) {
  82278. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82279. }
  82280. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  82281. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82282. }
  82283. };
  82284. // Down Sample X4 Post-Processs
  82285. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  82286. var _this = this;
  82287. var downSampleX4Offsets = new Array(32);
  82288. 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);
  82289. this.downSampleX4PostProcess.onApply = function (effect) {
  82290. var id = 0;
  82291. var width = _this.downSampleX4PostProcess.width;
  82292. var height = _this.downSampleX4PostProcess.height;
  82293. for (var i = -2; i < 2; i++) {
  82294. for (var j = -2; j < 2; j++) {
  82295. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  82296. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  82297. id += 2;
  82298. }
  82299. }
  82300. effect.setArray2("dsOffsets", downSampleX4Offsets);
  82301. };
  82302. // Add to pipeline
  82303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  82304. };
  82305. // Brightpass Post-Process
  82306. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  82307. var _this = this;
  82308. var brightOffsets = new Array(8);
  82309. 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);
  82310. this.brightPassPostProcess.onApply = function (effect) {
  82311. var sU = (1.0 / _this.brightPassPostProcess.width);
  82312. var sV = (1.0 / _this.brightPassPostProcess.height);
  82313. brightOffsets[0] = -0.5 * sU;
  82314. brightOffsets[1] = 0.5 * sV;
  82315. brightOffsets[2] = 0.5 * sU;
  82316. brightOffsets[3] = 0.5 * sV;
  82317. brightOffsets[4] = -0.5 * sU;
  82318. brightOffsets[5] = -0.5 * sV;
  82319. brightOffsets[6] = 0.5 * sU;
  82320. brightOffsets[7] = -0.5 * sV;
  82321. effect.setArray2("dsOffsets", brightOffsets);
  82322. effect.setFloat("brightThreshold", _this.brightThreshold);
  82323. };
  82324. // Add to pipeline
  82325. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  82326. };
  82327. // Create blur H&V post-processes
  82328. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  82329. var _this = this;
  82330. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  82331. var engine = scene.getEngine();
  82332. 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);
  82333. 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);
  82334. blurX.onActivateObservable.add(function () {
  82335. var dw = blurX.width / engine.getRenderWidth();
  82336. blurX.kernel = _this[blurWidthKey] * dw;
  82337. });
  82338. blurY.onActivateObservable.add(function () {
  82339. var dw = blurY.height / engine.getRenderHeight();
  82340. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  82341. });
  82342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  82343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  82344. this.blurHPostProcesses.push(blurX);
  82345. this.blurVPostProcesses.push(blurY);
  82346. };
  82347. // Create texture adder post-process
  82348. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  82349. var _this = this;
  82350. 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);
  82351. this.textureAdderPostProcess.onApply = function (effect) {
  82352. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  82353. effect.setTexture("lensSampler", _this.lensTexture);
  82354. effect.setFloat("exposure", _this.exposure);
  82355. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  82356. };
  82357. // Add to pipeline
  82358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  82359. };
  82360. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  82361. var _this = this;
  82362. var geometryRenderer = scene.enableGeometryBufferRenderer();
  82363. geometryRenderer.enablePosition = true;
  82364. var geometry = geometryRenderer.getGBuffer();
  82365. // Base post-process
  82366. 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));
  82367. var depthValues = BABYLON.Vector2.Zero();
  82368. this.volumetricLightPostProcess.onApply = function (effect) {
  82369. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  82370. var generator = _this.sourceLight.getShadowGenerator();
  82371. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  82372. effect.setTexture("positionSampler", geometry.textures[2]);
  82373. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  82374. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  82375. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  82376. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  82377. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  82378. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  82379. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  82380. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  82381. effect.setVector2("depthValues", depthValues);
  82382. }
  82383. };
  82384. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  82385. // Smooth
  82386. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  82387. // Merge
  82388. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  82389. this.volumetricLightMergePostProces.onApply = function (effect) {
  82390. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  82391. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  82392. };
  82393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  82394. };
  82395. // Create luminance
  82396. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  82397. var _this = this;
  82398. // Create luminance
  82399. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  82400. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  82401. var offsets = [];
  82402. this.luminancePostProcess.onApply = function (effect) {
  82403. var sU = (1.0 / _this.luminancePostProcess.width);
  82404. var sV = (1.0 / _this.luminancePostProcess.height);
  82405. offsets[0] = -0.5 * sU;
  82406. offsets[1] = 0.5 * sV;
  82407. offsets[2] = 0.5 * sU;
  82408. offsets[3] = 0.5 * sV;
  82409. offsets[4] = -0.5 * sU;
  82410. offsets[5] = -0.5 * sV;
  82411. offsets[6] = 0.5 * sU;
  82412. offsets[7] = -0.5 * sV;
  82413. effect.setArray2("lumOffsets", offsets);
  82414. };
  82415. // Add to pipeline
  82416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  82417. // Create down sample luminance
  82418. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  82419. var size = Math.pow(3, i);
  82420. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  82421. if (i === 0) {
  82422. defines += "#define FINAL_DOWN_SAMPLER";
  82423. }
  82424. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  82425. this.luminanceDownSamplePostProcesses.push(postProcess);
  82426. }
  82427. // Create callbacks and add effects
  82428. var lastLuminance = this.luminancePostProcess;
  82429. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  82430. var downSampleOffsets = new Array(18);
  82431. pp.onApply = function (effect) {
  82432. if (!lastLuminance) {
  82433. return;
  82434. }
  82435. var id = 0;
  82436. for (var x = -1; x < 2; x++) {
  82437. for (var y = -1; y < 2; y++) {
  82438. downSampleOffsets[id] = x / lastLuminance.width;
  82439. downSampleOffsets[id + 1] = y / lastLuminance.height;
  82440. id += 2;
  82441. }
  82442. }
  82443. effect.setArray2("dsOffsets", downSampleOffsets);
  82444. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  82445. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82446. lastLuminance = _this.luminancePostProcess;
  82447. }
  82448. else {
  82449. lastLuminance = pp;
  82450. }
  82451. };
  82452. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82453. pp.onAfterRender = function (effect) {
  82454. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  82455. 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);
  82456. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  82457. };
  82458. }
  82459. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  82460. });
  82461. };
  82462. // Create HDR post-process
  82463. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  82464. var _this = this;
  82465. 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);
  82466. var outputLiminance = 1;
  82467. var time = 0;
  82468. var lastTime = 0;
  82469. this.hdrPostProcess.onApply = function (effect) {
  82470. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  82471. time += scene.getEngine().getDeltaTime();
  82472. if (outputLiminance < 0) {
  82473. outputLiminance = _this._hdrCurrentLuminance;
  82474. }
  82475. else {
  82476. var dt = (lastTime - time) / 1000.0;
  82477. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  82478. outputLiminance += _this.hdrDecreaseRate * dt;
  82479. }
  82480. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  82481. outputLiminance -= _this.hdrIncreaseRate * dt;
  82482. }
  82483. else {
  82484. outputLiminance = _this._hdrCurrentLuminance;
  82485. }
  82486. }
  82487. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  82488. effect.setFloat("averageLuminance", outputLiminance);
  82489. lastTime = time;
  82490. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  82491. };
  82492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  82493. };
  82494. // Create lens flare post-process
  82495. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  82496. var _this = this;
  82497. 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);
  82498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  82499. this._createBlurPostProcesses(scene, ratio / 4, 2);
  82500. 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);
  82501. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  82502. var resolution = new BABYLON.Vector2(0, 0);
  82503. // Lens flare
  82504. this.lensFlarePostProcess.onApply = function (effect) {
  82505. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  82506. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  82507. effect.setFloat("strength", _this.lensFlareStrength);
  82508. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  82509. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  82510. // Shift
  82511. resolution.x = _this.lensFlarePostProcess.width;
  82512. resolution.y = _this.lensFlarePostProcess.height;
  82513. effect.setVector2("resolution", resolution);
  82514. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  82515. };
  82516. // Compose
  82517. 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);
  82518. 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);
  82519. this.lensFlareComposePostProcess.onApply = function (effect) {
  82520. if (!_this._scene.activeCamera) {
  82521. return;
  82522. }
  82523. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82524. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  82525. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  82526. // Lens start rotation matrix
  82527. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  82528. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  82529. 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));
  82530. camRot *= 4.0;
  82531. 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);
  82532. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  82533. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  82534. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  82535. };
  82536. };
  82537. // Create depth-of-field post-process
  82538. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82539. var _this = this;
  82540. 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);
  82541. this.depthOfFieldPostProcess.onApply = function (effect) {
  82542. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82543. effect.setTexture("depthSampler", _this._getDepthTexture());
  82544. effect.setFloat("distance", _this.depthOfFieldDistance);
  82545. };
  82546. // Add to pipeline
  82547. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82548. };
  82549. // Create motion blur post-process
  82550. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82551. var _this = this;
  82552. 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);
  82553. var motionScale = 0;
  82554. var prevViewProjection = BABYLON.Matrix.Identity();
  82555. var invViewProjection = BABYLON.Matrix.Identity();
  82556. var viewProjection = BABYLON.Matrix.Identity();
  82557. var screenSize = BABYLON.Vector2.Zero();
  82558. this.motionBlurPostProcess.onApply = function (effect) {
  82559. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82560. viewProjection.invertToRef(invViewProjection);
  82561. effect.setMatrix("inverseViewProjection", invViewProjection);
  82562. effect.setMatrix("prevViewProjection", prevViewProjection);
  82563. prevViewProjection = viewProjection;
  82564. screenSize.x = _this.motionBlurPostProcess.width;
  82565. screenSize.y = _this.motionBlurPostProcess.height;
  82566. effect.setVector2("screenSize", screenSize);
  82567. motionScale = scene.getEngine().getFps() / 60.0;
  82568. effect.setFloat("motionScale", motionScale);
  82569. effect.setFloat("motionStrength", _this.motionStrength);
  82570. effect.setTexture("depthSampler", _this._getDepthTexture());
  82571. };
  82572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82573. };
  82574. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82575. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82576. var renderer = this._scene.enableGeometryBufferRenderer();
  82577. return renderer.getGBuffer().textures[0];
  82578. }
  82579. return this._scene.enableDepthRenderer().getDepthMap();
  82580. };
  82581. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82582. for (var i = 0; i < this._cameras.length; i++) {
  82583. var camera = this._cameras[i];
  82584. if (this.originalPostProcess) {
  82585. this.originalPostProcess.dispose(camera);
  82586. }
  82587. if (this.downSampleX4PostProcess) {
  82588. this.downSampleX4PostProcess.dispose(camera);
  82589. }
  82590. if (this.brightPassPostProcess) {
  82591. this.brightPassPostProcess.dispose(camera);
  82592. }
  82593. if (this.textureAdderPostProcess) {
  82594. this.textureAdderPostProcess.dispose(camera);
  82595. }
  82596. if (this.textureAdderFinalPostProcess) {
  82597. this.textureAdderFinalPostProcess.dispose(camera);
  82598. }
  82599. if (this.volumetricLightPostProcess) {
  82600. this.volumetricLightPostProcess.dispose(camera);
  82601. }
  82602. if (this.volumetricLightSmoothXPostProcess) {
  82603. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82604. }
  82605. if (this.volumetricLightSmoothYPostProcess) {
  82606. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82607. }
  82608. if (this.volumetricLightMergePostProces) {
  82609. this.volumetricLightMergePostProces.dispose(camera);
  82610. }
  82611. if (this.volumetricLightFinalPostProcess) {
  82612. this.volumetricLightFinalPostProcess.dispose(camera);
  82613. }
  82614. if (this.lensFlarePostProcess) {
  82615. this.lensFlarePostProcess.dispose(camera);
  82616. }
  82617. if (this.lensFlareComposePostProcess) {
  82618. this.lensFlareComposePostProcess.dispose(camera);
  82619. }
  82620. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82621. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82622. }
  82623. if (this.luminancePostProcess) {
  82624. this.luminancePostProcess.dispose(camera);
  82625. }
  82626. if (this.hdrPostProcess) {
  82627. this.hdrPostProcess.dispose(camera);
  82628. }
  82629. if (this.hdrFinalPostProcess) {
  82630. this.hdrFinalPostProcess.dispose(camera);
  82631. }
  82632. if (this.depthOfFieldPostProcess) {
  82633. this.depthOfFieldPostProcess.dispose(camera);
  82634. }
  82635. if (this.motionBlurPostProcess) {
  82636. this.motionBlurPostProcess.dispose(camera);
  82637. }
  82638. if (this.fxaaPostProcess) {
  82639. this.fxaaPostProcess.dispose(camera);
  82640. }
  82641. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82642. this.blurHPostProcesses[j].dispose(camera);
  82643. }
  82644. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82645. this.blurVPostProcesses[j].dispose(camera);
  82646. }
  82647. }
  82648. this.originalPostProcess = null;
  82649. this.downSampleX4PostProcess = null;
  82650. this.brightPassPostProcess = null;
  82651. this.textureAdderPostProcess = null;
  82652. this.textureAdderFinalPostProcess = null;
  82653. this.volumetricLightPostProcess = null;
  82654. this.volumetricLightSmoothXPostProcess = null;
  82655. this.volumetricLightSmoothYPostProcess = null;
  82656. this.volumetricLightMergePostProces = null;
  82657. this.volumetricLightFinalPostProcess = null;
  82658. this.lensFlarePostProcess = null;
  82659. this.lensFlareComposePostProcess = null;
  82660. this.luminancePostProcess = null;
  82661. this.hdrPostProcess = null;
  82662. this.hdrFinalPostProcess = null;
  82663. this.depthOfFieldPostProcess = null;
  82664. this.motionBlurPostProcess = null;
  82665. this.fxaaPostProcess = null;
  82666. this.luminanceDownSamplePostProcesses = [];
  82667. this.blurHPostProcesses = [];
  82668. this.blurVPostProcesses = [];
  82669. };
  82670. /**
  82671. * Dispose of the pipeline and stop all post processes
  82672. */
  82673. StandardRenderingPipeline.prototype.dispose = function () {
  82674. this._disposePostProcesses();
  82675. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82676. _super.prototype.dispose.call(this);
  82677. };
  82678. /**
  82679. * Serialize the rendering pipeline (Used when exporting)
  82680. * @returns the serialized object
  82681. */
  82682. StandardRenderingPipeline.prototype.serialize = function () {
  82683. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82684. if (this.sourceLight) {
  82685. serializationObject.sourceLightId = this.sourceLight.id;
  82686. }
  82687. serializationObject.customType = "StandardRenderingPipeline";
  82688. return serializationObject;
  82689. };
  82690. /**
  82691. * Parse the serialized pipeline
  82692. * @param source Source pipeline.
  82693. * @param scene The scene to load the pipeline to.
  82694. * @param rootUrl The URL of the serialized pipeline.
  82695. * @returns An instantiated pipeline from the serialized object.
  82696. */
  82697. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82698. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82699. if (source.sourceLightId) {
  82700. p.sourceLight = scene.getLightByID(source.sourceLightId);
  82701. }
  82702. return p;
  82703. };
  82704. // Luminance steps
  82705. StandardRenderingPipeline.LuminanceSteps = 6;
  82706. __decorate([
  82707. BABYLON.serialize()
  82708. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  82709. __decorate([
  82710. BABYLON.serialize()
  82711. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  82712. __decorate([
  82713. BABYLON.serialize()
  82714. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  82715. __decorate([
  82716. BABYLON.serialize()
  82717. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  82718. __decorate([
  82719. BABYLON.serializeAsTexture("lensTexture")
  82720. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  82721. __decorate([
  82722. BABYLON.serialize()
  82723. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  82724. __decorate([
  82725. BABYLON.serialize()
  82726. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  82727. __decorate([
  82728. BABYLON.serialize()
  82729. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  82730. __decorate([
  82731. BABYLON.serialize()
  82732. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  82733. __decorate([
  82734. BABYLON.serialize()
  82735. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  82736. __decorate([
  82737. BABYLON.serialize()
  82738. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  82739. __decorate([
  82740. BABYLON.serializeAsTexture("lensColorTexture")
  82741. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  82742. __decorate([
  82743. BABYLON.serialize()
  82744. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  82745. __decorate([
  82746. BABYLON.serialize()
  82747. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  82748. __decorate([
  82749. BABYLON.serialize()
  82750. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  82751. __decorate([
  82752. BABYLON.serialize()
  82753. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  82754. __decorate([
  82755. BABYLON.serializeAsTexture("lensStarTexture")
  82756. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  82757. __decorate([
  82758. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  82759. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  82760. __decorate([
  82761. BABYLON.serialize()
  82762. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  82763. __decorate([
  82764. BABYLON.serialize()
  82765. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  82766. __decorate([
  82767. BABYLON.serialize()
  82768. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  82769. __decorate([
  82770. BABYLON.serialize()
  82771. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  82772. __decorate([
  82773. BABYLON.serialize()
  82774. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  82775. __decorate([
  82776. BABYLON.serialize()
  82777. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  82778. __decorate([
  82779. BABYLON.serialize()
  82780. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  82781. __decorate([
  82782. BABYLON.serialize()
  82783. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  82784. __decorate([
  82785. BABYLON.serialize()
  82786. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  82787. __decorate([
  82788. BABYLON.serialize()
  82789. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  82790. __decorate([
  82791. BABYLON.serialize()
  82792. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  82793. __decorate([
  82794. BABYLON.serialize()
  82795. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  82796. __decorate([
  82797. BABYLON.serialize()
  82798. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  82799. __decorate([
  82800. BABYLON.serialize()
  82801. ], StandardRenderingPipeline.prototype, "samples", null);
  82802. return StandardRenderingPipeline;
  82803. }(BABYLON.PostProcessRenderPipeline));
  82804. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  82805. })(BABYLON || (BABYLON = {}));
  82806. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  82807. var BABYLON;
  82808. (function (BABYLON) {
  82809. var FxaaPostProcess = /** @class */ (function (_super) {
  82810. __extends(FxaaPostProcess, _super);
  82811. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82812. if (camera === void 0) { camera = null; }
  82813. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82814. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  82815. var defines = _this._getDefines();
  82816. _this.updateEffect(defines);
  82817. _this.onApplyObservable.add(function (effect) {
  82818. var texelSize = _this.texelSize;
  82819. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  82820. });
  82821. return _this;
  82822. }
  82823. FxaaPostProcess.prototype._getDefines = function () {
  82824. var engine = this.getEngine();
  82825. if (!engine) {
  82826. return null;
  82827. }
  82828. var glInfo = engine.getGlInfo();
  82829. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  82830. return "#define MALI 1\n";
  82831. }
  82832. return null;
  82833. };
  82834. return FxaaPostProcess;
  82835. }(BABYLON.PostProcess));
  82836. BABYLON.FxaaPostProcess = FxaaPostProcess;
  82837. })(BABYLON || (BABYLON = {}));
  82838. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  82839. var BABYLON;
  82840. (function (BABYLON) {
  82841. /**
  82842. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  82843. */
  82844. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  82845. __extends(ChromaticAberrationPostProcess, _super);
  82846. /**
  82847. * Creates a new instance ChromaticAberrationPostProcess
  82848. * @param name The name of the effect.
  82849. * @param screenWidth The width of the screen to apply the effect on.
  82850. * @param screenHeight The height of the screen to apply the effect on.
  82851. * @param options The required width/height ratio to downsize to before computing the render pass.
  82852. * @param camera The camera to apply the render pass to.
  82853. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82854. * @param engine The engine which the post process will be applied. (default: current engine)
  82855. * @param reusable If the post process can be reused on the same frame. (default: false)
  82856. * @param textureType Type of textures used when performing the post process. (default: 0)
  82857. * @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)
  82858. */
  82859. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82860. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82861. if (blockCompilation === void 0) { blockCompilation = false; }
  82862. 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;
  82863. /**
  82864. * The amount of seperation of rgb channels (default: 30)
  82865. */
  82866. _this.aberrationAmount = 30;
  82867. /**
  82868. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  82869. */
  82870. _this.radialIntensity = 0;
  82871. /**
  82872. * 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))
  82873. */
  82874. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  82875. /**
  82876. * 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))
  82877. */
  82878. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  82879. _this.onApplyObservable.add(function (effect) {
  82880. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  82881. effect.setFloat('screen_width', screenWidth);
  82882. effect.setFloat('screen_height', screenHeight);
  82883. effect.setFloat('radialIntensity', _this.radialIntensity);
  82884. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  82885. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  82886. });
  82887. return _this;
  82888. }
  82889. return ChromaticAberrationPostProcess;
  82890. }(BABYLON.PostProcess));
  82891. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  82892. })(BABYLON || (BABYLON = {}));
  82893. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  82894. var BABYLON;
  82895. (function (BABYLON) {
  82896. /**
  82897. * The GrainPostProcess adds noise to the image at mid luminance levels
  82898. */
  82899. var GrainPostProcess = /** @class */ (function (_super) {
  82900. __extends(GrainPostProcess, _super);
  82901. /**
  82902. * Creates a new instance of @see GrainPostProcess
  82903. * @param name The name of the effect.
  82904. * @param options The required width/height ratio to downsize to before computing the render pass.
  82905. * @param camera The camera to apply the render pass to.
  82906. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82907. * @param engine The engine which the post process will be applied. (default: current engine)
  82908. * @param reusable If the post process can be reused on the same frame. (default: false)
  82909. * @param textureType Type of textures used when performing the post process. (default: 0)
  82910. * @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)
  82911. */
  82912. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82913. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82914. if (blockCompilation === void 0) { blockCompilation = false; }
  82915. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82916. /**
  82917. * The intensity of the grain added (default: 30)
  82918. */
  82919. _this.intensity = 30;
  82920. /**
  82921. * If the grain should be randomized on every frame
  82922. */
  82923. _this.animated = false;
  82924. _this.onApplyObservable.add(function (effect) {
  82925. effect.setFloat('intensity', _this.intensity);
  82926. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82927. });
  82928. return _this;
  82929. }
  82930. return GrainPostProcess;
  82931. }(BABYLON.PostProcess));
  82932. BABYLON.GrainPostProcess = GrainPostProcess;
  82933. })(BABYLON || (BABYLON = {}));
  82934. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82935. var BABYLON;
  82936. (function (BABYLON) {
  82937. /**
  82938. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82939. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82940. */
  82941. var SharpenPostProcess = /** @class */ (function (_super) {
  82942. __extends(SharpenPostProcess, _super);
  82943. /**
  82944. * Creates a new instance ConvolutionPostProcess
  82945. * @param name The name of the effect.
  82946. * @param options The required width/height ratio to downsize to before computing the render pass.
  82947. * @param camera The camera to apply the render pass to.
  82948. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82949. * @param engine The engine which the post process will be applied. (default: current engine)
  82950. * @param reusable If the post process can be reused on the same frame. (default: false)
  82951. * @param textureType Type of textures used when performing the post process. (default: 0)
  82952. * @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)
  82953. */
  82954. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82955. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82956. if (blockCompilation === void 0) { blockCompilation = false; }
  82957. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82958. /**
  82959. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82960. */
  82961. _this.colorAmount = 1.0;
  82962. /**
  82963. * How much sharpness should be applied (default: 0.3)
  82964. */
  82965. _this.edgeAmount = 0.3;
  82966. _this.onApply = function (effect) {
  82967. effect.setFloat2("screenSize", _this.width, _this.height);
  82968. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82969. };
  82970. return _this;
  82971. }
  82972. return SharpenPostProcess;
  82973. }(BABYLON.PostProcess));
  82974. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82975. })(BABYLON || (BABYLON = {}));
  82976. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82977. var BABYLON;
  82978. (function (BABYLON) {
  82979. /**
  82980. * The Blur Post Process which blurs an image based on a kernel and direction.
  82981. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82982. */
  82983. var BlurPostProcess = /** @class */ (function (_super) {
  82984. __extends(BlurPostProcess, _super);
  82985. /**
  82986. * Creates a new instance BlurPostProcess
  82987. * @param name The name of the effect.
  82988. * @param direction The direction in which to blur the image.
  82989. * @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.
  82990. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82991. * @param camera The camera to apply the render pass to.
  82992. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82993. * @param engine The engine which the post process will be applied. (default: current engine)
  82994. * @param reusable If the post process can be reused on the same frame. (default: false)
  82995. * @param textureType Type of textures used when performing the post process. (default: 0)
  82996. * @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)
  82997. */
  82998. function BlurPostProcess(name,
  82999. /** The direction in which to blur the image. */
  83000. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  83001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83002. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83003. if (defines === void 0) { defines = ""; }
  83004. if (blockCompilation === void 0) { blockCompilation = false; }
  83005. 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;
  83006. _this.direction = direction;
  83007. _this.blockCompilation = blockCompilation;
  83008. _this._packedFloat = false;
  83009. _this._staticDefines = "";
  83010. _this._staticDefines = defines;
  83011. _this.onApplyObservable.add(function (effect) {
  83012. if (_this._outputTexture) {
  83013. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  83014. }
  83015. else {
  83016. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  83017. }
  83018. });
  83019. _this.kernel = kernel;
  83020. return _this;
  83021. }
  83022. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  83023. /**
  83024. * Gets the length in pixels of the blur sample region
  83025. */
  83026. get: function () {
  83027. return this._idealKernel;
  83028. },
  83029. /**
  83030. * Sets the length in pixels of the blur sample region
  83031. */
  83032. set: function (v) {
  83033. if (this._idealKernel === v) {
  83034. return;
  83035. }
  83036. v = Math.max(v, 1);
  83037. this._idealKernel = v;
  83038. this._kernel = this._nearestBestKernel(v);
  83039. if (!this.blockCompilation) {
  83040. this._updateParameters();
  83041. }
  83042. },
  83043. enumerable: true,
  83044. configurable: true
  83045. });
  83046. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  83047. /**
  83048. * Gets wether or not the blur is unpacking/repacking floats
  83049. */
  83050. get: function () {
  83051. return this._packedFloat;
  83052. },
  83053. /**
  83054. * Sets wether or not the blur needs to unpack/repack floats
  83055. */
  83056. set: function (v) {
  83057. if (this._packedFloat === v) {
  83058. return;
  83059. }
  83060. this._packedFloat = v;
  83061. if (!this.blockCompilation) {
  83062. this._updateParameters();
  83063. }
  83064. },
  83065. enumerable: true,
  83066. configurable: true
  83067. });
  83068. /**
  83069. * Updates the effect with the current post process compile time values and recompiles the shader.
  83070. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83071. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83072. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83073. * @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
  83074. * @param onCompiled Called when the shader has been compiled.
  83075. * @param onError Called if there is an error when compiling a shader.
  83076. */
  83077. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83078. if (defines === void 0) { defines = null; }
  83079. if (uniforms === void 0) { uniforms = null; }
  83080. if (samplers === void 0) { samplers = null; }
  83081. this._updateParameters(onCompiled, onError);
  83082. };
  83083. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  83084. // Generate sampling offsets and weights
  83085. var N = this._kernel;
  83086. var centerIndex = (N - 1) / 2;
  83087. // Generate Gaussian sampling weights over kernel
  83088. var offsets = [];
  83089. var weights = [];
  83090. var totalWeight = 0;
  83091. for (var i = 0; i < N; i++) {
  83092. var u = i / (N - 1);
  83093. var w = this._gaussianWeight(u * 2.0 - 1);
  83094. offsets[i] = (i - centerIndex);
  83095. weights[i] = w;
  83096. totalWeight += w;
  83097. }
  83098. // Normalize weights
  83099. for (var i = 0; i < weights.length; i++) {
  83100. weights[i] /= totalWeight;
  83101. }
  83102. // Optimize: combine samples to take advantage of hardware linear sampling
  83103. // Walk from left to center, combining pairs (symmetrically)
  83104. var linearSamplingWeights = [];
  83105. var linearSamplingOffsets = [];
  83106. var linearSamplingMap = [];
  83107. for (var i = 0; i <= centerIndex; i += 2) {
  83108. var j = Math.min(i + 1, Math.floor(centerIndex));
  83109. var singleCenterSample = i === j;
  83110. if (singleCenterSample) {
  83111. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83112. }
  83113. else {
  83114. var sharedCell = j === centerIndex;
  83115. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  83116. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  83117. if (offsetLinear === 0) {
  83118. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83119. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  83120. }
  83121. else {
  83122. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  83123. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  83124. }
  83125. }
  83126. }
  83127. for (var i = 0; i < linearSamplingMap.length; i++) {
  83128. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  83129. linearSamplingWeights[i] = linearSamplingMap[i].w;
  83130. }
  83131. // Replace with optimized
  83132. offsets = linearSamplingOffsets;
  83133. weights = linearSamplingWeights;
  83134. // Generate shaders
  83135. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  83136. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  83137. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  83138. var defines = "";
  83139. defines += this._staticDefines;
  83140. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  83141. if (this._staticDefines.indexOf("DOF") != -1) {
  83142. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  83143. varyingCount--;
  83144. }
  83145. for (var i = 0; i < varyingCount; i++) {
  83146. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  83147. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  83148. }
  83149. var depCount = 0;
  83150. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  83151. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  83152. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  83153. depCount++;
  83154. }
  83155. if (this.packedFloat) {
  83156. defines += "#define PACKEDFLOAT 1";
  83157. }
  83158. this.blockCompilation = false;
  83159. _super.prototype.updateEffect.call(this, defines, null, null, {
  83160. varyingCount: varyingCount,
  83161. depCount: depCount
  83162. }, onCompiled, onError);
  83163. };
  83164. /**
  83165. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  83166. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  83167. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  83168. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  83169. * The gaps between physical kernels are compensated for in the weighting of the samples
  83170. * @param idealKernel Ideal blur kernel.
  83171. * @return Nearest best kernel.
  83172. */
  83173. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  83174. var v = Math.round(idealKernel);
  83175. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  83176. var k = _a[_i];
  83177. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  83178. return Math.max(k, 3);
  83179. }
  83180. }
  83181. return Math.max(v, 3);
  83182. };
  83183. /**
  83184. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  83185. * @param x The point on the Gaussian distribution to sample.
  83186. * @return the value of the Gaussian function at x.
  83187. */
  83188. BlurPostProcess.prototype._gaussianWeight = function (x) {
  83189. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  83190. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  83191. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  83192. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  83193. // truncated at around 1.3% of peak strength.
  83194. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  83195. var sigma = (1 / 3);
  83196. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  83197. var exponent = -((x * x) / (2.0 * sigma * sigma));
  83198. var weight = (1.0 / denominator) * Math.exp(exponent);
  83199. return weight;
  83200. };
  83201. /**
  83202. * Generates a string that can be used as a floating point number in GLSL.
  83203. * @param x Value to print.
  83204. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  83205. * @return GLSL float string.
  83206. */
  83207. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  83208. if (decimalFigures === void 0) { decimalFigures = 8; }
  83209. return x.toFixed(decimalFigures).replace(/0+$/, '');
  83210. };
  83211. return BlurPostProcess;
  83212. }(BABYLON.PostProcess));
  83213. BABYLON.BlurPostProcess = BlurPostProcess;
  83214. })(BABYLON || (BABYLON = {}));
  83215. //# sourceMappingURL=babylon.blurPostProcess.js.map
  83216. var BABYLON;
  83217. (function (BABYLON) {
  83218. /**
  83219. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  83220. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  83221. * based on samples that have a large difference in distance than the center pixel.
  83222. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83223. */
  83224. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  83225. __extends(DepthOfFieldBlurPostProcess, _super);
  83226. /**
  83227. * Creates a new instance CircleOfConfusionPostProcess
  83228. * @param name The name of the effect.
  83229. * @param scene The scene the effect belongs to.
  83230. * @param direction The direction the blur should be applied.
  83231. * @param kernel The size of the kernel used to blur.
  83232. * @param options The required width/height ratio to downsize to before computing the render pass.
  83233. * @param camera The camera to apply the render pass to.
  83234. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  83235. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  83236. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83237. * @param engine The engine which the post process will be applied. (default: current engine)
  83238. * @param reusable If the post process can be reused on the same frame. (default: false)
  83239. * @param textureType Type of textures used when performing the post process. (default: 0)
  83240. * @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)
  83241. */
  83242. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  83243. if (imageToBlur === void 0) { imageToBlur = null; }
  83244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83245. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83246. if (blockCompilation === void 0) { blockCompilation = false; }
  83247. 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;
  83248. _this.direction = direction;
  83249. _this.onApplyObservable.add(function (effect) {
  83250. if (imageToBlur != null) {
  83251. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  83252. }
  83253. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83254. if (scene.activeCamera) {
  83255. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83256. }
  83257. });
  83258. return _this;
  83259. }
  83260. return DepthOfFieldBlurPostProcess;
  83261. }(BABYLON.BlurPostProcess));
  83262. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  83263. })(BABYLON || (BABYLON = {}));
  83264. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  83265. var BABYLON;
  83266. (function (BABYLON) {
  83267. /**
  83268. * Options to be set when merging outputs from the default pipeline.
  83269. */
  83270. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  83271. function DepthOfFieldMergePostProcessOptions() {
  83272. }
  83273. return DepthOfFieldMergePostProcessOptions;
  83274. }());
  83275. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  83276. /**
  83277. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83278. */
  83279. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  83280. __extends(DepthOfFieldMergePostProcess, _super);
  83281. /**
  83282. * Creates a new instance of DepthOfFieldMergePostProcess
  83283. * @param name The name of the effect.
  83284. * @param originalFromInput Post process which's input will be used for the merge.
  83285. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  83286. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  83287. * @param options The required width/height ratio to downsize to before computing the render pass.
  83288. * @param camera The camera to apply the render pass to.
  83289. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83290. * @param engine The engine which the post process will be applied. (default: current engine)
  83291. * @param reusable If the post process can be reused on the same frame. (default: false)
  83292. * @param textureType Type of textures used when performing the post process. (default: 0)
  83293. * @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)
  83294. */
  83295. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83296. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83297. if (blockCompilation === void 0) { blockCompilation = false; }
  83298. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83299. _this.blurSteps = blurSteps;
  83300. _this.onApplyObservable.add(function (effect) {
  83301. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83302. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83303. blurSteps.forEach(function (step, index) {
  83304. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  83305. });
  83306. });
  83307. if (!blockCompilation) {
  83308. _this.updateEffect();
  83309. }
  83310. return _this;
  83311. }
  83312. /**
  83313. * Updates the effect with the current post process compile time values and recompiles the shader.
  83314. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83315. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83316. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83317. * @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
  83318. * @param onCompiled Called when the shader has been compiled.
  83319. * @param onError Called if there is an error when compiling a shader.
  83320. */
  83321. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83322. if (defines === void 0) { defines = null; }
  83323. if (uniforms === void 0) { uniforms = null; }
  83324. if (samplers === void 0) { samplers = null; }
  83325. if (!defines) {
  83326. defines = "";
  83327. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  83328. }
  83329. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  83330. };
  83331. return DepthOfFieldMergePostProcess;
  83332. }(BABYLON.PostProcess));
  83333. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  83334. })(BABYLON || (BABYLON = {}));
  83335. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  83336. var BABYLON;
  83337. (function (BABYLON) {
  83338. /**
  83339. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  83340. */
  83341. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  83342. __extends(CircleOfConfusionPostProcess, _super);
  83343. /**
  83344. * Creates a new instance CircleOfConfusionPostProcess
  83345. * @param name The name of the effect.
  83346. * @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.
  83347. * @param options The required width/height ratio to downsize to before computing the render pass.
  83348. * @param camera The camera to apply the render pass to.
  83349. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83350. * @param engine The engine which the post process will be applied. (default: current engine)
  83351. * @param reusable If the post process can be reused on the same frame. (default: false)
  83352. * @param textureType Type of textures used when performing the post process. (default: 0)
  83353. * @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)
  83354. */
  83355. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83356. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83357. if (blockCompilation === void 0) { blockCompilation = false; }
  83358. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83359. /**
  83360. * 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.
  83361. */
  83362. _this.lensSize = 50;
  83363. /**
  83364. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83365. */
  83366. _this.fStop = 1.4;
  83367. /**
  83368. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83369. */
  83370. _this.focusDistance = 2000;
  83371. /**
  83372. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  83373. */
  83374. _this.focalLength = 50;
  83375. _this._depthTexture = null;
  83376. _this._depthTexture = depthTexture;
  83377. _this.onApplyObservable.add(function (effect) {
  83378. if (!_this._depthTexture) {
  83379. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  83380. return;
  83381. }
  83382. effect.setTexture("depthSampler", _this._depthTexture);
  83383. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  83384. var aperture = _this.lensSize / _this.fStop;
  83385. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  83386. effect.setFloat('focusDistance', _this.focusDistance);
  83387. effect.setFloat('cocPrecalculation', cocPrecalculation);
  83388. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  83389. });
  83390. return _this;
  83391. }
  83392. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  83393. /**
  83394. * 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.
  83395. */
  83396. set: function (value) {
  83397. this._depthTexture = value;
  83398. },
  83399. enumerable: true,
  83400. configurable: true
  83401. });
  83402. return CircleOfConfusionPostProcess;
  83403. }(BABYLON.PostProcess));
  83404. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  83405. })(BABYLON || (BABYLON = {}));
  83406. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  83407. var BABYLON;
  83408. (function (BABYLON) {
  83409. /**
  83410. * Specifies the level of max blur that should be applied when using the depth of field effect
  83411. */
  83412. var DepthOfFieldEffectBlurLevel;
  83413. (function (DepthOfFieldEffectBlurLevel) {
  83414. /**
  83415. * Subtle blur
  83416. */
  83417. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  83418. /**
  83419. * Medium blur
  83420. */
  83421. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  83422. /**
  83423. * Large blur
  83424. */
  83425. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  83426. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  83427. ;
  83428. /**
  83429. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  83430. */
  83431. var DepthOfFieldEffect = /** @class */ (function (_super) {
  83432. __extends(DepthOfFieldEffect, _super);
  83433. /**
  83434. * Creates a new instance DepthOfFieldEffect
  83435. * @param scene The scene the effect belongs to.
  83436. * @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.
  83437. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83438. * @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)
  83439. */
  83440. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  83441. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  83442. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83443. if (blockCompilation === void 0) { blockCompilation = false; }
  83444. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  83445. return _this._effects;
  83446. }, true) || this;
  83447. /**
  83448. * @hidden Internal post processes in depth of field effect
  83449. */
  83450. _this._effects = [];
  83451. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  83452. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83453. // 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)
  83454. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  83455. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83456. _this._depthOfFieldBlurY = [];
  83457. _this._depthOfFieldBlurX = [];
  83458. var blurCount = 1;
  83459. var kernelSize = 15;
  83460. switch (blurLevel) {
  83461. case DepthOfFieldEffectBlurLevel.High: {
  83462. blurCount = 3;
  83463. kernelSize = 51;
  83464. break;
  83465. }
  83466. case DepthOfFieldEffectBlurLevel.Medium: {
  83467. blurCount = 2;
  83468. kernelSize = 31;
  83469. break;
  83470. }
  83471. default: {
  83472. kernelSize = 15;
  83473. blurCount = 1;
  83474. break;
  83475. }
  83476. }
  83477. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  83478. var ratio = 1.0;
  83479. for (var i = 0; i < blurCount; i++) {
  83480. 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);
  83481. blurY.autoClear = false;
  83482. ratio = 0.75 / Math.pow(2, i);
  83483. 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);
  83484. blurX.autoClear = false;
  83485. _this._depthOfFieldBlurY.push(blurY);
  83486. _this._depthOfFieldBlurX.push(blurX);
  83487. }
  83488. // Set all post processes on the effect.
  83489. _this._effects = [_this._circleOfConfusion];
  83490. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  83491. _this._effects.push(_this._depthOfFieldBlurY[i]);
  83492. _this._effects.push(_this._depthOfFieldBlurX[i]);
  83493. }
  83494. // Merge blurred images with original image based on circleOfConfusion
  83495. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83496. _this._dofMerge.autoClear = false;
  83497. _this._effects.push(_this._dofMerge);
  83498. return _this;
  83499. }
  83500. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  83501. get: function () {
  83502. return this._circleOfConfusion.focalLength;
  83503. },
  83504. /**
  83505. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  83506. */
  83507. set: function (value) {
  83508. this._circleOfConfusion.focalLength = value;
  83509. },
  83510. enumerable: true,
  83511. configurable: true
  83512. });
  83513. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  83514. get: function () {
  83515. return this._circleOfConfusion.fStop;
  83516. },
  83517. /**
  83518. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83519. */
  83520. set: function (value) {
  83521. this._circleOfConfusion.fStop = value;
  83522. },
  83523. enumerable: true,
  83524. configurable: true
  83525. });
  83526. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  83527. get: function () {
  83528. return this._circleOfConfusion.focusDistance;
  83529. },
  83530. /**
  83531. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83532. */
  83533. set: function (value) {
  83534. this._circleOfConfusion.focusDistance = value;
  83535. },
  83536. enumerable: true,
  83537. configurable: true
  83538. });
  83539. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83540. get: function () {
  83541. return this._circleOfConfusion.lensSize;
  83542. },
  83543. /**
  83544. * 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.
  83545. */
  83546. set: function (value) {
  83547. this._circleOfConfusion.lensSize = value;
  83548. },
  83549. enumerable: true,
  83550. configurable: true
  83551. });
  83552. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83553. /**
  83554. * 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.
  83555. */
  83556. set: function (value) {
  83557. this._circleOfConfusion.depthTexture = value;
  83558. },
  83559. enumerable: true,
  83560. configurable: true
  83561. });
  83562. /**
  83563. * Disposes each of the internal effects for a given camera.
  83564. * @param camera The camera to dispose the effect on.
  83565. */
  83566. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83567. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83568. this._effects[effectIndex].dispose(camera);
  83569. }
  83570. };
  83571. /**
  83572. * @hidden Internal
  83573. */
  83574. DepthOfFieldEffect.prototype._updateEffects = function () {
  83575. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83576. this._effects[effectIndex].updateEffect();
  83577. }
  83578. };
  83579. /**
  83580. * Internal
  83581. * @returns if all the contained post processes are ready.
  83582. * @hidden
  83583. */
  83584. DepthOfFieldEffect.prototype._isReady = function () {
  83585. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83586. if (!this._effects[effectIndex].isReady()) {
  83587. return false;
  83588. }
  83589. }
  83590. return true;
  83591. };
  83592. return DepthOfFieldEffect;
  83593. }(BABYLON.PostProcessRenderEffect));
  83594. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83595. })(BABYLON || (BABYLON = {}));
  83596. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83597. var BABYLON;
  83598. (function (BABYLON) {
  83599. /**
  83600. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83601. */
  83602. var BloomMergePostProcess = /** @class */ (function (_super) {
  83603. __extends(BloomMergePostProcess, _super);
  83604. /**
  83605. * Creates a new instance of @see BloomMergePostProcess
  83606. * @param name The name of the effect.
  83607. * @param originalFromInput Post process which's input will be used for the merge.
  83608. * @param blurred Blurred highlights post process which's output will be used.
  83609. * @param weight Weight of the bloom to be added to the original input.
  83610. * @param options The required width/height ratio to downsize to before computing the render pass.
  83611. * @param camera The camera to apply the render pass to.
  83612. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83613. * @param engine The engine which the post process will be applied. (default: current engine)
  83614. * @param reusable If the post process can be reused on the same frame. (default: false)
  83615. * @param textureType Type of textures used when performing the post process. (default: 0)
  83616. * @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)
  83617. */
  83618. function BloomMergePostProcess(name, originalFromInput, blurred,
  83619. /** Weight of the bloom to be added to the original input. */
  83620. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83621. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83622. if (blockCompilation === void 0) { blockCompilation = false; }
  83623. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83624. _this.weight = weight;
  83625. _this.onApplyObservable.add(function (effect) {
  83626. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83627. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83628. effect.setFloat("bloomWeight", _this.weight);
  83629. });
  83630. if (!blockCompilation) {
  83631. _this.updateEffect();
  83632. }
  83633. return _this;
  83634. }
  83635. return BloomMergePostProcess;
  83636. }(BABYLON.PostProcess));
  83637. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83638. })(BABYLON || (BABYLON = {}));
  83639. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83640. var BABYLON;
  83641. (function (BABYLON) {
  83642. /**
  83643. * 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.
  83644. */
  83645. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83646. __extends(ExtractHighlightsPostProcess, _super);
  83647. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83648. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83649. if (blockCompilation === void 0) { blockCompilation = false; }
  83650. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83651. /**
  83652. * The luminance threshold, pixels below this value will be set to black.
  83653. */
  83654. _this.threshold = 0.9;
  83655. /** @hidden */
  83656. _this._exposure = 1;
  83657. /**
  83658. * Post process which has the input texture to be used when performing highlight extraction
  83659. * @hidden
  83660. */
  83661. _this._inputPostProcess = null;
  83662. _this.onApplyObservable.add(function (effect) {
  83663. if (_this._inputPostProcess) {
  83664. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  83665. }
  83666. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  83667. effect.setFloat('exposure', _this._exposure);
  83668. });
  83669. return _this;
  83670. }
  83671. return ExtractHighlightsPostProcess;
  83672. }(BABYLON.PostProcess));
  83673. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  83674. })(BABYLON || (BABYLON = {}));
  83675. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  83676. var BABYLON;
  83677. (function (BABYLON) {
  83678. /**
  83679. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  83680. */
  83681. var BloomEffect = /** @class */ (function (_super) {
  83682. __extends(BloomEffect, _super);
  83683. /**
  83684. * Creates a new instance of @see BloomEffect
  83685. * @param scene The scene the effect belongs to.
  83686. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  83687. * @param bloomKernel The size of the kernel to be used when applying the blur.
  83688. * @param bloomWeight The the strength of bloom.
  83689. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83690. * @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)
  83691. */
  83692. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  83693. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83694. if (blockCompilation === void 0) { blockCompilation = false; }
  83695. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  83696. return _this._effects;
  83697. }, true) || this;
  83698. _this.bloomScale = bloomScale;
  83699. /**
  83700. * @hidden Internal
  83701. */
  83702. _this._effects = [];
  83703. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83704. _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);
  83705. _this._blurX.alwaysForcePOT = true;
  83706. _this._blurX.autoClear = false;
  83707. _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);
  83708. _this._blurY.alwaysForcePOT = true;
  83709. _this._blurY.autoClear = false;
  83710. _this.kernel = bloomKernel;
  83711. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  83712. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83713. _this._merge.autoClear = false;
  83714. _this._effects.push(_this._merge);
  83715. return _this;
  83716. }
  83717. Object.defineProperty(BloomEffect.prototype, "threshold", {
  83718. /**
  83719. * The luminance threshold to find bright areas of the image to bloom.
  83720. */
  83721. get: function () {
  83722. return this._downscale.threshold;
  83723. },
  83724. set: function (value) {
  83725. this._downscale.threshold = value;
  83726. },
  83727. enumerable: true,
  83728. configurable: true
  83729. });
  83730. Object.defineProperty(BloomEffect.prototype, "weight", {
  83731. /**
  83732. * The strength of the bloom.
  83733. */
  83734. get: function () {
  83735. return this._merge.weight;
  83736. },
  83737. set: function (value) {
  83738. this._merge.weight = value;
  83739. },
  83740. enumerable: true,
  83741. configurable: true
  83742. });
  83743. Object.defineProperty(BloomEffect.prototype, "kernel", {
  83744. /**
  83745. * Specifies the size of the bloom blur kernel, relative to the final output size
  83746. */
  83747. get: function () {
  83748. return this._blurX.kernel / this.bloomScale;
  83749. },
  83750. set: function (value) {
  83751. this._blurX.kernel = value * this.bloomScale;
  83752. this._blurY.kernel = value * this.bloomScale;
  83753. },
  83754. enumerable: true,
  83755. configurable: true
  83756. });
  83757. /**
  83758. * Disposes each of the internal effects for a given camera.
  83759. * @param camera The camera to dispose the effect on.
  83760. */
  83761. BloomEffect.prototype.disposeEffects = function (camera) {
  83762. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83763. this._effects[effectIndex].dispose(camera);
  83764. }
  83765. };
  83766. /**
  83767. * @hidden Internal
  83768. */
  83769. BloomEffect.prototype._updateEffects = function () {
  83770. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83771. this._effects[effectIndex].updateEffect();
  83772. }
  83773. };
  83774. /**
  83775. * Internal
  83776. * @returns if all the contained post processes are ready.
  83777. * @hidden
  83778. */
  83779. BloomEffect.prototype._isReady = function () {
  83780. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83781. if (!this._effects[effectIndex].isReady()) {
  83782. return false;
  83783. }
  83784. }
  83785. return true;
  83786. };
  83787. return BloomEffect;
  83788. }(BABYLON.PostProcessRenderEffect));
  83789. BABYLON.BloomEffect = BloomEffect;
  83790. })(BABYLON || (BABYLON = {}));
  83791. //# sourceMappingURL=babylon.bloomEffect.js.map
  83792. var BABYLON;
  83793. (function (BABYLON) {
  83794. /**
  83795. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  83796. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  83797. */
  83798. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  83799. __extends(DefaultRenderingPipeline, _super);
  83800. /**
  83801. * @constructor
  83802. * @param {string} name - The rendering pipeline name (default: "")
  83803. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  83804. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  83805. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  83806. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  83807. */
  83808. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  83809. if (name === void 0) { name = ""; }
  83810. if (hdr === void 0) { hdr = true; }
  83811. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  83812. if (automaticBuild === void 0) { automaticBuild = true; }
  83813. var _this = _super.call(this, scene.getEngine(), name) || this;
  83814. _this._camerasToBeAttached = [];
  83815. /**
  83816. * ID of the sharpen post process,
  83817. */
  83818. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  83819. /**
  83820. * ID of the image processing post process;
  83821. */
  83822. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  83823. /**
  83824. * ID of the Fast Approximate Anti-Aliasing post process;
  83825. */
  83826. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  83827. /**
  83828. * ID of the chromatic aberration post process,
  83829. */
  83830. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  83831. /**
  83832. * ID of the grain post process
  83833. */
  83834. _this.GrainPostProcessId = "GrainPostProcessEffect";
  83835. /**
  83836. * Glow post process which adds a glow to emmisive areas of the image
  83837. */
  83838. _this._glowLayer = null;
  83839. /**
  83840. * Animations which can be used to tweak settings over a period of time
  83841. */
  83842. _this.animations = [];
  83843. _this._imageProcessingConfigurationObserver = null;
  83844. // Values
  83845. _this._sharpenEnabled = false;
  83846. _this._bloomEnabled = false;
  83847. _this._depthOfFieldEnabled = false;
  83848. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  83849. _this._fxaaEnabled = false;
  83850. _this._imageProcessingEnabled = true;
  83851. _this._bloomScale = 0.5;
  83852. _this._chromaticAberrationEnabled = false;
  83853. _this._grainEnabled = false;
  83854. _this._buildAllowed = true;
  83855. _this._resizeObserver = null;
  83856. _this._hardwareScaleLevel = 1.0;
  83857. _this._bloomKernel = 64;
  83858. /**
  83859. * Specifies the weight of the bloom in the final rendering
  83860. */
  83861. _this._bloomWeight = 0.15;
  83862. /**
  83863. * Specifies the luma threshold for the area that will be blurred by the bloom
  83864. */
  83865. _this._bloomThreshold = 0.9;
  83866. _this._samples = 1;
  83867. _this._hasCleared = false;
  83868. _this._prevPostProcess = null;
  83869. _this._prevPrevPostProcess = null;
  83870. _this._depthOfFieldSceneObserver = null;
  83871. _this._cameras = cameras || scene.cameras;
  83872. _this._cameras = _this._cameras.slice();
  83873. _this._camerasToBeAttached = _this._cameras.slice();
  83874. _this._buildAllowed = automaticBuild;
  83875. // Initialize
  83876. _this._scene = scene;
  83877. var caps = _this._scene.getEngine().getCaps();
  83878. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  83879. // Misc
  83880. if (_this._hdr) {
  83881. if (caps.textureHalfFloatRender) {
  83882. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83883. }
  83884. else if (caps.textureFloatRender) {
  83885. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83886. }
  83887. }
  83888. else {
  83889. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83890. }
  83891. // Attach
  83892. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83893. var engine = _this._scene.getEngine();
  83894. // Create post processes before hand so they can be modified before enabled.
  83895. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  83896. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83897. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  83898. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  83899. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  83900. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83901. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  83902. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83903. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  83904. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83905. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83906. _this.bloomKernel = _this.bloomKernel;
  83907. });
  83908. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83909. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83910. });
  83911. _this._buildPipeline();
  83912. return _this;
  83913. }
  83914. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83915. get: function () {
  83916. return this._sharpenEnabled;
  83917. },
  83918. /**
  83919. * Enable or disable the sharpen process from the pipeline
  83920. */
  83921. set: function (enabled) {
  83922. if (this._sharpenEnabled === enabled) {
  83923. return;
  83924. }
  83925. this._sharpenEnabled = enabled;
  83926. this._buildPipeline();
  83927. },
  83928. enumerable: true,
  83929. configurable: true
  83930. });
  83931. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83932. /**
  83933. * Specifies the size of the bloom blur kernel, relative to the final output size
  83934. */
  83935. get: function () {
  83936. return this._bloomKernel;
  83937. },
  83938. set: function (value) {
  83939. this._bloomKernel = value;
  83940. this.bloom.kernel = value / this._hardwareScaleLevel;
  83941. },
  83942. enumerable: true,
  83943. configurable: true
  83944. });
  83945. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83946. get: function () {
  83947. return this._bloomWeight;
  83948. },
  83949. /**
  83950. * The strength of the bloom.
  83951. */
  83952. set: function (value) {
  83953. if (this._bloomWeight === value) {
  83954. return;
  83955. }
  83956. this.bloom.weight = value;
  83957. this._bloomWeight = value;
  83958. },
  83959. enumerable: true,
  83960. configurable: true
  83961. });
  83962. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83963. get: function () {
  83964. return this._bloomThreshold;
  83965. },
  83966. /**
  83967. * The strength of the bloom.
  83968. */
  83969. set: function (value) {
  83970. if (this._bloomThreshold === value) {
  83971. return;
  83972. }
  83973. this.bloom.threshold = value;
  83974. this._bloomThreshold = value;
  83975. },
  83976. enumerable: true,
  83977. configurable: true
  83978. });
  83979. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83980. get: function () {
  83981. return this._bloomScale;
  83982. },
  83983. /**
  83984. * The scale of the bloom, lower value will provide better performance.
  83985. */
  83986. set: function (value) {
  83987. if (this._bloomScale === value) {
  83988. return;
  83989. }
  83990. this._bloomScale = value;
  83991. // recreate bloom and dispose old as this setting is not dynamic
  83992. this._rebuildBloom();
  83993. this._buildPipeline();
  83994. },
  83995. enumerable: true,
  83996. configurable: true
  83997. });
  83998. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83999. get: function () {
  84000. return this._bloomEnabled;
  84001. },
  84002. /**
  84003. * Enable or disable the bloom from the pipeline
  84004. */
  84005. set: function (enabled) {
  84006. if (this._bloomEnabled === enabled) {
  84007. return;
  84008. }
  84009. this._bloomEnabled = enabled;
  84010. this._buildPipeline();
  84011. },
  84012. enumerable: true,
  84013. configurable: true
  84014. });
  84015. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  84016. // recreate bloom and dispose old as this setting is not dynamic
  84017. var oldBloom = this.bloom;
  84018. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  84019. this.bloom.threshold = oldBloom.threshold;
  84020. for (var i = 0; i < this._cameras.length; i++) {
  84021. oldBloom.disposeEffects(this._cameras[i]);
  84022. }
  84023. };
  84024. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  84025. /**
  84026. * If the depth of field is enabled.
  84027. */
  84028. get: function () {
  84029. return this._depthOfFieldEnabled;
  84030. },
  84031. set: function (enabled) {
  84032. if (this._depthOfFieldEnabled === enabled) {
  84033. return;
  84034. }
  84035. this._depthOfFieldEnabled = enabled;
  84036. this._buildPipeline();
  84037. },
  84038. enumerable: true,
  84039. configurable: true
  84040. });
  84041. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  84042. /**
  84043. * Blur level of the depth of field effect. (Higher blur will effect performance)
  84044. */
  84045. get: function () {
  84046. return this._depthOfFieldBlurLevel;
  84047. },
  84048. set: function (value) {
  84049. if (this._depthOfFieldBlurLevel === value) {
  84050. return;
  84051. }
  84052. this._depthOfFieldBlurLevel = value;
  84053. // recreate dof and dispose old as this setting is not dynamic
  84054. var oldDof = this.depthOfField;
  84055. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  84056. this.depthOfField.focalLength = oldDof.focalLength;
  84057. this.depthOfField.focusDistance = oldDof.focusDistance;
  84058. this.depthOfField.fStop = oldDof.fStop;
  84059. this.depthOfField.lensSize = oldDof.lensSize;
  84060. for (var i = 0; i < this._cameras.length; i++) {
  84061. oldDof.disposeEffects(this._cameras[i]);
  84062. }
  84063. this._buildPipeline();
  84064. },
  84065. enumerable: true,
  84066. configurable: true
  84067. });
  84068. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  84069. get: function () {
  84070. return this._fxaaEnabled;
  84071. },
  84072. /**
  84073. * If the anti aliasing is enabled.
  84074. */
  84075. set: function (enabled) {
  84076. if (this._fxaaEnabled === enabled) {
  84077. return;
  84078. }
  84079. this._fxaaEnabled = enabled;
  84080. this._buildPipeline();
  84081. },
  84082. enumerable: true,
  84083. configurable: true
  84084. });
  84085. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  84086. get: function () {
  84087. return this._samples;
  84088. },
  84089. /**
  84090. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84091. */
  84092. set: function (sampleCount) {
  84093. if (this._samples === sampleCount) {
  84094. return;
  84095. }
  84096. this._samples = sampleCount;
  84097. this._buildPipeline();
  84098. },
  84099. enumerable: true,
  84100. configurable: true
  84101. });
  84102. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  84103. get: function () {
  84104. return this._imageProcessingEnabled;
  84105. },
  84106. /**
  84107. * If image processing is enabled.
  84108. */
  84109. set: function (enabled) {
  84110. if (this._imageProcessingEnabled === enabled) {
  84111. return;
  84112. }
  84113. this._imageProcessingEnabled = enabled;
  84114. this._buildPipeline();
  84115. },
  84116. enumerable: true,
  84117. configurable: true
  84118. });
  84119. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  84120. get: function () {
  84121. return this._glowLayer == null;
  84122. },
  84123. /**
  84124. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  84125. */
  84126. set: function (enabled) {
  84127. if (enabled && !this._glowLayer) {
  84128. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  84129. }
  84130. else if (!enabled && this._glowLayer) {
  84131. this._glowLayer.dispose();
  84132. this._glowLayer = null;
  84133. }
  84134. },
  84135. enumerable: true,
  84136. configurable: true
  84137. });
  84138. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  84139. get: function () {
  84140. return this._chromaticAberrationEnabled;
  84141. },
  84142. /**
  84143. * Enable or disable the chromaticAberration process from the pipeline
  84144. */
  84145. set: function (enabled) {
  84146. if (this._chromaticAberrationEnabled === enabled) {
  84147. return;
  84148. }
  84149. this._chromaticAberrationEnabled = enabled;
  84150. this._buildPipeline();
  84151. },
  84152. enumerable: true,
  84153. configurable: true
  84154. });
  84155. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  84156. get: function () {
  84157. return this._grainEnabled;
  84158. },
  84159. /**
  84160. * Enable or disable the grain process from the pipeline
  84161. */
  84162. set: function (enabled) {
  84163. if (this._grainEnabled === enabled) {
  84164. return;
  84165. }
  84166. this._grainEnabled = enabled;
  84167. this._buildPipeline();
  84168. },
  84169. enumerable: true,
  84170. configurable: true
  84171. });
  84172. /**
  84173. * Force the compilation of the entire pipeline.
  84174. */
  84175. DefaultRenderingPipeline.prototype.prepare = function () {
  84176. var previousState = this._buildAllowed;
  84177. this._buildAllowed = true;
  84178. this._buildPipeline();
  84179. this._buildAllowed = previousState;
  84180. };
  84181. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  84182. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  84183. if (this._hasCleared) {
  84184. postProcess.autoClear = false;
  84185. }
  84186. else {
  84187. postProcess.autoClear = true;
  84188. this._scene.autoClear = false;
  84189. this._hasCleared = true;
  84190. }
  84191. if (!skipTextureSharing) {
  84192. if (this._prevPrevPostProcess) {
  84193. postProcess.shareOutputWith(this._prevPrevPostProcess);
  84194. }
  84195. else {
  84196. postProcess.useOwnOutput();
  84197. }
  84198. if (this._prevPostProcess) {
  84199. this._prevPrevPostProcess = this._prevPostProcess;
  84200. }
  84201. this._prevPostProcess = postProcess;
  84202. }
  84203. };
  84204. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  84205. var _this = this;
  84206. if (!this._buildAllowed) {
  84207. return;
  84208. }
  84209. this._scene.autoClear = true;
  84210. var engine = this._scene.getEngine();
  84211. this._disposePostProcesses();
  84212. if (this._cameras !== null) {
  84213. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84214. // get back cameras to be used to reattach pipeline
  84215. this._cameras = this._camerasToBeAttached.slice();
  84216. }
  84217. this._reset();
  84218. this._prevPostProcess = null;
  84219. this._prevPrevPostProcess = null;
  84220. this._hasCleared = false;
  84221. if (this.depthOfFieldEnabled) {
  84222. // Multi camera suport
  84223. if (this._cameras.length > 1) {
  84224. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  84225. var camera = _a[_i];
  84226. var depthRenderer = this._scene.enableDepthRenderer(camera);
  84227. depthRenderer.useOnlyInActiveCamera = true;
  84228. }
  84229. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  84230. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  84231. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  84232. }
  84233. });
  84234. }
  84235. else {
  84236. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84237. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  84238. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  84239. }
  84240. if (!this.depthOfField._isReady()) {
  84241. this.depthOfField._updateEffects();
  84242. }
  84243. this.addEffect(this.depthOfField);
  84244. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  84245. }
  84246. else {
  84247. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84248. }
  84249. if (this.bloomEnabled) {
  84250. if (!this.bloom._isReady()) {
  84251. this.bloom._updateEffects();
  84252. }
  84253. this.addEffect(this.bloom);
  84254. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  84255. }
  84256. if (this._imageProcessingEnabled) {
  84257. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84258. if (this._hdr) {
  84259. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  84260. this._setAutoClearAndTextureSharing(this.imageProcessing);
  84261. }
  84262. else {
  84263. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  84264. }
  84265. }
  84266. if (this.sharpenEnabled) {
  84267. if (!this.sharpen.isReady()) {
  84268. this.sharpen.updateEffect();
  84269. }
  84270. this.addEffect(this._sharpenEffect);
  84271. this._setAutoClearAndTextureSharing(this.sharpen);
  84272. }
  84273. if (this.grainEnabled) {
  84274. if (!this.grain.isReady()) {
  84275. this.grain.updateEffect();
  84276. }
  84277. this.addEffect(this._grainEffect);
  84278. this._setAutoClearAndTextureSharing(this.grain);
  84279. }
  84280. if (this.chromaticAberrationEnabled) {
  84281. if (!this.chromaticAberration.isReady()) {
  84282. this.chromaticAberration.updateEffect();
  84283. }
  84284. this.addEffect(this._chromaticAberrationEffect);
  84285. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  84286. }
  84287. if (this.fxaaEnabled) {
  84288. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84289. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  84290. this._setAutoClearAndTextureSharing(this.fxaa, true);
  84291. }
  84292. if (this._cameras !== null) {
  84293. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84294. }
  84295. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  84296. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84297. }
  84298. };
  84299. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  84300. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  84301. for (var i = 0; i < this._cameras.length; i++) {
  84302. var camera = this._cameras[i];
  84303. if (this.imageProcessing) {
  84304. this.imageProcessing.dispose(camera);
  84305. }
  84306. if (this.fxaa) {
  84307. this.fxaa.dispose(camera);
  84308. }
  84309. // These are created in the constructor and should not be disposed on every pipeline change
  84310. if (disposeNonRecreated) {
  84311. if (this.sharpen) {
  84312. this.sharpen.dispose(camera);
  84313. }
  84314. if (this.depthOfField) {
  84315. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84316. this.depthOfField.disposeEffects(camera);
  84317. }
  84318. if (this.bloom) {
  84319. this.bloom.disposeEffects(camera);
  84320. }
  84321. if (this.chromaticAberration) {
  84322. this.chromaticAberration.dispose(camera);
  84323. }
  84324. if (this.grain) {
  84325. this.grain.dispose(camera);
  84326. }
  84327. if (this._glowLayer) {
  84328. this._glowLayer.dispose();
  84329. }
  84330. }
  84331. }
  84332. this.imageProcessing = null;
  84333. this.fxaa = null;
  84334. if (disposeNonRecreated) {
  84335. this.sharpen = null;
  84336. this._sharpenEffect = null;
  84337. this.depthOfField = null;
  84338. this.bloom = null;
  84339. this.chromaticAberration = null;
  84340. this._chromaticAberrationEffect = null;
  84341. this.grain = null;
  84342. this._grainEffect = null;
  84343. this._glowLayer = null;
  84344. }
  84345. };
  84346. /**
  84347. * Adds a camera to the pipeline
  84348. * @param camera the camera to be added
  84349. */
  84350. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  84351. this._camerasToBeAttached.push(camera);
  84352. this._buildPipeline();
  84353. };
  84354. /**
  84355. * Removes a camera from the pipeline
  84356. * @param camera the camera to remove
  84357. */
  84358. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  84359. var index = this._camerasToBeAttached.indexOf(camera);
  84360. this._camerasToBeAttached.splice(index, 1);
  84361. this._buildPipeline();
  84362. };
  84363. /**
  84364. * Dispose of the pipeline and stop all post processes
  84365. */
  84366. DefaultRenderingPipeline.prototype.dispose = function () {
  84367. this._disposePostProcesses(true);
  84368. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84369. this._scene.autoClear = true;
  84370. if (this._resizeObserver) {
  84371. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  84372. this._resizeObserver = null;
  84373. }
  84374. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  84375. _super.prototype.dispose.call(this);
  84376. };
  84377. /**
  84378. * Serialize the rendering pipeline (Used when exporting)
  84379. * @returns the serialized object
  84380. */
  84381. DefaultRenderingPipeline.prototype.serialize = function () {
  84382. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84383. serializationObject.customType = "DefaultRenderingPipeline";
  84384. return serializationObject;
  84385. };
  84386. /**
  84387. * Parse the serialized pipeline
  84388. * @param source Source pipeline.
  84389. * @param scene The scene to load the pipeline to.
  84390. * @param rootUrl The URL of the serialized pipeline.
  84391. * @returns An instantiated pipeline from the serialized object.
  84392. */
  84393. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84394. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  84395. };
  84396. __decorate([
  84397. BABYLON.serialize()
  84398. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  84399. __decorate([
  84400. BABYLON.serialize()
  84401. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  84402. __decorate([
  84403. BABYLON.serialize()
  84404. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  84405. __decorate([
  84406. BABYLON.serialize()
  84407. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  84408. __decorate([
  84409. BABYLON.serialize()
  84410. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  84411. __decorate([
  84412. BABYLON.serialize()
  84413. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  84414. __decorate([
  84415. BABYLON.serialize()
  84416. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  84417. __decorate([
  84418. BABYLON.serialize()
  84419. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  84420. __decorate([
  84421. BABYLON.serialize()
  84422. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  84423. __decorate([
  84424. BABYLON.serialize()
  84425. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  84426. __decorate([
  84427. BABYLON.serialize()
  84428. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  84429. __decorate([
  84430. BABYLON.serialize()
  84431. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  84432. __decorate([
  84433. BABYLON.serialize()
  84434. ], DefaultRenderingPipeline.prototype, "samples", null);
  84435. __decorate([
  84436. BABYLON.serialize()
  84437. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  84438. __decorate([
  84439. BABYLON.serialize()
  84440. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  84441. __decorate([
  84442. BABYLON.serialize()
  84443. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  84444. __decorate([
  84445. BABYLON.serialize()
  84446. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  84447. return DefaultRenderingPipeline;
  84448. }(BABYLON.PostProcessRenderPipeline));
  84449. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  84450. })(BABYLON || (BABYLON = {}));
  84451. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  84452. var BABYLON;
  84453. (function (BABYLON) {
  84454. /**
  84455. * @hidden
  84456. */
  84457. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  84458. __extends(ImageProcessingConfigurationDefines, _super);
  84459. function ImageProcessingConfigurationDefines() {
  84460. var _this = _super.call(this) || this;
  84461. _this.IMAGEPROCESSING = false;
  84462. _this.VIGNETTE = false;
  84463. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84464. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84465. _this.TONEMAPPING = false;
  84466. _this.TONEMAPPING_ACES = false;
  84467. _this.CONTRAST = false;
  84468. _this.COLORCURVES = false;
  84469. _this.COLORGRADING = false;
  84470. _this.COLORGRADING3D = false;
  84471. _this.SAMPLER3DGREENDEPTH = false;
  84472. _this.SAMPLER3DBGRMAP = false;
  84473. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84474. _this.EXPOSURE = false;
  84475. _this.rebuild();
  84476. return _this;
  84477. }
  84478. return ImageProcessingConfigurationDefines;
  84479. }(BABYLON.MaterialDefines));
  84480. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  84481. /**
  84482. * This groups together the common properties used for image processing either in direct forward pass
  84483. * or through post processing effect depending on the use of the image processing pipeline in your scene
  84484. * or not.
  84485. */
  84486. var ImageProcessingConfiguration = /** @class */ (function () {
  84487. function ImageProcessingConfiguration() {
  84488. /**
  84489. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  84490. */
  84491. this.colorCurves = new BABYLON.ColorCurves();
  84492. this._colorCurvesEnabled = false;
  84493. this._colorGradingEnabled = false;
  84494. this._colorGradingWithGreenDepth = true;
  84495. this._colorGradingBGR = true;
  84496. /** @hidden */
  84497. this._exposure = 1.0;
  84498. this._toneMappingEnabled = false;
  84499. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  84500. this._contrast = 1.0;
  84501. /**
  84502. * Vignette stretch size.
  84503. */
  84504. this.vignetteStretch = 0;
  84505. /**
  84506. * Vignette centre X Offset.
  84507. */
  84508. this.vignetteCentreX = 0;
  84509. /**
  84510. * Vignette centre Y Offset.
  84511. */
  84512. this.vignetteCentreY = 0;
  84513. /**
  84514. * Vignette weight or intensity of the vignette effect.
  84515. */
  84516. this.vignetteWeight = 1.5;
  84517. /**
  84518. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84519. * if vignetteEnabled is set to true.
  84520. */
  84521. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84522. /**
  84523. * Camera field of view used by the Vignette effect.
  84524. */
  84525. this.vignetteCameraFov = 0.5;
  84526. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  84527. this._vignetteEnabled = false;
  84528. this._applyByPostProcess = false;
  84529. this._isEnabled = true;
  84530. /**
  84531. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  84532. */
  84533. this.onUpdateParameters = new BABYLON.Observable();
  84534. }
  84535. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84536. /**
  84537. * Gets wether the color curves effect is enabled.
  84538. */
  84539. get: function () {
  84540. return this._colorCurvesEnabled;
  84541. },
  84542. /**
  84543. * Sets wether the color curves effect is enabled.
  84544. */
  84545. set: function (value) {
  84546. if (this._colorCurvesEnabled === value) {
  84547. return;
  84548. }
  84549. this._colorCurvesEnabled = value;
  84550. this._updateParameters();
  84551. },
  84552. enumerable: true,
  84553. configurable: true
  84554. });
  84555. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84556. /**
  84557. * Gets wether the color grading effect is enabled.
  84558. */
  84559. get: function () {
  84560. return this._colorGradingEnabled;
  84561. },
  84562. /**
  84563. * Sets wether the color grading effect is enabled.
  84564. */
  84565. set: function (value) {
  84566. if (this._colorGradingEnabled === value) {
  84567. return;
  84568. }
  84569. this._colorGradingEnabled = value;
  84570. this._updateParameters();
  84571. },
  84572. enumerable: true,
  84573. configurable: true
  84574. });
  84575. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84576. /**
  84577. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84578. */
  84579. get: function () {
  84580. return this._colorGradingWithGreenDepth;
  84581. },
  84582. /**
  84583. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84584. */
  84585. set: function (value) {
  84586. if (this._colorGradingWithGreenDepth === value) {
  84587. return;
  84588. }
  84589. this._colorGradingWithGreenDepth = value;
  84590. this._updateParameters();
  84591. },
  84592. enumerable: true,
  84593. configurable: true
  84594. });
  84595. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84596. /**
  84597. * Gets wether the color grading texture contains BGR values.
  84598. */
  84599. get: function () {
  84600. return this._colorGradingBGR;
  84601. },
  84602. /**
  84603. * Sets wether the color grading texture contains BGR values.
  84604. */
  84605. set: function (value) {
  84606. if (this._colorGradingBGR === value) {
  84607. return;
  84608. }
  84609. this._colorGradingBGR = value;
  84610. this._updateParameters();
  84611. },
  84612. enumerable: true,
  84613. configurable: true
  84614. });
  84615. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84616. /**
  84617. * Gets the Exposure used in the effect.
  84618. */
  84619. get: function () {
  84620. return this._exposure;
  84621. },
  84622. /**
  84623. * Sets the Exposure used in the effect.
  84624. */
  84625. set: function (value) {
  84626. if (this._exposure === value) {
  84627. return;
  84628. }
  84629. this._exposure = value;
  84630. this._updateParameters();
  84631. },
  84632. enumerable: true,
  84633. configurable: true
  84634. });
  84635. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84636. /**
  84637. * Gets wether the tone mapping effect is enabled.
  84638. */
  84639. get: function () {
  84640. return this._toneMappingEnabled;
  84641. },
  84642. /**
  84643. * Sets wether the tone mapping effect is enabled.
  84644. */
  84645. set: function (value) {
  84646. if (this._toneMappingEnabled === value) {
  84647. return;
  84648. }
  84649. this._toneMappingEnabled = value;
  84650. this._updateParameters();
  84651. },
  84652. enumerable: true,
  84653. configurable: true
  84654. });
  84655. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84656. /**
  84657. * Gets the type of tone mapping effect.
  84658. */
  84659. get: function () {
  84660. return this._toneMappingType;
  84661. },
  84662. /**
  84663. * Sets the type of tone mapping effect used in BabylonJS.
  84664. */
  84665. set: function (value) {
  84666. if (this._toneMappingType === value) {
  84667. return;
  84668. }
  84669. this._toneMappingType = value;
  84670. this._updateParameters();
  84671. },
  84672. enumerable: true,
  84673. configurable: true
  84674. });
  84675. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  84676. /**
  84677. * Gets the contrast used in the effect.
  84678. */
  84679. get: function () {
  84680. return this._contrast;
  84681. },
  84682. /**
  84683. * Sets the contrast used in the effect.
  84684. */
  84685. set: function (value) {
  84686. if (this._contrast === value) {
  84687. return;
  84688. }
  84689. this._contrast = value;
  84690. this._updateParameters();
  84691. },
  84692. enumerable: true,
  84693. configurable: true
  84694. });
  84695. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  84696. /**
  84697. * Gets the vignette blend mode allowing different kind of effect.
  84698. */
  84699. get: function () {
  84700. return this._vignetteBlendMode;
  84701. },
  84702. /**
  84703. * Sets the vignette blend mode allowing different kind of effect.
  84704. */
  84705. set: function (value) {
  84706. if (this._vignetteBlendMode === value) {
  84707. return;
  84708. }
  84709. this._vignetteBlendMode = value;
  84710. this._updateParameters();
  84711. },
  84712. enumerable: true,
  84713. configurable: true
  84714. });
  84715. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  84716. /**
  84717. * Gets wether the vignette effect is enabled.
  84718. */
  84719. get: function () {
  84720. return this._vignetteEnabled;
  84721. },
  84722. /**
  84723. * Sets wether the vignette effect is enabled.
  84724. */
  84725. set: function (value) {
  84726. if (this._vignetteEnabled === value) {
  84727. return;
  84728. }
  84729. this._vignetteEnabled = value;
  84730. this._updateParameters();
  84731. },
  84732. enumerable: true,
  84733. configurable: true
  84734. });
  84735. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  84736. /**
  84737. * Gets wether the image processing is applied through a post process or not.
  84738. */
  84739. get: function () {
  84740. return this._applyByPostProcess;
  84741. },
  84742. /**
  84743. * Sets wether the image processing is applied through a post process or not.
  84744. */
  84745. set: function (value) {
  84746. if (this._applyByPostProcess === value) {
  84747. return;
  84748. }
  84749. this._applyByPostProcess = value;
  84750. this._updateParameters();
  84751. },
  84752. enumerable: true,
  84753. configurable: true
  84754. });
  84755. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  84756. /**
  84757. * Gets wether the image processing is enabled or not.
  84758. */
  84759. get: function () {
  84760. return this._isEnabled;
  84761. },
  84762. /**
  84763. * Sets wether the image processing is enabled or not.
  84764. */
  84765. set: function (value) {
  84766. if (this._isEnabled === value) {
  84767. return;
  84768. }
  84769. this._isEnabled = value;
  84770. this._updateParameters();
  84771. },
  84772. enumerable: true,
  84773. configurable: true
  84774. });
  84775. /**
  84776. * Method called each time the image processing information changes requires to recompile the effect.
  84777. */
  84778. ImageProcessingConfiguration.prototype._updateParameters = function () {
  84779. this.onUpdateParameters.notifyObservers(this);
  84780. };
  84781. ImageProcessingConfiguration.prototype.getClassName = function () {
  84782. return "ImageProcessingConfiguration";
  84783. };
  84784. /**
  84785. * Prepare the list of uniforms associated with the Image Processing effects.
  84786. * @param uniformsList The list of uniforms used in the effect
  84787. * @param defines the list of defines currently in use
  84788. */
  84789. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  84790. if (defines.EXPOSURE) {
  84791. uniforms.push("exposureLinear");
  84792. }
  84793. if (defines.CONTRAST) {
  84794. uniforms.push("contrast");
  84795. }
  84796. if (defines.COLORGRADING) {
  84797. uniforms.push("colorTransformSettings");
  84798. }
  84799. if (defines.VIGNETTE) {
  84800. uniforms.push("vInverseScreenSize");
  84801. uniforms.push("vignetteSettings1");
  84802. uniforms.push("vignetteSettings2");
  84803. }
  84804. if (defines.COLORCURVES) {
  84805. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  84806. }
  84807. };
  84808. /**
  84809. * Prepare the list of samplers associated with the Image Processing effects.
  84810. * @param uniformsList The list of uniforms used in the effect
  84811. * @param defines the list of defines currently in use
  84812. */
  84813. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  84814. if (defines.COLORGRADING) {
  84815. samplersList.push("txColorTransform");
  84816. }
  84817. };
  84818. /**
  84819. * Prepare the list of defines associated to the shader.
  84820. * @param defines the list of defines to complete
  84821. */
  84822. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  84823. if (forPostProcess === void 0) { forPostProcess = false; }
  84824. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  84825. defines.VIGNETTE = false;
  84826. defines.TONEMAPPING = false;
  84827. defines.TONEMAPPING_ACES = false;
  84828. defines.CONTRAST = false;
  84829. defines.EXPOSURE = false;
  84830. defines.COLORCURVES = false;
  84831. defines.COLORGRADING = false;
  84832. defines.COLORGRADING3D = false;
  84833. defines.IMAGEPROCESSING = false;
  84834. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  84835. return;
  84836. }
  84837. defines.VIGNETTE = this.vignetteEnabled;
  84838. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  84839. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  84840. defines.TONEMAPPING = this.toneMappingEnabled;
  84841. switch (this._toneMappingType) {
  84842. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  84843. defines.TONEMAPPING_ACES = true;
  84844. break;
  84845. }
  84846. defines.CONTRAST = (this.contrast !== 1.0);
  84847. defines.EXPOSURE = (this.exposure !== 1.0);
  84848. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  84849. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  84850. if (defines.COLORGRADING) {
  84851. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  84852. }
  84853. else {
  84854. defines.COLORGRADING3D = false;
  84855. }
  84856. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  84857. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  84858. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  84859. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  84860. };
  84861. /**
  84862. * Returns true if all the image processing information are ready.
  84863. */
  84864. ImageProcessingConfiguration.prototype.isReady = function () {
  84865. // Color Grading texure can not be none blocking.
  84866. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  84867. };
  84868. /**
  84869. * Binds the image processing to the shader.
  84870. * @param effect The effect to bind to
  84871. */
  84872. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  84873. if (aspectRatio === void 0) { aspectRatio = 1; }
  84874. // Color Curves
  84875. if (this._colorCurvesEnabled && this.colorCurves) {
  84876. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  84877. }
  84878. // Vignette
  84879. if (this._vignetteEnabled) {
  84880. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  84881. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  84882. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  84883. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  84884. var vignetteScaleX = vignetteScaleY * aspectRatio;
  84885. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  84886. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  84887. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  84888. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  84889. var vignettePower = -2.0 * this.vignetteWeight;
  84890. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  84891. }
  84892. // Exposure
  84893. effect.setFloat("exposureLinear", this.exposure);
  84894. // Contrast
  84895. effect.setFloat("contrast", this.contrast);
  84896. // Color transform settings
  84897. if (this.colorGradingTexture) {
  84898. effect.setTexture("txColorTransform", this.colorGradingTexture);
  84899. var textureSize = this.colorGradingTexture.getSize().height;
  84900. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  84901. 0.5 / textureSize, // textureOffset
  84902. textureSize, // textureSize
  84903. this.colorGradingTexture.level // weight
  84904. );
  84905. }
  84906. };
  84907. /**
  84908. * Clones the current image processing instance.
  84909. * @return The cloned image processing
  84910. */
  84911. ImageProcessingConfiguration.prototype.clone = function () {
  84912. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84913. };
  84914. /**
  84915. * Serializes the current image processing instance to a json representation.
  84916. * @return a JSON representation
  84917. */
  84918. ImageProcessingConfiguration.prototype.serialize = function () {
  84919. return BABYLON.SerializationHelper.Serialize(this);
  84920. };
  84921. /**
  84922. * Parses the image processing from a json representation.
  84923. * @param source the JSON source to parse
  84924. * @return The parsed image processing
  84925. */
  84926. ImageProcessingConfiguration.Parse = function (source) {
  84927. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84928. };
  84929. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84930. /**
  84931. * Used to apply the vignette as a mix with the pixel color.
  84932. */
  84933. get: function () {
  84934. return this._VIGNETTEMODE_MULTIPLY;
  84935. },
  84936. enumerable: true,
  84937. configurable: true
  84938. });
  84939. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84940. /**
  84941. * Used to apply the vignette as a replacement of the pixel color.
  84942. */
  84943. get: function () {
  84944. return this._VIGNETTEMODE_OPAQUE;
  84945. },
  84946. enumerable: true,
  84947. configurable: true
  84948. });
  84949. /**
  84950. * Default tone mapping applied in BabylonJS.
  84951. */
  84952. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84953. /**
  84954. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84955. * to other engines rendering to increase portability.
  84956. */
  84957. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84958. // Static constants associated to the image processing.
  84959. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84960. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84961. __decorate([
  84962. BABYLON.serializeAsColorCurves()
  84963. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84964. __decorate([
  84965. BABYLON.serialize()
  84966. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84967. __decorate([
  84968. BABYLON.serializeAsTexture()
  84969. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84970. __decorate([
  84971. BABYLON.serialize()
  84972. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84973. __decorate([
  84974. BABYLON.serialize()
  84975. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84976. __decorate([
  84977. BABYLON.serialize()
  84978. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84979. __decorate([
  84980. BABYLON.serialize()
  84981. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84982. __decorate([
  84983. BABYLON.serialize()
  84984. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84985. __decorate([
  84986. BABYLON.serialize()
  84987. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84988. __decorate([
  84989. BABYLON.serialize()
  84990. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84991. __decorate([
  84992. BABYLON.serialize()
  84993. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84994. __decorate([
  84995. BABYLON.serialize()
  84996. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84997. __decorate([
  84998. BABYLON.serialize()
  84999. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  85000. __decorate([
  85001. BABYLON.serialize()
  85002. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  85003. __decorate([
  85004. BABYLON.serializeAsColor4()
  85005. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  85006. __decorate([
  85007. BABYLON.serialize()
  85008. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  85009. __decorate([
  85010. BABYLON.serialize()
  85011. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  85012. __decorate([
  85013. BABYLON.serialize()
  85014. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  85015. __decorate([
  85016. BABYLON.serialize()
  85017. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  85018. __decorate([
  85019. BABYLON.serialize()
  85020. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  85021. return ImageProcessingConfiguration;
  85022. }());
  85023. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  85024. })(BABYLON || (BABYLON = {}));
  85025. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  85026. var BABYLON;
  85027. (function (BABYLON) {
  85028. /**
  85029. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  85030. * It can help converting any input color in a desired output one. This can then be used to create effects
  85031. * from sepia, black and white to sixties or futuristic rendering...
  85032. *
  85033. * The only supported format is currently 3dl.
  85034. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  85035. */
  85036. var ColorGradingTexture = /** @class */ (function (_super) {
  85037. __extends(ColorGradingTexture, _super);
  85038. /**
  85039. * Instantiates a ColorGradingTexture from the following parameters.
  85040. *
  85041. * @param url The location of the color gradind data (currently only supporting 3dl)
  85042. * @param scene The scene the texture will be used in
  85043. */
  85044. function ColorGradingTexture(url, scene) {
  85045. var _this = _super.call(this, scene) || this;
  85046. if (!url) {
  85047. return _this;
  85048. }
  85049. _this._engine = scene.getEngine();
  85050. _this._textureMatrix = BABYLON.Matrix.Identity();
  85051. _this.name = url;
  85052. _this.url = url;
  85053. _this.hasAlpha = false;
  85054. _this.isCube = false;
  85055. _this.is3D = _this._engine.webGLVersion > 1;
  85056. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85057. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85058. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85059. _this.anisotropicFilteringLevel = 1;
  85060. _this._texture = _this._getFromCache(url, true);
  85061. if (!_this._texture) {
  85062. if (!scene.useDelayedTextureLoading) {
  85063. _this.loadTexture();
  85064. }
  85065. else {
  85066. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85067. }
  85068. }
  85069. return _this;
  85070. }
  85071. /**
  85072. * Returns the texture matrix used in most of the material.
  85073. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  85074. */
  85075. ColorGradingTexture.prototype.getTextureMatrix = function () {
  85076. return this._textureMatrix;
  85077. };
  85078. /**
  85079. * Occurs when the file being loaded is a .3dl LUT file.
  85080. */
  85081. ColorGradingTexture.prototype.load3dlTexture = function () {
  85082. var engine = this._engine;
  85083. var texture;
  85084. if (engine.webGLVersion === 1) {
  85085. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85086. }
  85087. else {
  85088. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85089. }
  85090. this._texture = texture;
  85091. var callback = function (text) {
  85092. if (typeof text !== "string") {
  85093. return;
  85094. }
  85095. var data = null;
  85096. var tempData = null;
  85097. var line;
  85098. var lines = text.split('\n');
  85099. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  85100. var maxColor = 0;
  85101. for (var i = 0; i < lines.length; i++) {
  85102. line = lines[i];
  85103. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  85104. continue;
  85105. if (line.indexOf('#') === 0)
  85106. continue;
  85107. var words = line.split(" ");
  85108. if (size === 0) {
  85109. // Number of space + one
  85110. size = words.length;
  85111. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  85112. tempData = new Float32Array(size * size * size * 4);
  85113. continue;
  85114. }
  85115. if (size != 0) {
  85116. var r = Math.max(parseInt(words[0]), 0);
  85117. var g = Math.max(parseInt(words[1]), 0);
  85118. var b = Math.max(parseInt(words[2]), 0);
  85119. maxColor = Math.max(r, maxColor);
  85120. maxColor = Math.max(g, maxColor);
  85121. maxColor = Math.max(b, maxColor);
  85122. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  85123. if (tempData) {
  85124. tempData[pixelStorageIndex + 0] = r;
  85125. tempData[pixelStorageIndex + 1] = g;
  85126. tempData[pixelStorageIndex + 2] = b;
  85127. }
  85128. pixelIndexSlice++;
  85129. if (pixelIndexSlice % size == 0) {
  85130. pixelIndexH++;
  85131. pixelIndexSlice = 0;
  85132. if (pixelIndexH % size == 0) {
  85133. pixelIndexW++;
  85134. pixelIndexH = 0;
  85135. }
  85136. }
  85137. }
  85138. }
  85139. if (tempData && data) {
  85140. for (var i = 0; i < tempData.length; i++) {
  85141. if (i > 0 && (i + 1) % 4 === 0) {
  85142. data[i] = 255;
  85143. }
  85144. else {
  85145. var value = tempData[i];
  85146. data[i] = (value / maxColor * 255);
  85147. }
  85148. }
  85149. }
  85150. if (texture.is3D) {
  85151. texture.updateSize(size, size, size);
  85152. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85153. }
  85154. else {
  85155. texture.updateSize(size * size, size);
  85156. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85157. }
  85158. };
  85159. var scene = this.getScene();
  85160. if (scene) {
  85161. scene._loadFile(this.url, callback);
  85162. }
  85163. else {
  85164. this._engine._loadFile(this.url, callback);
  85165. }
  85166. return this._texture;
  85167. };
  85168. /**
  85169. * Starts the loading process of the texture.
  85170. */
  85171. ColorGradingTexture.prototype.loadTexture = function () {
  85172. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  85173. this.load3dlTexture();
  85174. }
  85175. };
  85176. /**
  85177. * Clones the color gradind texture.
  85178. */
  85179. ColorGradingTexture.prototype.clone = function () {
  85180. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  85181. // Base texture
  85182. newTexture.level = this.level;
  85183. return newTexture;
  85184. };
  85185. /**
  85186. * Called during delayed load for textures.
  85187. */
  85188. ColorGradingTexture.prototype.delayLoad = function () {
  85189. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85190. return;
  85191. }
  85192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85193. this._texture = this._getFromCache(this.url, true);
  85194. if (!this._texture) {
  85195. this.loadTexture();
  85196. }
  85197. };
  85198. /**
  85199. * Parses a color grading texture serialized by Babylon.
  85200. * @param parsedTexture The texture information being parsedTexture
  85201. * @param scene The scene to load the texture in
  85202. * @param rootUrl The root url of the data assets to load
  85203. * @return A color gradind texture
  85204. */
  85205. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85206. var texture = null;
  85207. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85208. texture = new ColorGradingTexture(parsedTexture.name, scene);
  85209. texture.name = parsedTexture.name;
  85210. texture.level = parsedTexture.level;
  85211. }
  85212. return texture;
  85213. };
  85214. /**
  85215. * Serializes the LUT texture to json format.
  85216. */
  85217. ColorGradingTexture.prototype.serialize = function () {
  85218. if (!this.name) {
  85219. return null;
  85220. }
  85221. var serializationObject = {};
  85222. serializationObject.name = this.name;
  85223. serializationObject.level = this.level;
  85224. serializationObject.customType = "BABYLON.ColorGradingTexture";
  85225. return serializationObject;
  85226. };
  85227. /**
  85228. * Empty line regex stored for GC.
  85229. */
  85230. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  85231. return ColorGradingTexture;
  85232. }(BABYLON.BaseTexture));
  85233. BABYLON.ColorGradingTexture = ColorGradingTexture;
  85234. })(BABYLON || (BABYLON = {}));
  85235. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  85236. var BABYLON;
  85237. (function (BABYLON) {
  85238. /**
  85239. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85240. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85241. * 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;
  85242. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85243. */
  85244. var ColorCurves = /** @class */ (function () {
  85245. function ColorCurves() {
  85246. this._dirty = true;
  85247. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  85248. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  85249. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85250. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  85251. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85252. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  85253. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  85254. this._globalHue = 30;
  85255. this._globalDensity = 0;
  85256. this._globalSaturation = 0;
  85257. this._globalExposure = 0;
  85258. this._highlightsHue = 30;
  85259. this._highlightsDensity = 0;
  85260. this._highlightsSaturation = 0;
  85261. this._highlightsExposure = 0;
  85262. this._midtonesHue = 30;
  85263. this._midtonesDensity = 0;
  85264. this._midtonesSaturation = 0;
  85265. this._midtonesExposure = 0;
  85266. this._shadowsHue = 30;
  85267. this._shadowsDensity = 0;
  85268. this._shadowsSaturation = 0;
  85269. this._shadowsExposure = 0;
  85270. }
  85271. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  85272. /**
  85273. * Gets the global Hue value.
  85274. * 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).
  85275. */
  85276. get: function () {
  85277. return this._globalHue;
  85278. },
  85279. /**
  85280. * Sets the global Hue value.
  85281. * 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).
  85282. */
  85283. set: function (value) {
  85284. this._globalHue = value;
  85285. this._dirty = true;
  85286. },
  85287. enumerable: true,
  85288. configurable: true
  85289. });
  85290. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  85291. /**
  85292. * Gets the global Density value.
  85293. * 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.
  85294. * Values less than zero provide a filter of opposite hue.
  85295. */
  85296. get: function () {
  85297. return this._globalDensity;
  85298. },
  85299. /**
  85300. * Sets the global Density value.
  85301. * 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.
  85302. * Values less than zero provide a filter of opposite hue.
  85303. */
  85304. set: function (value) {
  85305. this._globalDensity = value;
  85306. this._dirty = true;
  85307. },
  85308. enumerable: true,
  85309. configurable: true
  85310. });
  85311. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  85312. /**
  85313. * Gets the global Saturation value.
  85314. * 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.
  85315. */
  85316. get: function () {
  85317. return this._globalSaturation;
  85318. },
  85319. /**
  85320. * Sets the global Saturation value.
  85321. * 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.
  85322. */
  85323. set: function (value) {
  85324. this._globalSaturation = value;
  85325. this._dirty = true;
  85326. },
  85327. enumerable: true,
  85328. configurable: true
  85329. });
  85330. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  85331. /**
  85332. * Gets the global Exposure value.
  85333. * 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.
  85334. */
  85335. get: function () {
  85336. return this._globalExposure;
  85337. },
  85338. /**
  85339. * Sets the global Exposure value.
  85340. * 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.
  85341. */
  85342. set: function (value) {
  85343. this._globalExposure = value;
  85344. this._dirty = true;
  85345. },
  85346. enumerable: true,
  85347. configurable: true
  85348. });
  85349. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  85350. /**
  85351. * Gets the highlights Hue value.
  85352. * 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).
  85353. */
  85354. get: function () {
  85355. return this._highlightsHue;
  85356. },
  85357. /**
  85358. * Sets the highlights Hue value.
  85359. * 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).
  85360. */
  85361. set: function (value) {
  85362. this._highlightsHue = value;
  85363. this._dirty = true;
  85364. },
  85365. enumerable: true,
  85366. configurable: true
  85367. });
  85368. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  85369. /**
  85370. * Gets the highlights Density value.
  85371. * 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.
  85372. * Values less than zero provide a filter of opposite hue.
  85373. */
  85374. get: function () {
  85375. return this._highlightsDensity;
  85376. },
  85377. /**
  85378. * Sets the highlights Density value.
  85379. * 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.
  85380. * Values less than zero provide a filter of opposite hue.
  85381. */
  85382. set: function (value) {
  85383. this._highlightsDensity = value;
  85384. this._dirty = true;
  85385. },
  85386. enumerable: true,
  85387. configurable: true
  85388. });
  85389. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  85390. /**
  85391. * Gets the highlights Saturation value.
  85392. * 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.
  85393. */
  85394. get: function () {
  85395. return this._highlightsSaturation;
  85396. },
  85397. /**
  85398. * Sets the highlights Saturation value.
  85399. * 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.
  85400. */
  85401. set: function (value) {
  85402. this._highlightsSaturation = value;
  85403. this._dirty = true;
  85404. },
  85405. enumerable: true,
  85406. configurable: true
  85407. });
  85408. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  85409. /**
  85410. * Gets the highlights Exposure value.
  85411. * 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.
  85412. */
  85413. get: function () {
  85414. return this._highlightsExposure;
  85415. },
  85416. /**
  85417. * Sets the highlights Exposure value.
  85418. * 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.
  85419. */
  85420. set: function (value) {
  85421. this._highlightsExposure = value;
  85422. this._dirty = true;
  85423. },
  85424. enumerable: true,
  85425. configurable: true
  85426. });
  85427. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  85428. /**
  85429. * Gets the midtones Hue value.
  85430. * 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).
  85431. */
  85432. get: function () {
  85433. return this._midtonesHue;
  85434. },
  85435. /**
  85436. * Sets the midtones Hue value.
  85437. * 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).
  85438. */
  85439. set: function (value) {
  85440. this._midtonesHue = value;
  85441. this._dirty = true;
  85442. },
  85443. enumerable: true,
  85444. configurable: true
  85445. });
  85446. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  85447. /**
  85448. * Gets the midtones Density value.
  85449. * 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.
  85450. * Values less than zero provide a filter of opposite hue.
  85451. */
  85452. get: function () {
  85453. return this._midtonesDensity;
  85454. },
  85455. /**
  85456. * Sets the midtones Density value.
  85457. * 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.
  85458. * Values less than zero provide a filter of opposite hue.
  85459. */
  85460. set: function (value) {
  85461. this._midtonesDensity = value;
  85462. this._dirty = true;
  85463. },
  85464. enumerable: true,
  85465. configurable: true
  85466. });
  85467. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  85468. /**
  85469. * Gets the midtones Saturation value.
  85470. * 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.
  85471. */
  85472. get: function () {
  85473. return this._midtonesSaturation;
  85474. },
  85475. /**
  85476. * Sets the midtones Saturation value.
  85477. * 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.
  85478. */
  85479. set: function (value) {
  85480. this._midtonesSaturation = value;
  85481. this._dirty = true;
  85482. },
  85483. enumerable: true,
  85484. configurable: true
  85485. });
  85486. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  85487. /**
  85488. * Gets the midtones Exposure value.
  85489. * 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.
  85490. */
  85491. get: function () {
  85492. return this._midtonesExposure;
  85493. },
  85494. /**
  85495. * Sets the midtones Exposure value.
  85496. * 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.
  85497. */
  85498. set: function (value) {
  85499. this._midtonesExposure = value;
  85500. this._dirty = true;
  85501. },
  85502. enumerable: true,
  85503. configurable: true
  85504. });
  85505. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  85506. /**
  85507. * Gets the shadows Hue value.
  85508. * 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).
  85509. */
  85510. get: function () {
  85511. return this._shadowsHue;
  85512. },
  85513. /**
  85514. * Sets the shadows Hue value.
  85515. * 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).
  85516. */
  85517. set: function (value) {
  85518. this._shadowsHue = value;
  85519. this._dirty = true;
  85520. },
  85521. enumerable: true,
  85522. configurable: true
  85523. });
  85524. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  85525. /**
  85526. * Gets the shadows Density value.
  85527. * 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.
  85528. * Values less than zero provide a filter of opposite hue.
  85529. */
  85530. get: function () {
  85531. return this._shadowsDensity;
  85532. },
  85533. /**
  85534. * Sets the shadows Density value.
  85535. * 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.
  85536. * Values less than zero provide a filter of opposite hue.
  85537. */
  85538. set: function (value) {
  85539. this._shadowsDensity = value;
  85540. this._dirty = true;
  85541. },
  85542. enumerable: true,
  85543. configurable: true
  85544. });
  85545. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85546. /**
  85547. * Gets the shadows Saturation value.
  85548. * 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.
  85549. */
  85550. get: function () {
  85551. return this._shadowsSaturation;
  85552. },
  85553. /**
  85554. * Sets the shadows Saturation value.
  85555. * 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.
  85556. */
  85557. set: function (value) {
  85558. this._shadowsSaturation = value;
  85559. this._dirty = true;
  85560. },
  85561. enumerable: true,
  85562. configurable: true
  85563. });
  85564. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85565. /**
  85566. * Gets the shadows Exposure value.
  85567. * 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.
  85568. */
  85569. get: function () {
  85570. return this._shadowsExposure;
  85571. },
  85572. /**
  85573. * Sets the shadows Exposure value.
  85574. * 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.
  85575. */
  85576. set: function (value) {
  85577. this._shadowsExposure = value;
  85578. this._dirty = true;
  85579. },
  85580. enumerable: true,
  85581. configurable: true
  85582. });
  85583. ColorCurves.prototype.getClassName = function () {
  85584. return "ColorCurves";
  85585. };
  85586. /**
  85587. * Binds the color curves to the shader.
  85588. * @param colorCurves The color curve to bind
  85589. * @param effect The effect to bind to
  85590. */
  85591. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85592. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85593. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85594. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85595. if (colorCurves._dirty) {
  85596. colorCurves._dirty = false;
  85597. // Fill in global info.
  85598. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85599. // Compute highlights info.
  85600. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85601. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85602. // Compute midtones info.
  85603. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85604. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85605. // Compute shadows info.
  85606. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85607. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85608. // Compute deltas (neutral is midtones).
  85609. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85610. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85611. }
  85612. if (effect) {
  85613. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85614. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85615. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85616. }
  85617. };
  85618. /**
  85619. * Prepare the list of uniforms associated with the ColorCurves effects.
  85620. * @param uniformsList The list of uniforms used in the effect
  85621. */
  85622. ColorCurves.PrepareUniforms = function (uniformsList) {
  85623. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85624. };
  85625. /**
  85626. * Returns color grading data based on a hue, density, saturation and exposure value.
  85627. * @param filterHue The hue of the color filter.
  85628. * @param filterDensity The density of the color filter.
  85629. * @param saturation The saturation.
  85630. * @param exposure The exposure.
  85631. * @param result The result data container.
  85632. */
  85633. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85634. if (hue == null) {
  85635. return;
  85636. }
  85637. hue = ColorCurves.clamp(hue, 0, 360);
  85638. density = ColorCurves.clamp(density, -100, 100);
  85639. saturation = ColorCurves.clamp(saturation, -100, 100);
  85640. exposure = ColorCurves.clamp(exposure, -100, 100);
  85641. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85642. // so that the maximum filter density is only 50% control. This provides fine control
  85643. // for small values and reasonable range.
  85644. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85645. density *= 0.5;
  85646. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85647. if (density < 0) {
  85648. density *= -1;
  85649. hue = (hue + 180) % 360;
  85650. }
  85651. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85652. result.scaleToRef(2, result);
  85653. result.a = 1 + 0.01 * saturation;
  85654. };
  85655. /**
  85656. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  85657. * @param value The input slider value in range [-100,100].
  85658. * @returns Adjusted value.
  85659. */
  85660. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  85661. value /= 100;
  85662. var x = Math.abs(value);
  85663. x = Math.pow(x, 2);
  85664. if (value < 0) {
  85665. x *= -1;
  85666. }
  85667. x *= 100;
  85668. return x;
  85669. };
  85670. /**
  85671. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  85672. * @param hue The hue (H) input.
  85673. * @param saturation The saturation (S) input.
  85674. * @param brightness The brightness (B) input.
  85675. * @result An RGBA color represented as Vector4.
  85676. */
  85677. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  85678. var h = ColorCurves.clamp(hue, 0, 360);
  85679. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  85680. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  85681. if (s === 0) {
  85682. result.r = v;
  85683. result.g = v;
  85684. result.b = v;
  85685. }
  85686. else {
  85687. // sector 0 to 5
  85688. h /= 60;
  85689. var i = Math.floor(h);
  85690. // fractional part of h
  85691. var f = h - i;
  85692. var p = v * (1 - s);
  85693. var q = v * (1 - s * f);
  85694. var t = v * (1 - s * (1 - f));
  85695. switch (i) {
  85696. case 0:
  85697. result.r = v;
  85698. result.g = t;
  85699. result.b = p;
  85700. break;
  85701. case 1:
  85702. result.r = q;
  85703. result.g = v;
  85704. result.b = p;
  85705. break;
  85706. case 2:
  85707. result.r = p;
  85708. result.g = v;
  85709. result.b = t;
  85710. break;
  85711. case 3:
  85712. result.r = p;
  85713. result.g = q;
  85714. result.b = v;
  85715. break;
  85716. case 4:
  85717. result.r = t;
  85718. result.g = p;
  85719. result.b = v;
  85720. break;
  85721. default: // case 5:
  85722. result.r = v;
  85723. result.g = p;
  85724. result.b = q;
  85725. break;
  85726. }
  85727. }
  85728. result.a = 1;
  85729. };
  85730. /**
  85731. * Returns a value clamped between min and max
  85732. * @param value The value to clamp
  85733. * @param min The minimum of value
  85734. * @param max The maximum of value
  85735. * @returns The clamped value.
  85736. */
  85737. ColorCurves.clamp = function (value, min, max) {
  85738. return Math.min(Math.max(value, min), max);
  85739. };
  85740. /**
  85741. * Clones the current color curve instance.
  85742. * @return The cloned curves
  85743. */
  85744. ColorCurves.prototype.clone = function () {
  85745. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  85746. };
  85747. /**
  85748. * Serializes the current color curve instance to a json representation.
  85749. * @return a JSON representation
  85750. */
  85751. ColorCurves.prototype.serialize = function () {
  85752. return BABYLON.SerializationHelper.Serialize(this);
  85753. };
  85754. /**
  85755. * Parses the color curve from a json representation.
  85756. * @param source the JSON source to parse
  85757. * @return The parsed curves
  85758. */
  85759. ColorCurves.Parse = function (source) {
  85760. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  85761. };
  85762. __decorate([
  85763. BABYLON.serialize()
  85764. ], ColorCurves.prototype, "_globalHue", void 0);
  85765. __decorate([
  85766. BABYLON.serialize()
  85767. ], ColorCurves.prototype, "_globalDensity", void 0);
  85768. __decorate([
  85769. BABYLON.serialize()
  85770. ], ColorCurves.prototype, "_globalSaturation", void 0);
  85771. __decorate([
  85772. BABYLON.serialize()
  85773. ], ColorCurves.prototype, "_globalExposure", void 0);
  85774. __decorate([
  85775. BABYLON.serialize()
  85776. ], ColorCurves.prototype, "_highlightsHue", void 0);
  85777. __decorate([
  85778. BABYLON.serialize()
  85779. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  85780. __decorate([
  85781. BABYLON.serialize()
  85782. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  85783. __decorate([
  85784. BABYLON.serialize()
  85785. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  85786. __decorate([
  85787. BABYLON.serialize()
  85788. ], ColorCurves.prototype, "_midtonesHue", void 0);
  85789. __decorate([
  85790. BABYLON.serialize()
  85791. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  85792. __decorate([
  85793. BABYLON.serialize()
  85794. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  85795. __decorate([
  85796. BABYLON.serialize()
  85797. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  85798. return ColorCurves;
  85799. }());
  85800. BABYLON.ColorCurves = ColorCurves;
  85801. })(BABYLON || (BABYLON = {}));
  85802. //# sourceMappingURL=babylon.colorCurves.js.map
  85803. var BABYLON;
  85804. (function (BABYLON) {
  85805. var RefractionPostProcess = /** @class */ (function (_super) {
  85806. __extends(RefractionPostProcess, _super);
  85807. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  85808. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  85809. _this.color = color;
  85810. _this.depth = depth;
  85811. _this.colorLevel = colorLevel;
  85812. _this._ownRefractionTexture = true;
  85813. _this.onActivateObservable.add(function (cam) {
  85814. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  85815. });
  85816. _this.onApplyObservable.add(function (effect) {
  85817. effect.setColor3("baseColor", _this.color);
  85818. effect.setFloat("depth", _this.depth);
  85819. effect.setFloat("colorLevel", _this.colorLevel);
  85820. effect.setTexture("refractionSampler", _this._refTexture);
  85821. });
  85822. return _this;
  85823. }
  85824. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  85825. /**
  85826. * Gets or sets the refraction texture
  85827. * Please note that you are responsible for disposing the texture if you set it manually
  85828. */
  85829. get: function () {
  85830. return this._refTexture;
  85831. },
  85832. set: function (value) {
  85833. if (this._refTexture && this._ownRefractionTexture) {
  85834. this._refTexture.dispose();
  85835. }
  85836. this._refTexture = value;
  85837. this._ownRefractionTexture = false;
  85838. },
  85839. enumerable: true,
  85840. configurable: true
  85841. });
  85842. // Methods
  85843. RefractionPostProcess.prototype.dispose = function (camera) {
  85844. if (this._refTexture && this._ownRefractionTexture) {
  85845. this._refTexture.dispose();
  85846. this._refTexture = null;
  85847. }
  85848. _super.prototype.dispose.call(this, camera);
  85849. };
  85850. return RefractionPostProcess;
  85851. }(BABYLON.PostProcess));
  85852. BABYLON.RefractionPostProcess = RefractionPostProcess;
  85853. })(BABYLON || (BABYLON = {}));
  85854. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  85855. var BABYLON;
  85856. (function (BABYLON) {
  85857. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  85858. __extends(BlackAndWhitePostProcess, _super);
  85859. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  85860. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  85861. _this.degree = 1;
  85862. _this.onApplyObservable.add(function (effect) {
  85863. effect.setFloat("degree", _this.degree);
  85864. });
  85865. return _this;
  85866. }
  85867. return BlackAndWhitePostProcess;
  85868. }(BABYLON.PostProcess));
  85869. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  85870. })(BABYLON || (BABYLON = {}));
  85871. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  85872. var BABYLON;
  85873. (function (BABYLON) {
  85874. /**
  85875. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  85876. * input texture to perform effects such as edge detection or sharpening
  85877. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85878. */
  85879. var ConvolutionPostProcess = /** @class */ (function (_super) {
  85880. __extends(ConvolutionPostProcess, _super);
  85881. /**
  85882. * Creates a new instance ConvolutionPostProcess
  85883. * @param name The name of the effect.
  85884. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  85885. * @param options The required width/height ratio to downsize to before computing the render pass.
  85886. * @param camera The camera to apply the render pass to.
  85887. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85888. * @param engine The engine which the post process will be applied. (default: current engine)
  85889. * @param reusable If the post process can be reused on the same frame. (default: false)
  85890. * @param textureType Type of textures used when performing the post process. (default: 0)
  85891. */
  85892. function ConvolutionPostProcess(name,
  85893. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  85894. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  85895. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85896. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85897. _this.kernel = kernel;
  85898. _this.onApply = function (effect) {
  85899. effect.setFloat2("screenSize", _this.width, _this.height);
  85900. effect.setArray("kernel", _this.kernel);
  85901. };
  85902. return _this;
  85903. }
  85904. // Statics
  85905. /**
  85906. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85907. */
  85908. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85909. /**
  85910. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85911. */
  85912. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85913. /**
  85914. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85915. */
  85916. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85917. /**
  85918. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85919. */
  85920. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85921. /**
  85922. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85923. */
  85924. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85925. /**
  85926. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85927. */
  85928. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85929. return ConvolutionPostProcess;
  85930. }(BABYLON.PostProcess));
  85931. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85932. })(BABYLON || (BABYLON = {}));
  85933. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85934. var BABYLON;
  85935. (function (BABYLON) {
  85936. var FilterPostProcess = /** @class */ (function (_super) {
  85937. __extends(FilterPostProcess, _super);
  85938. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85939. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85940. _this.kernelMatrix = kernelMatrix;
  85941. _this.onApply = function (effect) {
  85942. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85943. };
  85944. return _this;
  85945. }
  85946. return FilterPostProcess;
  85947. }(BABYLON.PostProcess));
  85948. BABYLON.FilterPostProcess = FilterPostProcess;
  85949. })(BABYLON || (BABYLON = {}));
  85950. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85951. var BABYLON;
  85952. (function (BABYLON) {
  85953. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85954. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85955. __extends(VolumetricLightScatteringPostProcess, _super);
  85956. /**
  85957. * @constructor
  85958. * @param {string} name - The post-process name
  85959. * @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)
  85960. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85961. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85962. * @param {number} samples - The post-process quality, default 100
  85963. * @param {number} samplingMode - The post-process filtering mode
  85964. * @param {BABYLON.Engine} engine - The babylon engine
  85965. * @param {boolean} reusable - If the post-process is reusable
  85966. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85967. */
  85968. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85969. if (samples === void 0) { samples = 100; }
  85970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85971. 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;
  85972. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85973. /**
  85974. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85975. */
  85976. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85977. /**
  85978. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85979. */
  85980. _this.useCustomMeshPosition = false;
  85981. /**
  85982. * If the post-process should inverse the light scattering direction
  85983. */
  85984. _this.invert = true;
  85985. /**
  85986. * Array containing the excluded meshes not rendered in the internal pass
  85987. */
  85988. _this.excludedMeshes = new Array();
  85989. /**
  85990. * Controls the overall intensity of the post-process
  85991. */
  85992. _this.exposure = 0.3;
  85993. /**
  85994. * Dissipates each sample's contribution in range [0, 1]
  85995. */
  85996. _this.decay = 0.96815;
  85997. /**
  85998. * Controls the overall intensity of each sample
  85999. */
  86000. _this.weight = 0.58767;
  86001. /**
  86002. * Controls the density of each sample
  86003. */
  86004. _this.density = 0.926;
  86005. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  86006. engine = scene.getEngine();
  86007. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  86008. // Configure mesh
  86009. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  86010. // Configure
  86011. _this._createPass(scene, ratio.passRatio || ratio);
  86012. _this.onActivate = function (camera) {
  86013. if (!_this.isSupported) {
  86014. _this.dispose(camera);
  86015. }
  86016. _this.onActivate = null;
  86017. };
  86018. _this.onApplyObservable.add(function (effect) {
  86019. _this._updateMeshScreenCoordinates(scene);
  86020. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  86021. effect.setFloat("exposure", _this.exposure);
  86022. effect.setFloat("decay", _this.decay);
  86023. effect.setFloat("weight", _this.weight);
  86024. effect.setFloat("density", _this.density);
  86025. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  86026. });
  86027. return _this;
  86028. }
  86029. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  86030. get: function () {
  86031. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86032. return false;
  86033. },
  86034. set: function (useDiffuseColor) {
  86035. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86036. },
  86037. enumerable: true,
  86038. configurable: true
  86039. });
  86040. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  86041. return "VolumetricLightScatteringPostProcess";
  86042. };
  86043. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  86044. var mesh = subMesh.getMesh();
  86045. // Render this.mesh as default
  86046. if (mesh === this.mesh && mesh.material) {
  86047. return mesh.material.isReady(mesh);
  86048. }
  86049. var defines = [];
  86050. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86051. var material = subMesh.getMaterial();
  86052. // Alpha test
  86053. if (material) {
  86054. if (material.needAlphaTesting()) {
  86055. defines.push("#define ALPHATEST");
  86056. }
  86057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86058. attribs.push(BABYLON.VertexBuffer.UVKind);
  86059. defines.push("#define UV1");
  86060. }
  86061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86063. defines.push("#define UV2");
  86064. }
  86065. }
  86066. // Bones
  86067. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86070. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86071. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86072. }
  86073. else {
  86074. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86075. }
  86076. // Instances
  86077. if (useInstances) {
  86078. defines.push("#define INSTANCES");
  86079. attribs.push("world0");
  86080. attribs.push("world1");
  86081. attribs.push("world2");
  86082. attribs.push("world3");
  86083. }
  86084. // Get correct effect
  86085. var join = defines.join("\n");
  86086. if (this._cachedDefines !== join) {
  86087. this._cachedDefines = join;
  86088. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  86089. }
  86090. return this._volumetricLightScatteringPass.isReady();
  86091. };
  86092. /**
  86093. * Sets the new light position for light scattering effect
  86094. * @param {BABYLON.Vector3} The new custom light position
  86095. */
  86096. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  86097. this.customMeshPosition = position;
  86098. };
  86099. /**
  86100. * Returns the light position for light scattering effect
  86101. * @return {BABYLON.Vector3} The custom light position
  86102. */
  86103. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  86104. return this.customMeshPosition;
  86105. };
  86106. /**
  86107. * Disposes the internal assets and detaches the post-process from the camera
  86108. */
  86109. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  86110. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  86111. if (rttIndex !== -1) {
  86112. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  86113. }
  86114. this._volumetricLightScatteringRTT.dispose();
  86115. _super.prototype.dispose.call(this, camera);
  86116. };
  86117. /**
  86118. * Returns the render target texture used by the post-process
  86119. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  86120. */
  86121. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  86122. return this._volumetricLightScatteringRTT;
  86123. };
  86124. // Private methods
  86125. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  86126. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  86127. return true;
  86128. }
  86129. return false;
  86130. };
  86131. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  86132. var _this = this;
  86133. var engine = scene.getEngine();
  86134. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86135. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86136. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86137. this._volumetricLightScatteringRTT.renderList = null;
  86138. this._volumetricLightScatteringRTT.renderParticles = false;
  86139. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  86140. var camera = this.getCamera();
  86141. if (camera) {
  86142. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86143. }
  86144. else {
  86145. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86146. }
  86147. // Custom render function for submeshes
  86148. var renderSubMesh = function (subMesh) {
  86149. var mesh = subMesh.getRenderingMesh();
  86150. if (_this._meshExcluded(mesh)) {
  86151. return;
  86152. }
  86153. var material = subMesh.getMaterial();
  86154. if (!material) {
  86155. return;
  86156. }
  86157. var scene = mesh.getScene();
  86158. var engine = scene.getEngine();
  86159. // Culling
  86160. engine.setState(material.backFaceCulling);
  86161. // Managing instances
  86162. var batch = mesh._getInstancesRenderList(subMesh._id);
  86163. if (batch.mustReturn) {
  86164. return;
  86165. }
  86166. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86167. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  86168. var effect = _this._volumetricLightScatteringPass;
  86169. if (mesh === _this.mesh) {
  86170. if (subMesh.effect) {
  86171. effect = subMesh.effect;
  86172. }
  86173. else {
  86174. effect = material.getEffect();
  86175. }
  86176. }
  86177. engine.enableEffect(effect);
  86178. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  86179. if (mesh === _this.mesh) {
  86180. material.bind(mesh.getWorldMatrix(), mesh);
  86181. }
  86182. else {
  86183. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  86184. // Alpha test
  86185. if (material && material.needAlphaTesting()) {
  86186. var alphaTexture = material.getAlphaTestTexture();
  86187. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  86188. if (alphaTexture) {
  86189. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86190. }
  86191. }
  86192. // Bones
  86193. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86194. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86195. }
  86196. }
  86197. // Draw
  86198. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  86199. }
  86200. };
  86201. // Render target texture callbacks
  86202. var savedSceneClearColor;
  86203. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  86204. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  86205. savedSceneClearColor = scene.clearColor;
  86206. scene.clearColor = sceneClearColor;
  86207. });
  86208. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  86209. scene.clearColor = savedSceneClearColor;
  86210. });
  86211. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86212. var engine = scene.getEngine();
  86213. var index;
  86214. if (depthOnlySubMeshes.length) {
  86215. engine.setColorWrite(false);
  86216. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86217. renderSubMesh(depthOnlySubMeshes.data[index]);
  86218. }
  86219. engine.setColorWrite(true);
  86220. }
  86221. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86222. renderSubMesh(opaqueSubMeshes.data[index]);
  86223. }
  86224. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86225. renderSubMesh(alphaTestSubMeshes.data[index]);
  86226. }
  86227. if (transparentSubMeshes.length) {
  86228. // Sort sub meshes
  86229. for (index = 0; index < transparentSubMeshes.length; index++) {
  86230. var submesh = transparentSubMeshes.data[index];
  86231. var boundingInfo = submesh.getBoundingInfo();
  86232. if (boundingInfo && scene.activeCamera) {
  86233. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  86234. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  86235. }
  86236. }
  86237. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  86238. sortedArray.sort(function (a, b) {
  86239. // Alpha index first
  86240. if (a._alphaIndex > b._alphaIndex) {
  86241. return 1;
  86242. }
  86243. if (a._alphaIndex < b._alphaIndex) {
  86244. return -1;
  86245. }
  86246. // Then distance to camera
  86247. if (a._distanceToCamera < b._distanceToCamera) {
  86248. return 1;
  86249. }
  86250. if (a._distanceToCamera > b._distanceToCamera) {
  86251. return -1;
  86252. }
  86253. return 0;
  86254. });
  86255. // Render sub meshes
  86256. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  86257. for (index = 0; index < sortedArray.length; index++) {
  86258. renderSubMesh(sortedArray[index]);
  86259. }
  86260. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86261. }
  86262. };
  86263. };
  86264. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  86265. var transform = scene.getTransformMatrix();
  86266. var meshPosition;
  86267. if (this.useCustomMeshPosition) {
  86268. meshPosition = this.customMeshPosition;
  86269. }
  86270. else if (this.attachedNode) {
  86271. meshPosition = this.attachedNode.position;
  86272. }
  86273. else {
  86274. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  86275. }
  86276. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  86277. this._screenCoordinates.x = pos.x / this._viewPort.width;
  86278. this._screenCoordinates.y = pos.y / this._viewPort.height;
  86279. if (this.invert)
  86280. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  86281. };
  86282. // Static methods
  86283. /**
  86284. * Creates a default mesh for the Volumeric Light Scattering post-process
  86285. * @param {string} The mesh name
  86286. * @param {BABYLON.Scene} The scene where to create the mesh
  86287. * @return {BABYLON.Mesh} the default mesh
  86288. */
  86289. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  86290. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  86291. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  86292. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  86293. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  86294. mesh.material = material;
  86295. return mesh;
  86296. };
  86297. __decorate([
  86298. BABYLON.serializeAsVector3()
  86299. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  86300. __decorate([
  86301. BABYLON.serialize()
  86302. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  86303. __decorate([
  86304. BABYLON.serialize()
  86305. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  86306. __decorate([
  86307. BABYLON.serializeAsMeshReference()
  86308. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  86309. __decorate([
  86310. BABYLON.serialize()
  86311. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  86312. __decorate([
  86313. BABYLON.serialize()
  86314. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  86315. __decorate([
  86316. BABYLON.serialize()
  86317. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  86318. __decorate([
  86319. BABYLON.serialize()
  86320. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  86321. __decorate([
  86322. BABYLON.serialize()
  86323. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  86324. return VolumetricLightScatteringPostProcess;
  86325. }(BABYLON.PostProcess));
  86326. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  86327. })(BABYLON || (BABYLON = {}));
  86328. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  86329. //
  86330. // This post-process allows the modification of rendered colors by using
  86331. // a 'look-up table' (LUT). This effect is also called Color Grading.
  86332. //
  86333. // The object needs to be provided an url to a texture containing the color
  86334. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  86335. // Use an image editing software to tweak the LUT to match your needs.
  86336. //
  86337. // For an example of a color LUT, see here:
  86338. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  86339. // For explanations on color grading, see here:
  86340. // http://udn.epicgames.com/Three/ColorGrading.html
  86341. //
  86342. var BABYLON;
  86343. (function (BABYLON) {
  86344. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  86345. __extends(ColorCorrectionPostProcess, _super);
  86346. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  86347. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  86348. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86349. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  86350. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86351. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86352. _this.onApply = function (effect) {
  86353. effect.setTexture("colorTable", _this._colorTableTexture);
  86354. };
  86355. return _this;
  86356. }
  86357. return ColorCorrectionPostProcess;
  86358. }(BABYLON.PostProcess));
  86359. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  86360. })(BABYLON || (BABYLON = {}));
  86361. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  86362. var BABYLON;
  86363. (function (BABYLON) {
  86364. /** Defines operator used for tonemapping */
  86365. var TonemappingOperator;
  86366. (function (TonemappingOperator) {
  86367. /** Hable */
  86368. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  86369. /** Reinhard */
  86370. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  86371. /** HejiDawson */
  86372. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  86373. /** Photographic */
  86374. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  86375. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  86376. ;
  86377. /**
  86378. * Defines a post process to apply tone mapping
  86379. */
  86380. var TonemapPostProcess = /** @class */ (function (_super) {
  86381. __extends(TonemapPostProcess, _super);
  86382. /**
  86383. * Creates a new TonemapPostProcess
  86384. * @param name defines the name of the postprocess
  86385. * @param _operator defines the operator to use
  86386. * @param exposureAdjustment defines the required exposure adjustement
  86387. * @param camera defines the camera to use (can be null)
  86388. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  86389. * @param engine defines the hosting engine (can be ignore if camera is set)
  86390. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  86391. */
  86392. function TonemapPostProcess(name, _operator,
  86393. /** Defines the required exposure adjustement */
  86394. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  86395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86396. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86397. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  86398. _this._operator = _operator;
  86399. _this.exposureAdjustment = exposureAdjustment;
  86400. var defines = "#define ";
  86401. if (_this._operator === TonemappingOperator.Hable)
  86402. defines += "HABLE_TONEMAPPING";
  86403. else if (_this._operator === TonemappingOperator.Reinhard)
  86404. defines += "REINHARD_TONEMAPPING";
  86405. else if (_this._operator === TonemappingOperator.HejiDawson)
  86406. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  86407. else if (_this._operator === TonemappingOperator.Photographic)
  86408. defines += "PHOTOGRAPHIC_TONEMAPPING";
  86409. //sadly a second call to create the effect.
  86410. _this.updateEffect(defines);
  86411. _this.onApply = function (effect) {
  86412. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  86413. };
  86414. return _this;
  86415. }
  86416. return TonemapPostProcess;
  86417. }(BABYLON.PostProcess));
  86418. BABYLON.TonemapPostProcess = TonemapPostProcess;
  86419. })(BABYLON || (BABYLON = {}));
  86420. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  86421. var BABYLON;
  86422. (function (BABYLON) {
  86423. var DisplayPassPostProcess = /** @class */ (function (_super) {
  86424. __extends(DisplayPassPostProcess, _super);
  86425. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  86426. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  86427. }
  86428. return DisplayPassPostProcess;
  86429. }(BABYLON.PostProcess));
  86430. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  86431. })(BABYLON || (BABYLON = {}));
  86432. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  86433. var BABYLON;
  86434. (function (BABYLON) {
  86435. var HighlightsPostProcess = /** @class */ (function (_super) {
  86436. __extends(HighlightsPostProcess, _super);
  86437. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86438. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86439. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86440. }
  86441. return HighlightsPostProcess;
  86442. }(BABYLON.PostProcess));
  86443. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  86444. })(BABYLON || (BABYLON = {}));
  86445. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  86446. var BABYLON;
  86447. (function (BABYLON) {
  86448. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  86449. __extends(ImageProcessingPostProcess, _super);
  86450. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  86451. if (camera === void 0) { camera = null; }
  86452. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86453. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  86454. _this._fromLinearSpace = true;
  86455. /**
  86456. * Defines cache preventing GC.
  86457. */
  86458. _this._defines = {
  86459. IMAGEPROCESSING: false,
  86460. VIGNETTE: false,
  86461. VIGNETTEBLENDMODEMULTIPLY: false,
  86462. VIGNETTEBLENDMODEOPAQUE: false,
  86463. TONEMAPPING: false,
  86464. TONEMAPPING_ACES: false,
  86465. CONTRAST: false,
  86466. COLORCURVES: false,
  86467. COLORGRADING: false,
  86468. COLORGRADING3D: false,
  86469. FROMLINEARSPACE: false,
  86470. SAMPLER3DGREENDEPTH: false,
  86471. SAMPLER3DBGRMAP: false,
  86472. IMAGEPROCESSINGPOSTPROCESS: false,
  86473. EXPOSURE: false,
  86474. };
  86475. // Setup the configuration as forced by the constructor. This would then not force the
  86476. // scene materials output in linear space and let untouched the default forward pass.
  86477. if (imageProcessingConfiguration) {
  86478. imageProcessingConfiguration.applyByPostProcess = true;
  86479. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  86480. // This will cause the shader to be compiled
  86481. _this.fromLinearSpace = false;
  86482. }
  86483. // Setup the default processing configuration to the scene.
  86484. else {
  86485. _this._attachImageProcessingConfiguration(null, true);
  86486. _this.imageProcessingConfiguration.applyByPostProcess = true;
  86487. }
  86488. _this.onApply = function (effect) {
  86489. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  86490. };
  86491. return _this;
  86492. }
  86493. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  86494. /**
  86495. * Gets the image processing configuration used either in this material.
  86496. */
  86497. get: function () {
  86498. return this._imageProcessingConfiguration;
  86499. },
  86500. /**
  86501. * Sets the Default image processing configuration used either in the this material.
  86502. *
  86503. * If sets to null, the scene one is in use.
  86504. */
  86505. set: function (value) {
  86506. this._attachImageProcessingConfiguration(value);
  86507. },
  86508. enumerable: true,
  86509. configurable: true
  86510. });
  86511. /**
  86512. * Attaches a new image processing configuration to the PBR Material.
  86513. * @param configuration
  86514. */
  86515. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  86516. var _this = this;
  86517. if (doNotBuild === void 0) { doNotBuild = false; }
  86518. if (configuration === this._imageProcessingConfiguration) {
  86519. return;
  86520. }
  86521. // Detaches observer.
  86522. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86523. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86524. }
  86525. // Pick the scene configuration if needed.
  86526. if (!configuration) {
  86527. var scene = null;
  86528. var engine = this.getEngine();
  86529. var camera = this.getCamera();
  86530. if (camera) {
  86531. scene = camera.getScene();
  86532. }
  86533. else if (engine && engine.scenes) {
  86534. var scenes = engine.scenes;
  86535. scene = scenes[scenes.length - 1];
  86536. }
  86537. else {
  86538. scene = BABYLON.Engine.LastCreatedScene;
  86539. }
  86540. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86541. }
  86542. else {
  86543. this._imageProcessingConfiguration = configuration;
  86544. }
  86545. // Attaches observer.
  86546. if (this._imageProcessingConfiguration) {
  86547. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86548. _this._updateParameters();
  86549. });
  86550. }
  86551. // Ensure the effect will be rebuilt.
  86552. if (!doNotBuild) {
  86553. this._updateParameters();
  86554. }
  86555. };
  86556. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86557. /**
  86558. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86559. */
  86560. get: function () {
  86561. return this.imageProcessingConfiguration.colorCurves;
  86562. },
  86563. /**
  86564. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86565. */
  86566. set: function (value) {
  86567. this.imageProcessingConfiguration.colorCurves = value;
  86568. },
  86569. enumerable: true,
  86570. configurable: true
  86571. });
  86572. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86573. /**
  86574. * Gets wether the color curves effect is enabled.
  86575. */
  86576. get: function () {
  86577. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86578. },
  86579. /**
  86580. * Sets wether the color curves effect is enabled.
  86581. */
  86582. set: function (value) {
  86583. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86584. },
  86585. enumerable: true,
  86586. configurable: true
  86587. });
  86588. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86589. /**
  86590. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86591. */
  86592. get: function () {
  86593. return this.imageProcessingConfiguration.colorGradingTexture;
  86594. },
  86595. /**
  86596. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86597. */
  86598. set: function (value) {
  86599. this.imageProcessingConfiguration.colorGradingTexture = value;
  86600. },
  86601. enumerable: true,
  86602. configurable: true
  86603. });
  86604. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86605. /**
  86606. * Gets wether the color grading effect is enabled.
  86607. */
  86608. get: function () {
  86609. return this.imageProcessingConfiguration.colorGradingEnabled;
  86610. },
  86611. /**
  86612. * Gets wether the color grading effect is enabled.
  86613. */
  86614. set: function (value) {
  86615. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86616. },
  86617. enumerable: true,
  86618. configurable: true
  86619. });
  86620. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86621. /**
  86622. * Gets exposure used in the effect.
  86623. */
  86624. get: function () {
  86625. return this.imageProcessingConfiguration.exposure;
  86626. },
  86627. /**
  86628. * Sets exposure used in the effect.
  86629. */
  86630. set: function (value) {
  86631. this.imageProcessingConfiguration.exposure = value;
  86632. },
  86633. enumerable: true,
  86634. configurable: true
  86635. });
  86636. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86637. /**
  86638. * Gets wether tonemapping is enabled or not.
  86639. */
  86640. get: function () {
  86641. return this._imageProcessingConfiguration.toneMappingEnabled;
  86642. },
  86643. /**
  86644. * Sets wether tonemapping is enabled or not
  86645. */
  86646. set: function (value) {
  86647. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86648. },
  86649. enumerable: true,
  86650. configurable: true
  86651. });
  86652. ;
  86653. ;
  86654. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  86655. /**
  86656. * Gets contrast used in the effect.
  86657. */
  86658. get: function () {
  86659. return this.imageProcessingConfiguration.contrast;
  86660. },
  86661. /**
  86662. * Sets contrast used in the effect.
  86663. */
  86664. set: function (value) {
  86665. this.imageProcessingConfiguration.contrast = value;
  86666. },
  86667. enumerable: true,
  86668. configurable: true
  86669. });
  86670. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  86671. /**
  86672. * Gets Vignette stretch size.
  86673. */
  86674. get: function () {
  86675. return this.imageProcessingConfiguration.vignetteStretch;
  86676. },
  86677. /**
  86678. * Sets Vignette stretch size.
  86679. */
  86680. set: function (value) {
  86681. this.imageProcessingConfiguration.vignetteStretch = value;
  86682. },
  86683. enumerable: true,
  86684. configurable: true
  86685. });
  86686. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  86687. /**
  86688. * Gets Vignette centre X Offset.
  86689. */
  86690. get: function () {
  86691. return this.imageProcessingConfiguration.vignetteCentreX;
  86692. },
  86693. /**
  86694. * Sets Vignette centre X Offset.
  86695. */
  86696. set: function (value) {
  86697. this.imageProcessingConfiguration.vignetteCentreX = value;
  86698. },
  86699. enumerable: true,
  86700. configurable: true
  86701. });
  86702. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  86703. /**
  86704. * Gets Vignette centre Y Offset.
  86705. */
  86706. get: function () {
  86707. return this.imageProcessingConfiguration.vignetteCentreY;
  86708. },
  86709. /**
  86710. * Sets Vignette centre Y Offset.
  86711. */
  86712. set: function (value) {
  86713. this.imageProcessingConfiguration.vignetteCentreY = value;
  86714. },
  86715. enumerable: true,
  86716. configurable: true
  86717. });
  86718. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  86719. /**
  86720. * Gets Vignette weight or intensity of the vignette effect.
  86721. */
  86722. get: function () {
  86723. return this.imageProcessingConfiguration.vignetteWeight;
  86724. },
  86725. /**
  86726. * Sets Vignette weight or intensity of the vignette effect.
  86727. */
  86728. set: function (value) {
  86729. this.imageProcessingConfiguration.vignetteWeight = value;
  86730. },
  86731. enumerable: true,
  86732. configurable: true
  86733. });
  86734. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  86735. /**
  86736. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86737. * if vignetteEnabled is set to true.
  86738. */
  86739. get: function () {
  86740. return this.imageProcessingConfiguration.vignetteColor;
  86741. },
  86742. /**
  86743. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86744. * if vignetteEnabled is set to true.
  86745. */
  86746. set: function (value) {
  86747. this.imageProcessingConfiguration.vignetteColor = value;
  86748. },
  86749. enumerable: true,
  86750. configurable: true
  86751. });
  86752. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  86753. /**
  86754. * Gets Camera field of view used by the Vignette effect.
  86755. */
  86756. get: function () {
  86757. return this.imageProcessingConfiguration.vignetteCameraFov;
  86758. },
  86759. /**
  86760. * Sets Camera field of view used by the Vignette effect.
  86761. */
  86762. set: function (value) {
  86763. this.imageProcessingConfiguration.vignetteCameraFov = value;
  86764. },
  86765. enumerable: true,
  86766. configurable: true
  86767. });
  86768. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  86769. /**
  86770. * Gets the vignette blend mode allowing different kind of effect.
  86771. */
  86772. get: function () {
  86773. return this.imageProcessingConfiguration.vignetteBlendMode;
  86774. },
  86775. /**
  86776. * Sets the vignette blend mode allowing different kind of effect.
  86777. */
  86778. set: function (value) {
  86779. this.imageProcessingConfiguration.vignetteBlendMode = value;
  86780. },
  86781. enumerable: true,
  86782. configurable: true
  86783. });
  86784. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  86785. /**
  86786. * Gets wether the vignette effect is enabled.
  86787. */
  86788. get: function () {
  86789. return this.imageProcessingConfiguration.vignetteEnabled;
  86790. },
  86791. /**
  86792. * Sets wether the vignette effect is enabled.
  86793. */
  86794. set: function (value) {
  86795. this.imageProcessingConfiguration.vignetteEnabled = value;
  86796. },
  86797. enumerable: true,
  86798. configurable: true
  86799. });
  86800. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  86801. /**
  86802. * Gets wether the input of the processing is in Gamma or Linear Space.
  86803. */
  86804. get: function () {
  86805. return this._fromLinearSpace;
  86806. },
  86807. /**
  86808. * Sets wether the input of the processing is in Gamma or Linear Space.
  86809. */
  86810. set: function (value) {
  86811. if (this._fromLinearSpace === value) {
  86812. return;
  86813. }
  86814. this._fromLinearSpace = value;
  86815. this._updateParameters();
  86816. },
  86817. enumerable: true,
  86818. configurable: true
  86819. });
  86820. ImageProcessingPostProcess.prototype.getClassName = function () {
  86821. return "ImageProcessingPostProcess";
  86822. };
  86823. ImageProcessingPostProcess.prototype._updateParameters = function () {
  86824. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  86825. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  86826. var defines = "";
  86827. for (var define in this._defines) {
  86828. if (this._defines[define]) {
  86829. defines += "#define " + define + ";\r\n";
  86830. }
  86831. }
  86832. var samplers = ["textureSampler"];
  86833. var uniforms = ["scale"];
  86834. if (BABYLON.ImageProcessingConfiguration) {
  86835. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  86836. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  86837. }
  86838. this.updateEffect(defines, uniforms, samplers);
  86839. };
  86840. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  86841. _super.prototype.dispose.call(this, camera);
  86842. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86843. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86844. }
  86845. if (this._imageProcessingConfiguration) {
  86846. this.imageProcessingConfiguration.applyByPostProcess = false;
  86847. }
  86848. };
  86849. __decorate([
  86850. BABYLON.serialize()
  86851. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  86852. return ImageProcessingPostProcess;
  86853. }(BABYLON.PostProcess));
  86854. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  86855. })(BABYLON || (BABYLON = {}));
  86856. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  86857. var BABYLON;
  86858. (function (BABYLON) {
  86859. /**
  86860. * Class used to store bone information
  86861. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86862. */
  86863. var Bone = /** @class */ (function (_super) {
  86864. __extends(Bone, _super);
  86865. /**
  86866. * Create a new bone
  86867. * @param name defines the bone name
  86868. * @param skeleton defines the parent skeleton
  86869. * @param parentBone defines the parent (can be null if the bone is the root)
  86870. * @param localMatrix defines the local matrix
  86871. * @param restPose defines the rest pose matrix
  86872. * @param baseMatrix defines the base matrix
  86873. * @param index defines index of the bone in the hiearchy
  86874. */
  86875. function Bone(
  86876. /**
  86877. * defines the bone name
  86878. */
  86879. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  86880. if (parentBone === void 0) { parentBone = null; }
  86881. if (localMatrix === void 0) { localMatrix = null; }
  86882. if (restPose === void 0) { restPose = null; }
  86883. if (baseMatrix === void 0) { baseMatrix = null; }
  86884. if (index === void 0) { index = null; }
  86885. var _this = _super.call(this, name, skeleton.getScene()) || this;
  86886. _this.name = name;
  86887. /**
  86888. * Gets the list of child bones
  86889. */
  86890. _this.children = new Array();
  86891. /** Gets the animations associated with this bone */
  86892. _this.animations = new Array();
  86893. /**
  86894. * @hidden Internal only
  86895. * Set this value to map this bone to a different index in the transform matrices
  86896. * Set this value to -1 to exclude the bone from the transform matrices
  86897. */
  86898. _this._index = null;
  86899. _this._absoluteTransform = new BABYLON.Matrix();
  86900. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  86901. _this._scalingDeterminant = 1;
  86902. _this._worldTransform = new BABYLON.Matrix();
  86903. _this._needToDecompose = true;
  86904. _this._needToCompose = false;
  86905. _this._skeleton = skeleton;
  86906. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86907. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86908. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86909. _this._index = index;
  86910. skeleton.bones.push(_this);
  86911. _this.setParent(parentBone, false);
  86912. if (baseMatrix || localMatrix) {
  86913. _this._updateDifferenceMatrix();
  86914. }
  86915. return _this;
  86916. }
  86917. Object.defineProperty(Bone.prototype, "_matrix", {
  86918. /** @hidden */
  86919. get: function () {
  86920. this._compose();
  86921. return this._localMatrix;
  86922. },
  86923. /** @hidden */
  86924. set: function (value) {
  86925. this._localMatrix.copyFrom(value);
  86926. this._needToDecompose = true;
  86927. },
  86928. enumerable: true,
  86929. configurable: true
  86930. });
  86931. // Members
  86932. /**
  86933. * Gets the parent skeleton
  86934. * @returns a skeleton
  86935. */
  86936. Bone.prototype.getSkeleton = function () {
  86937. return this._skeleton;
  86938. };
  86939. /**
  86940. * Gets parent bone
  86941. * @returns a bone or null if the bone is the root of the bone hierarchy
  86942. */
  86943. Bone.prototype.getParent = function () {
  86944. return this._parent;
  86945. };
  86946. /**
  86947. * Sets the parent bone
  86948. * @param parent defines the parent (can be null if the bone is the root)
  86949. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86950. */
  86951. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86952. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86953. if (this._parent === parent) {
  86954. return;
  86955. }
  86956. if (this._parent) {
  86957. var index = this._parent.children.indexOf(this);
  86958. if (index !== -1) {
  86959. this._parent.children.splice(index, 1);
  86960. }
  86961. }
  86962. this._parent = parent;
  86963. if (this._parent) {
  86964. this._parent.children.push(this);
  86965. }
  86966. if (updateDifferenceMatrix) {
  86967. this._updateDifferenceMatrix();
  86968. }
  86969. this.markAsDirty();
  86970. };
  86971. /**
  86972. * Gets the local matrix
  86973. * @returns a matrix
  86974. */
  86975. Bone.prototype.getLocalMatrix = function () {
  86976. this._compose();
  86977. return this._localMatrix;
  86978. };
  86979. /**
  86980. * Gets the base matrix (initial matrix which remains unchanged)
  86981. * @returns a matrix
  86982. */
  86983. Bone.prototype.getBaseMatrix = function () {
  86984. return this._baseMatrix;
  86985. };
  86986. /**
  86987. * Gets the rest pose matrix
  86988. * @returns a matrix
  86989. */
  86990. Bone.prototype.getRestPose = function () {
  86991. return this._restPose;
  86992. };
  86993. /**
  86994. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86995. */
  86996. Bone.prototype.getWorldMatrix = function () {
  86997. return this._worldTransform;
  86998. };
  86999. /**
  87000. * Sets the local matrix to rest pose matrix
  87001. */
  87002. Bone.prototype.returnToRest = function () {
  87003. this.updateMatrix(this._restPose.clone());
  87004. };
  87005. /**
  87006. * Gets the inverse of the absolute transform matrix.
  87007. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  87008. * @returns a matrix
  87009. */
  87010. Bone.prototype.getInvertedAbsoluteTransform = function () {
  87011. return this._invertedAbsoluteTransform;
  87012. };
  87013. /**
  87014. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  87015. * @returns a matrix
  87016. */
  87017. Bone.prototype.getAbsoluteTransform = function () {
  87018. return this._absoluteTransform;
  87019. };
  87020. Object.defineProperty(Bone.prototype, "position", {
  87021. // Properties (matches AbstractMesh properties)
  87022. /** Gets or sets current position (in local space) */
  87023. get: function () {
  87024. this._decompose();
  87025. return this._localPosition;
  87026. },
  87027. set: function (newPosition) {
  87028. this._decompose();
  87029. this._localPosition.copyFrom(newPosition);
  87030. this._markAsDirtyAndCompose();
  87031. },
  87032. enumerable: true,
  87033. configurable: true
  87034. });
  87035. Object.defineProperty(Bone.prototype, "rotation", {
  87036. /** Gets or sets current rotation (in local space) */
  87037. get: function () {
  87038. return this.getRotation();
  87039. },
  87040. set: function (newRotation) {
  87041. this.setRotation(newRotation);
  87042. },
  87043. enumerable: true,
  87044. configurable: true
  87045. });
  87046. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  87047. /** Gets or sets current rotation quaternion (in local space) */
  87048. get: function () {
  87049. this._decompose();
  87050. return this._localRotation;
  87051. },
  87052. set: function (newRotation) {
  87053. this.setRotationQuaternion(newRotation);
  87054. },
  87055. enumerable: true,
  87056. configurable: true
  87057. });
  87058. Object.defineProperty(Bone.prototype, "scaling", {
  87059. /** Gets or sets current scaling (in local space) */
  87060. get: function () {
  87061. return this.getScale();
  87062. },
  87063. set: function (newScaling) {
  87064. this.setScale(newScaling);
  87065. },
  87066. enumerable: true,
  87067. configurable: true
  87068. });
  87069. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  87070. /**
  87071. * Gets the animation properties override
  87072. */
  87073. get: function () {
  87074. return this._skeleton.animationPropertiesOverride;
  87075. },
  87076. enumerable: true,
  87077. configurable: true
  87078. });
  87079. // Methods
  87080. Bone.prototype._decompose = function () {
  87081. if (!this._needToDecompose) {
  87082. return;
  87083. }
  87084. this._needToDecompose = false;
  87085. if (!this._localScaling) {
  87086. this._localScaling = BABYLON.Vector3.Zero();
  87087. this._localRotation = BABYLON.Quaternion.Zero();
  87088. this._localPosition = BABYLON.Vector3.Zero();
  87089. }
  87090. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  87091. };
  87092. Bone.prototype._compose = function () {
  87093. if (!this._needToCompose) {
  87094. return;
  87095. }
  87096. this._needToCompose = false;
  87097. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  87098. };
  87099. /**
  87100. * Update the base and local matrices
  87101. * @param matrix defines the new base or local matrix
  87102. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87103. * @param updateLocalMatrix defines if the local matrix should be updated
  87104. */
  87105. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  87106. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87107. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  87108. this._baseMatrix.copyFrom(matrix);
  87109. if (updateDifferenceMatrix) {
  87110. this._updateDifferenceMatrix();
  87111. }
  87112. if (updateLocalMatrix) {
  87113. this._localMatrix.copyFrom(matrix);
  87114. this._markAsDirtyAndDecompose();
  87115. }
  87116. else {
  87117. this.markAsDirty();
  87118. }
  87119. };
  87120. /** @hidden */
  87121. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  87122. if (updateChildren === void 0) { updateChildren = true; }
  87123. if (!rootMatrix) {
  87124. rootMatrix = this._baseMatrix;
  87125. }
  87126. if (this._parent) {
  87127. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87128. }
  87129. else {
  87130. this._absoluteTransform.copyFrom(rootMatrix);
  87131. }
  87132. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  87133. if (updateChildren) {
  87134. for (var index = 0; index < this.children.length; index++) {
  87135. this.children[index]._updateDifferenceMatrix();
  87136. }
  87137. }
  87138. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  87139. };
  87140. /**
  87141. * Flag the bone as dirty (Forcing it to update everything)
  87142. */
  87143. Bone.prototype.markAsDirty = function () {
  87144. this._currentRenderId++;
  87145. this._childRenderId++;
  87146. this._skeleton._markAsDirty();
  87147. };
  87148. Bone.prototype._markAsDirtyAndCompose = function () {
  87149. this.markAsDirty();
  87150. this._needToCompose = true;
  87151. };
  87152. Bone.prototype._markAsDirtyAndDecompose = function () {
  87153. this.markAsDirty();
  87154. this._needToDecompose = true;
  87155. };
  87156. /**
  87157. * Copy an animation range from another bone
  87158. * @param source defines the source bone
  87159. * @param rangeName defines the range name to copy
  87160. * @param frameOffset defines the frame offset
  87161. * @param rescaleAsRequired defines if rescaling must be applied if required
  87162. * @param skelDimensionsRatio defines the scaling ratio
  87163. * @returns true if operation was successful
  87164. */
  87165. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  87166. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87167. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  87168. // all animation may be coming from a library skeleton, so may need to create animation
  87169. if (this.animations.length === 0) {
  87170. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  87171. this.animations[0].setKeys([]);
  87172. }
  87173. // get animation info / verify there is such a range from the source bone
  87174. var sourceRange = source.animations[0].getRange(rangeName);
  87175. if (!sourceRange) {
  87176. return false;
  87177. }
  87178. var from = sourceRange.from;
  87179. var to = sourceRange.to;
  87180. var sourceKeys = source.animations[0].getKeys();
  87181. // rescaling prep
  87182. var sourceBoneLength = source.length;
  87183. var sourceParent = source.getParent();
  87184. var parent = this.getParent();
  87185. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  87186. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  87187. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  87188. var destKeys = this.animations[0].getKeys();
  87189. // loop vars declaration
  87190. var orig;
  87191. var origTranslation;
  87192. var mat;
  87193. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  87194. orig = sourceKeys[key];
  87195. if (orig.frame >= from && orig.frame <= to) {
  87196. if (rescaleAsRequired) {
  87197. mat = orig.value.clone();
  87198. // scale based on parent ratio, when bone has parent
  87199. if (parentScalingReqd) {
  87200. origTranslation = mat.getTranslation();
  87201. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  87202. // scale based on skeleton dimension ratio when root bone, and value is passed
  87203. }
  87204. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  87205. origTranslation = mat.getTranslation();
  87206. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  87207. // use original when root bone, and no data for skelDimensionsRatio
  87208. }
  87209. else {
  87210. mat = orig.value;
  87211. }
  87212. }
  87213. else {
  87214. mat = orig.value;
  87215. }
  87216. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  87217. }
  87218. }
  87219. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  87220. return true;
  87221. };
  87222. /**
  87223. * Translate the bone in local or world space
  87224. * @param vec The amount to translate the bone
  87225. * @param space The space that the translation is in
  87226. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87227. */
  87228. Bone.prototype.translate = function (vec, space, mesh) {
  87229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87230. var lm = this.getLocalMatrix();
  87231. if (space == BABYLON.Space.LOCAL) {
  87232. lm.m[12] += vec.x;
  87233. lm.m[13] += vec.y;
  87234. lm.m[14] += vec.z;
  87235. }
  87236. else {
  87237. var wm = null;
  87238. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87239. if (mesh) {
  87240. wm = mesh.getWorldMatrix();
  87241. }
  87242. this._skeleton.computeAbsoluteTransforms();
  87243. var tmat = Bone._tmpMats[0];
  87244. var tvec = Bone._tmpVecs[0];
  87245. if (this._parent) {
  87246. if (mesh && wm) {
  87247. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87248. tmat.multiplyToRef(wm, tmat);
  87249. }
  87250. else {
  87251. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87252. }
  87253. }
  87254. tmat.m[12] = 0;
  87255. tmat.m[13] = 0;
  87256. tmat.m[14] = 0;
  87257. tmat.invert();
  87258. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  87259. lm.m[12] += tvec.x;
  87260. lm.m[13] += tvec.y;
  87261. lm.m[14] += tvec.z;
  87262. }
  87263. this._markAsDirtyAndDecompose();
  87264. };
  87265. /**
  87266. * Set the postion of the bone in local or world space
  87267. * @param position The position to set the bone
  87268. * @param space The space that the position is in
  87269. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87270. */
  87271. Bone.prototype.setPosition = function (position, space, mesh) {
  87272. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87273. var lm = this.getLocalMatrix();
  87274. if (space == BABYLON.Space.LOCAL) {
  87275. lm.m[12] = position.x;
  87276. lm.m[13] = position.y;
  87277. lm.m[14] = position.z;
  87278. }
  87279. else {
  87280. var wm = null;
  87281. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87282. if (mesh) {
  87283. wm = mesh.getWorldMatrix();
  87284. }
  87285. this._skeleton.computeAbsoluteTransforms();
  87286. var tmat = Bone._tmpMats[0];
  87287. var vec = Bone._tmpVecs[0];
  87288. if (this._parent) {
  87289. if (mesh && wm) {
  87290. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87291. tmat.multiplyToRef(wm, tmat);
  87292. }
  87293. else {
  87294. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87295. }
  87296. }
  87297. tmat.invert();
  87298. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  87299. lm.m[12] = vec.x;
  87300. lm.m[13] = vec.y;
  87301. lm.m[14] = vec.z;
  87302. }
  87303. this._markAsDirtyAndDecompose();
  87304. };
  87305. /**
  87306. * Set the absolute position of the bone (world space)
  87307. * @param position The position to set the bone
  87308. * @param mesh The mesh that this bone is attached to
  87309. */
  87310. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  87311. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  87312. };
  87313. /**
  87314. * Scale the bone on the x, y and z axes (in local space)
  87315. * @param x The amount to scale the bone on the x axis
  87316. * @param y The amount to scale the bone on the y axis
  87317. * @param z The amount to scale the bone on the z axis
  87318. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  87319. */
  87320. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  87321. if (scaleChildren === void 0) { scaleChildren = false; }
  87322. var locMat = this.getLocalMatrix();
  87323. // Apply new scaling on top of current local matrix
  87324. var scaleMat = Bone._tmpMats[0];
  87325. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  87326. scaleMat.multiplyToRef(locMat, locMat);
  87327. // Invert scaling matrix and apply the inverse to all children
  87328. scaleMat.invert();
  87329. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  87330. var child = _a[_i];
  87331. var cm = child.getLocalMatrix();
  87332. cm.multiplyToRef(scaleMat, cm);
  87333. cm.m[12] *= x;
  87334. cm.m[13] *= y;
  87335. cm.m[14] *= z;
  87336. child._markAsDirtyAndDecompose();
  87337. }
  87338. this._markAsDirtyAndDecompose();
  87339. if (scaleChildren) {
  87340. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  87341. var child = _c[_b];
  87342. child.scale(x, y, z, scaleChildren);
  87343. }
  87344. }
  87345. };
  87346. /**
  87347. * Set the bone scaling in local space
  87348. * @param scale defines the scaling vector
  87349. */
  87350. Bone.prototype.setScale = function (scale) {
  87351. this._decompose();
  87352. this._localScaling.copyFrom(scale);
  87353. this._markAsDirtyAndCompose();
  87354. };
  87355. /**
  87356. * Gets the current scaling in local space
  87357. * @returns the current scaling vector
  87358. */
  87359. Bone.prototype.getScale = function () {
  87360. this._decompose();
  87361. return this._localScaling;
  87362. };
  87363. /**
  87364. * Gets the current scaling in local space and stores it in a target vector
  87365. * @param result defines the target vector
  87366. */
  87367. Bone.prototype.getScaleToRef = function (result) {
  87368. this._decompose();
  87369. result.copyFrom(this._localScaling);
  87370. };
  87371. /**
  87372. * Set the yaw, pitch, and roll of the bone in local or world space
  87373. * @param yaw The rotation of the bone on the y axis
  87374. * @param pitch The rotation of the bone on the x axis
  87375. * @param roll The rotation of the bone on the z axis
  87376. * @param space The space that the axes of rotation are in
  87377. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87378. */
  87379. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  87380. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87381. if (space === BABYLON.Space.LOCAL) {
  87382. var quat = Bone._tmpQuat;
  87383. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  87384. this.setRotationQuaternion(quat, space, mesh);
  87385. return;
  87386. }
  87387. var rotMatInv = Bone._tmpMats[0];
  87388. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87389. return;
  87390. }
  87391. var rotMat = Bone._tmpMats[1];
  87392. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  87393. rotMatInv.multiplyToRef(rotMat, rotMat);
  87394. this._rotateWithMatrix(rotMat, space, mesh);
  87395. };
  87396. /**
  87397. * Add a rotation to the bone on an axis in local or world space
  87398. * @param axis The axis to rotate the bone on
  87399. * @param amount The amount to rotate the bone
  87400. * @param space The space that the axis is in
  87401. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87402. */
  87403. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  87404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87405. var rmat = Bone._tmpMats[0];
  87406. rmat.m[12] = 0;
  87407. rmat.m[13] = 0;
  87408. rmat.m[14] = 0;
  87409. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  87410. this._rotateWithMatrix(rmat, space, mesh);
  87411. };
  87412. /**
  87413. * Set the rotation of the bone to a particular axis angle in local or world space
  87414. * @param axis The axis to rotate the bone on
  87415. * @param angle The angle that the bone should be rotated to
  87416. * @param space The space that the axis is in
  87417. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87418. */
  87419. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  87420. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87421. if (space === BABYLON.Space.LOCAL) {
  87422. var quat = Bone._tmpQuat;
  87423. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  87424. this.setRotationQuaternion(quat, space, mesh);
  87425. return;
  87426. }
  87427. var rotMatInv = Bone._tmpMats[0];
  87428. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87429. return;
  87430. }
  87431. var rotMat = Bone._tmpMats[1];
  87432. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  87433. rotMatInv.multiplyToRef(rotMat, rotMat);
  87434. this._rotateWithMatrix(rotMat, space, mesh);
  87435. };
  87436. /**
  87437. * Set the euler rotation of the bone in local of world space
  87438. * @param rotation The euler rotation that the bone should be set to
  87439. * @param space The space that the rotation is in
  87440. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87441. */
  87442. Bone.prototype.setRotation = function (rotation, space, mesh) {
  87443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87444. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  87445. };
  87446. /**
  87447. * Set the quaternion rotation of the bone in local of world space
  87448. * @param quat The quaternion rotation that the bone should be set to
  87449. * @param space The space that the rotation is in
  87450. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87451. */
  87452. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  87453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87454. if (space === BABYLON.Space.LOCAL) {
  87455. this._decompose();
  87456. this._localRotation.copyFrom(quat);
  87457. this._markAsDirtyAndCompose();
  87458. return;
  87459. }
  87460. var rotMatInv = Bone._tmpMats[0];
  87461. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87462. return;
  87463. }
  87464. var rotMat = Bone._tmpMats[1];
  87465. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  87466. rotMatInv.multiplyToRef(rotMat, rotMat);
  87467. this._rotateWithMatrix(rotMat, space, mesh);
  87468. };
  87469. /**
  87470. * Set the rotation matrix of the bone in local of world space
  87471. * @param rotMat The rotation matrix that the bone should be set to
  87472. * @param space The space that the rotation is in
  87473. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87474. */
  87475. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  87476. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87477. if (space === BABYLON.Space.LOCAL) {
  87478. var quat = Bone._tmpQuat;
  87479. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  87480. this.setRotationQuaternion(quat, space, mesh);
  87481. return;
  87482. }
  87483. var rotMatInv = Bone._tmpMats[0];
  87484. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87485. return;
  87486. }
  87487. var rotMat2 = Bone._tmpMats[1];
  87488. rotMat2.copyFrom(rotMat);
  87489. rotMatInv.multiplyToRef(rotMat, rotMat2);
  87490. this._rotateWithMatrix(rotMat2, space, mesh);
  87491. };
  87492. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  87493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87494. var lmat = this.getLocalMatrix();
  87495. var lx = lmat.m[12];
  87496. var ly = lmat.m[13];
  87497. var lz = lmat.m[14];
  87498. var parent = this.getParent();
  87499. var parentScale = Bone._tmpMats[3];
  87500. var parentScaleInv = Bone._tmpMats[4];
  87501. if (parent && space == BABYLON.Space.WORLD) {
  87502. if (mesh) {
  87503. parentScale.copyFrom(mesh.getWorldMatrix());
  87504. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  87505. }
  87506. else {
  87507. parentScale.copyFrom(parent.getAbsoluteTransform());
  87508. }
  87509. parentScaleInv.copyFrom(parentScale);
  87510. parentScaleInv.invert();
  87511. lmat.multiplyToRef(parentScale, lmat);
  87512. lmat.multiplyToRef(rmat, lmat);
  87513. lmat.multiplyToRef(parentScaleInv, lmat);
  87514. }
  87515. else {
  87516. if (space == BABYLON.Space.WORLD && mesh) {
  87517. parentScale.copyFrom(mesh.getWorldMatrix());
  87518. parentScaleInv.copyFrom(parentScale);
  87519. parentScaleInv.invert();
  87520. lmat.multiplyToRef(parentScale, lmat);
  87521. lmat.multiplyToRef(rmat, lmat);
  87522. lmat.multiplyToRef(parentScaleInv, lmat);
  87523. }
  87524. else {
  87525. lmat.multiplyToRef(rmat, lmat);
  87526. }
  87527. }
  87528. lmat.m[12] = lx;
  87529. lmat.m[13] = ly;
  87530. lmat.m[14] = lz;
  87531. this.computeAbsoluteTransforms();
  87532. this._markAsDirtyAndDecompose();
  87533. };
  87534. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  87535. var scaleMatrix = Bone._tmpMats[2];
  87536. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87537. if (mesh) {
  87538. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87539. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87540. }
  87541. rotMatInv.invert();
  87542. if (isNaN(rotMatInv.m[0])) {
  87543. // Matrix failed to invert.
  87544. // This can happen if scale is zero for example.
  87545. return false;
  87546. }
  87547. scaleMatrix.m[0] *= this._scalingDeterminant;
  87548. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87549. return true;
  87550. };
  87551. /**
  87552. * Get the position of the bone in local or world space
  87553. * @param space The space that the returned position is in
  87554. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87555. * @returns The position of the bone
  87556. */
  87557. Bone.prototype.getPosition = function (space, mesh) {
  87558. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87559. if (mesh === void 0) { mesh = null; }
  87560. var pos = BABYLON.Vector3.Zero();
  87561. this.getPositionToRef(space, mesh, pos);
  87562. return pos;
  87563. };
  87564. /**
  87565. * Copy the position of the bone to a vector3 in local or world space
  87566. * @param space The space that the returned position is in
  87567. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87568. * @param result The vector3 to copy the position to
  87569. */
  87570. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87572. if (space == BABYLON.Space.LOCAL) {
  87573. var lm = this.getLocalMatrix();
  87574. result.x = lm.m[12];
  87575. result.y = lm.m[13];
  87576. result.z = lm.m[14];
  87577. }
  87578. else {
  87579. var wm = null;
  87580. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87581. if (mesh) {
  87582. wm = mesh.getWorldMatrix();
  87583. }
  87584. this._skeleton.computeAbsoluteTransforms();
  87585. var tmat = Bone._tmpMats[0];
  87586. if (mesh && wm) {
  87587. tmat.copyFrom(this.getAbsoluteTransform());
  87588. tmat.multiplyToRef(wm, tmat);
  87589. }
  87590. else {
  87591. tmat = this.getAbsoluteTransform();
  87592. }
  87593. result.x = tmat.m[12];
  87594. result.y = tmat.m[13];
  87595. result.z = tmat.m[14];
  87596. }
  87597. };
  87598. /**
  87599. * Get the absolute position of the bone (world space)
  87600. * @param mesh The mesh that this bone is attached to
  87601. * @returns The absolute position of the bone
  87602. */
  87603. Bone.prototype.getAbsolutePosition = function (mesh) {
  87604. if (mesh === void 0) { mesh = null; }
  87605. var pos = BABYLON.Vector3.Zero();
  87606. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87607. return pos;
  87608. };
  87609. /**
  87610. * Copy the absolute position of the bone (world space) to the result param
  87611. * @param mesh The mesh that this bone is attached to
  87612. * @param result The vector3 to copy the absolute position to
  87613. */
  87614. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87615. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87616. };
  87617. /**
  87618. * Compute the absolute transforms of this bone and its children
  87619. */
  87620. Bone.prototype.computeAbsoluteTransforms = function () {
  87621. this._compose();
  87622. if (this._parent) {
  87623. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87624. }
  87625. else {
  87626. this._absoluteTransform.copyFrom(this._localMatrix);
  87627. var poseMatrix = this._skeleton.getPoseMatrix();
  87628. if (poseMatrix) {
  87629. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87630. }
  87631. }
  87632. var children = this.children;
  87633. var len = children.length;
  87634. for (var i = 0; i < len; i++) {
  87635. children[i].computeAbsoluteTransforms();
  87636. }
  87637. };
  87638. /**
  87639. * Get the world direction from an axis that is in the local space of the bone
  87640. * @param localAxis The local direction that is used to compute the world direction
  87641. * @param mesh The mesh that this bone is attached to
  87642. * @returns The world direction
  87643. */
  87644. Bone.prototype.getDirection = function (localAxis, mesh) {
  87645. if (mesh === void 0) { mesh = null; }
  87646. var result = BABYLON.Vector3.Zero();
  87647. this.getDirectionToRef(localAxis, mesh, result);
  87648. return result;
  87649. };
  87650. /**
  87651. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  87652. * @param localAxis The local direction that is used to compute the world direction
  87653. * @param mesh The mesh that this bone is attached to
  87654. * @param result The vector3 that the world direction will be copied to
  87655. */
  87656. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  87657. if (mesh === void 0) { mesh = null; }
  87658. var wm = null;
  87659. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87660. if (mesh) {
  87661. wm = mesh.getWorldMatrix();
  87662. }
  87663. this._skeleton.computeAbsoluteTransforms();
  87664. var mat = Bone._tmpMats[0];
  87665. mat.copyFrom(this.getAbsoluteTransform());
  87666. if (mesh && wm) {
  87667. mat.multiplyToRef(wm, mat);
  87668. }
  87669. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  87670. result.normalize();
  87671. };
  87672. /**
  87673. * Get the euler rotation of the bone in local or world space
  87674. * @param space The space that the rotation should be in
  87675. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87676. * @returns The euler rotation
  87677. */
  87678. Bone.prototype.getRotation = function (space, mesh) {
  87679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87680. if (mesh === void 0) { mesh = null; }
  87681. var result = BABYLON.Vector3.Zero();
  87682. this.getRotationToRef(space, mesh, result);
  87683. return result;
  87684. };
  87685. /**
  87686. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  87687. * @param space The space that the rotation should be in
  87688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87689. * @param result The vector3 that the rotation should be copied to
  87690. */
  87691. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  87692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87693. if (mesh === void 0) { mesh = null; }
  87694. var quat = Bone._tmpQuat;
  87695. this.getRotationQuaternionToRef(space, mesh, quat);
  87696. quat.toEulerAnglesToRef(result);
  87697. };
  87698. /**
  87699. * Get the quaternion rotation of the bone in either local or world space
  87700. * @param space The space that the rotation should be in
  87701. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87702. * @returns The quaternion rotation
  87703. */
  87704. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  87705. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87706. if (mesh === void 0) { mesh = null; }
  87707. var result = BABYLON.Quaternion.Identity();
  87708. this.getRotationQuaternionToRef(space, mesh, result);
  87709. return result;
  87710. };
  87711. /**
  87712. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  87713. * @param space The space that the rotation should be in
  87714. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87715. * @param result The quaternion that the rotation should be copied to
  87716. */
  87717. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  87718. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87719. if (mesh === void 0) { mesh = null; }
  87720. if (space == BABYLON.Space.LOCAL) {
  87721. this._decompose();
  87722. result.copyFrom(this._localRotation);
  87723. }
  87724. else {
  87725. var mat = Bone._tmpMats[0];
  87726. var amat = this.getAbsoluteTransform();
  87727. if (mesh) {
  87728. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87729. }
  87730. else {
  87731. mat.copyFrom(amat);
  87732. }
  87733. mat.m[0] *= this._scalingDeterminant;
  87734. mat.m[1] *= this._scalingDeterminant;
  87735. mat.m[2] *= this._scalingDeterminant;
  87736. mat.decompose(undefined, result, undefined);
  87737. }
  87738. };
  87739. /**
  87740. * Get the rotation matrix of the bone in local or world space
  87741. * @param space The space that the rotation should be in
  87742. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87743. * @returns The rotation matrix
  87744. */
  87745. Bone.prototype.getRotationMatrix = function (space, mesh) {
  87746. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87747. var result = BABYLON.Matrix.Identity();
  87748. this.getRotationMatrixToRef(space, mesh, result);
  87749. return result;
  87750. };
  87751. /**
  87752. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  87753. * @param space The space that the rotation should be in
  87754. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87755. * @param result The quaternion that the rotation should be copied to
  87756. */
  87757. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  87758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87759. if (space == BABYLON.Space.LOCAL) {
  87760. this.getLocalMatrix().getRotationMatrixToRef(result);
  87761. }
  87762. else {
  87763. var mat = Bone._tmpMats[0];
  87764. var amat = this.getAbsoluteTransform();
  87765. if (mesh) {
  87766. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87767. }
  87768. else {
  87769. mat.copyFrom(amat);
  87770. }
  87771. mat.m[0] *= this._scalingDeterminant;
  87772. mat.m[1] *= this._scalingDeterminant;
  87773. mat.m[2] *= this._scalingDeterminant;
  87774. mat.getRotationMatrixToRef(result);
  87775. }
  87776. };
  87777. /**
  87778. * Get the world position of a point that is in the local space of the bone
  87779. * @param position The local position
  87780. * @param mesh The mesh that this bone is attached to
  87781. * @returns The world position
  87782. */
  87783. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  87784. if (mesh === void 0) { mesh = null; }
  87785. var result = BABYLON.Vector3.Zero();
  87786. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  87787. return result;
  87788. };
  87789. /**
  87790. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  87791. * @param position The local position
  87792. * @param mesh The mesh that this bone is attached to
  87793. * @param result The vector3 that the world position should be copied to
  87794. */
  87795. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  87796. if (mesh === void 0) { mesh = null; }
  87797. var wm = null;
  87798. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87799. if (mesh) {
  87800. wm = mesh.getWorldMatrix();
  87801. }
  87802. this._skeleton.computeAbsoluteTransforms();
  87803. var tmat = Bone._tmpMats[0];
  87804. if (mesh && wm) {
  87805. tmat.copyFrom(this.getAbsoluteTransform());
  87806. tmat.multiplyToRef(wm, tmat);
  87807. }
  87808. else {
  87809. tmat = this.getAbsoluteTransform();
  87810. }
  87811. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87812. };
  87813. /**
  87814. * Get the local position of a point that is in world space
  87815. * @param position The world position
  87816. * @param mesh The mesh that this bone is attached to
  87817. * @returns The local position
  87818. */
  87819. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  87820. if (mesh === void 0) { mesh = null; }
  87821. var result = BABYLON.Vector3.Zero();
  87822. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  87823. return result;
  87824. };
  87825. /**
  87826. * Get the local position of a point that is in world space and copy it to the result param
  87827. * @param position The world position
  87828. * @param mesh The mesh that this bone is attached to
  87829. * @param result The vector3 that the local position should be copied to
  87830. */
  87831. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  87832. if (mesh === void 0) { mesh = null; }
  87833. var wm = null;
  87834. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87835. if (mesh) {
  87836. wm = mesh.getWorldMatrix();
  87837. }
  87838. this._skeleton.computeAbsoluteTransforms();
  87839. var tmat = Bone._tmpMats[0];
  87840. tmat.copyFrom(this.getAbsoluteTransform());
  87841. if (mesh && wm) {
  87842. tmat.multiplyToRef(wm, tmat);
  87843. }
  87844. tmat.invert();
  87845. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87846. };
  87847. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87848. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  87849. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87850. return Bone;
  87851. }(BABYLON.Node));
  87852. BABYLON.Bone = Bone;
  87853. })(BABYLON || (BABYLON = {}));
  87854. //# sourceMappingURL=babylon.bone.js.map
  87855. var BABYLON;
  87856. (function (BABYLON) {
  87857. /**
  87858. * Class used to apply inverse kinematics to bones
  87859. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  87860. */
  87861. var BoneIKController = /** @class */ (function () {
  87862. /**
  87863. * Creates a new BoneIKController
  87864. * @param mesh defines the mesh to control
  87865. * @param bone defines the bone to control
  87866. * @param options defines options to set up the controller
  87867. */
  87868. function BoneIKController(mesh, bone, options) {
  87869. /**
  87870. * Gets or sets the target position
  87871. */
  87872. this.targetPosition = BABYLON.Vector3.Zero();
  87873. /**
  87874. * Gets or sets the pole target position
  87875. */
  87876. this.poleTargetPosition = BABYLON.Vector3.Zero();
  87877. /**
  87878. * Gets or sets the pole target local offset
  87879. */
  87880. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  87881. /**
  87882. * Gets or sets the pole angle
  87883. */
  87884. this.poleAngle = 0;
  87885. /**
  87886. * 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)
  87887. */
  87888. this.slerpAmount = 1;
  87889. this._bone1Quat = BABYLON.Quaternion.Identity();
  87890. this._bone1Mat = BABYLON.Matrix.Identity();
  87891. this._bone2Ang = Math.PI;
  87892. this._maxAngle = Math.PI;
  87893. this._rightHandedSystem = false;
  87894. this._bendAxis = BABYLON.Vector3.Right();
  87895. this._slerping = false;
  87896. this._adjustRoll = 0;
  87897. this._bone2 = bone;
  87898. this._bone1 = bone.getParent();
  87899. if (!this._bone1) {
  87900. return;
  87901. }
  87902. this.mesh = mesh;
  87903. var bonePos = bone.getPosition();
  87904. if (bone.getAbsoluteTransform().determinant() > 0) {
  87905. this._rightHandedSystem = true;
  87906. this._bendAxis.x = 0;
  87907. this._bendAxis.y = 0;
  87908. this._bendAxis.z = -1;
  87909. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87910. this._adjustRoll = Math.PI * .5;
  87911. this._bendAxis.z = 1;
  87912. }
  87913. }
  87914. if (this._bone1.length) {
  87915. var boneScale1 = this._bone1.getScale();
  87916. var boneScale2 = this._bone2.getScale();
  87917. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87918. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87919. }
  87920. else if (this._bone1.children[0]) {
  87921. mesh.computeWorldMatrix(true);
  87922. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87923. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87924. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87925. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87926. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87927. }
  87928. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87929. this.maxAngle = Math.PI;
  87930. if (options) {
  87931. if (options.targetMesh) {
  87932. this.targetMesh = options.targetMesh;
  87933. this.targetMesh.computeWorldMatrix(true);
  87934. }
  87935. if (options.poleTargetMesh) {
  87936. this.poleTargetMesh = options.poleTargetMesh;
  87937. this.poleTargetMesh.computeWorldMatrix(true);
  87938. }
  87939. else if (options.poleTargetBone) {
  87940. this.poleTargetBone = options.poleTargetBone;
  87941. }
  87942. else if (this._bone1.getParent()) {
  87943. this.poleTargetBone = this._bone1.getParent();
  87944. }
  87945. if (options.poleTargetLocalOffset) {
  87946. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87947. }
  87948. if (options.poleAngle) {
  87949. this.poleAngle = options.poleAngle;
  87950. }
  87951. if (options.bendAxis) {
  87952. this._bendAxis.copyFrom(options.bendAxis);
  87953. }
  87954. if (options.maxAngle) {
  87955. this.maxAngle = options.maxAngle;
  87956. }
  87957. if (options.slerpAmount) {
  87958. this.slerpAmount = options.slerpAmount;
  87959. }
  87960. }
  87961. }
  87962. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87963. /**
  87964. * Gets or sets maximum allowed angle
  87965. */
  87966. get: function () {
  87967. return this._maxAngle;
  87968. },
  87969. set: function (value) {
  87970. this._setMaxAngle(value);
  87971. },
  87972. enumerable: true,
  87973. configurable: true
  87974. });
  87975. BoneIKController.prototype._setMaxAngle = function (ang) {
  87976. if (ang < 0) {
  87977. ang = 0;
  87978. }
  87979. if (ang > Math.PI || ang == undefined) {
  87980. ang = Math.PI;
  87981. }
  87982. this._maxAngle = ang;
  87983. var a = this._bone1Length;
  87984. var b = this._bone2Length;
  87985. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87986. };
  87987. /**
  87988. * Force the controller to update the bones
  87989. */
  87990. BoneIKController.prototype.update = function () {
  87991. var bone1 = this._bone1;
  87992. if (!bone1) {
  87993. return;
  87994. }
  87995. var target = this.targetPosition;
  87996. var poleTarget = this.poleTargetPosition;
  87997. var mat1 = BoneIKController._tmpMats[0];
  87998. var mat2 = BoneIKController._tmpMats[1];
  87999. if (this.targetMesh) {
  88000. target.copyFrom(this.targetMesh.getAbsolutePosition());
  88001. }
  88002. if (this.poleTargetBone) {
  88003. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  88004. }
  88005. else if (this.poleTargetMesh) {
  88006. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  88007. }
  88008. var bonePos = BoneIKController._tmpVecs[0];
  88009. var zaxis = BoneIKController._tmpVecs[1];
  88010. var xaxis = BoneIKController._tmpVecs[2];
  88011. var yaxis = BoneIKController._tmpVecs[3];
  88012. var upAxis = BoneIKController._tmpVecs[4];
  88013. var _tmpQuat = BoneIKController._tmpQuat;
  88014. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  88015. poleTarget.subtractToRef(bonePos, upAxis);
  88016. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  88017. upAxis.y = 1;
  88018. }
  88019. else {
  88020. upAxis.normalize();
  88021. }
  88022. target.subtractToRef(bonePos, yaxis);
  88023. yaxis.normalize();
  88024. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  88025. zaxis.normalize();
  88026. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  88027. xaxis.normalize();
  88028. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  88029. var a = this._bone1Length;
  88030. var b = this._bone2Length;
  88031. var c = BABYLON.Vector3.Distance(bonePos, target);
  88032. if (this._maxReach > 0) {
  88033. c = Math.min(this._maxReach, c);
  88034. }
  88035. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  88036. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  88037. if (acosa > 1) {
  88038. acosa = 1;
  88039. }
  88040. if (acosb > 1) {
  88041. acosb = 1;
  88042. }
  88043. if (acosa < -1) {
  88044. acosa = -1;
  88045. }
  88046. if (acosb < -1) {
  88047. acosb = -1;
  88048. }
  88049. var angA = Math.acos(acosa);
  88050. var angB = Math.acos(acosb);
  88051. var angC = -angA - angB;
  88052. if (this._rightHandedSystem) {
  88053. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  88054. mat2.multiplyToRef(mat1, mat1);
  88055. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  88056. mat2.multiplyToRef(mat1, mat1);
  88057. }
  88058. else {
  88059. var _tmpVec = BoneIKController._tmpVecs[5];
  88060. _tmpVec.copyFrom(this._bendAxis);
  88061. _tmpVec.x *= -1;
  88062. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  88063. mat2.multiplyToRef(mat1, mat1);
  88064. }
  88065. if (this.poleAngle) {
  88066. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  88067. mat1.multiplyToRef(mat2, mat1);
  88068. }
  88069. if (this._bone1) {
  88070. if (this.slerpAmount < 1) {
  88071. if (!this._slerping) {
  88072. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  88073. }
  88074. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  88075. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  88076. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  88077. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  88078. this._slerping = true;
  88079. }
  88080. else {
  88081. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  88082. this._bone1Mat.copyFrom(mat1);
  88083. this._slerping = false;
  88084. }
  88085. }
  88086. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  88087. this._bone2Ang = angC;
  88088. };
  88089. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88090. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  88091. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88092. return BoneIKController;
  88093. }());
  88094. BABYLON.BoneIKController = BoneIKController;
  88095. })(BABYLON || (BABYLON = {}));
  88096. //# sourceMappingURL=babylon.boneIKController.js.map
  88097. var BABYLON;
  88098. (function (BABYLON) {
  88099. /**
  88100. * Class used to make a bone look toward a point in space
  88101. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  88102. */
  88103. var BoneLookController = /** @class */ (function () {
  88104. /**
  88105. * Create a BoneLookController
  88106. * @param mesh the mesh that the bone belongs to
  88107. * @param bone the bone that will be looking to the target
  88108. * @param target the target Vector3 to look at
  88109. * @param settings optional settings:
  88110. * * maxYaw: the maximum angle the bone will yaw to
  88111. * * minYaw: the minimum angle the bone will yaw to
  88112. * * maxPitch: the maximum angle the bone will pitch to
  88113. * * minPitch: the minimum angle the bone will yaw to
  88114. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  88115. * * upAxis: the up axis of the coordinate system
  88116. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  88117. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  88118. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  88119. * * adjustYaw: used to make an adjustment to the yaw of the bone
  88120. * * adjustPitch: used to make an adjustment to the pitch of the bone
  88121. * * adjustRoll: used to make an adjustment to the roll of the bone
  88122. **/
  88123. function BoneLookController(mesh, bone, target, options) {
  88124. /**
  88125. * The up axis of the coordinate system that is used when the bone is rotated
  88126. */
  88127. this.upAxis = BABYLON.Vector3.Up();
  88128. /**
  88129. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  88130. */
  88131. this.upAxisSpace = BABYLON.Space.LOCAL;
  88132. /**
  88133. * Used to make an adjustment to the yaw of the bone
  88134. */
  88135. this.adjustYaw = 0;
  88136. /**
  88137. * Used to make an adjustment to the pitch of the bone
  88138. */
  88139. this.adjustPitch = 0;
  88140. /**
  88141. * Used to make an adjustment to the roll of the bone
  88142. */
  88143. this.adjustRoll = 0;
  88144. /**
  88145. * 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)
  88146. */
  88147. this.slerpAmount = 1;
  88148. this._boneQuat = BABYLON.Quaternion.Identity();
  88149. this._slerping = false;
  88150. this._firstFrameSkipped = false;
  88151. this._fowardAxis = BABYLON.Vector3.Forward();
  88152. this.mesh = mesh;
  88153. this.bone = bone;
  88154. this.target = target;
  88155. if (options) {
  88156. if (options.adjustYaw) {
  88157. this.adjustYaw = options.adjustYaw;
  88158. }
  88159. if (options.adjustPitch) {
  88160. this.adjustPitch = options.adjustPitch;
  88161. }
  88162. if (options.adjustRoll) {
  88163. this.adjustRoll = options.adjustRoll;
  88164. }
  88165. if (options.maxYaw != null) {
  88166. this.maxYaw = options.maxYaw;
  88167. }
  88168. else {
  88169. this.maxYaw = Math.PI;
  88170. }
  88171. if (options.minYaw != null) {
  88172. this.minYaw = options.minYaw;
  88173. }
  88174. else {
  88175. this.minYaw = -Math.PI;
  88176. }
  88177. if (options.maxPitch != null) {
  88178. this.maxPitch = options.maxPitch;
  88179. }
  88180. else {
  88181. this.maxPitch = Math.PI;
  88182. }
  88183. if (options.minPitch != null) {
  88184. this.minPitch = options.minPitch;
  88185. }
  88186. else {
  88187. this.minPitch = -Math.PI;
  88188. }
  88189. if (options.slerpAmount != null) {
  88190. this.slerpAmount = options.slerpAmount;
  88191. }
  88192. if (options.upAxis != null) {
  88193. this.upAxis = options.upAxis;
  88194. }
  88195. if (options.upAxisSpace != null) {
  88196. this.upAxisSpace = options.upAxisSpace;
  88197. }
  88198. if (options.yawAxis != null || options.pitchAxis != null) {
  88199. var newYawAxis = BABYLON.Axis.Y;
  88200. var newPitchAxis = BABYLON.Axis.X;
  88201. if (options.yawAxis != null) {
  88202. newYawAxis = options.yawAxis.clone();
  88203. newYawAxis.normalize();
  88204. }
  88205. if (options.pitchAxis != null) {
  88206. newPitchAxis = options.pitchAxis.clone();
  88207. newPitchAxis.normalize();
  88208. }
  88209. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  88210. this._transformYawPitch = BABYLON.Matrix.Identity();
  88211. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  88212. this._transformYawPitchInv = this._transformYawPitch.clone();
  88213. this._transformYawPitch.invert();
  88214. }
  88215. }
  88216. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  88217. this.upAxisSpace = BABYLON.Space.LOCAL;
  88218. }
  88219. }
  88220. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  88221. /**
  88222. * Gets or sets the minimum yaw angle that the bone can look to
  88223. */
  88224. get: function () {
  88225. return this._minYaw;
  88226. },
  88227. set: function (value) {
  88228. this._minYaw = value;
  88229. this._minYawSin = Math.sin(value);
  88230. this._minYawCos = Math.cos(value);
  88231. if (this._maxYaw != null) {
  88232. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88233. this._yawRange = this._maxYaw - this._minYaw;
  88234. }
  88235. },
  88236. enumerable: true,
  88237. configurable: true
  88238. });
  88239. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  88240. /**
  88241. * Gets or sets the maximum yaw angle that the bone can look to
  88242. */
  88243. get: function () {
  88244. return this._maxYaw;
  88245. },
  88246. set: function (value) {
  88247. this._maxYaw = value;
  88248. this._maxYawSin = Math.sin(value);
  88249. this._maxYawCos = Math.cos(value);
  88250. if (this._minYaw != null) {
  88251. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88252. this._yawRange = this._maxYaw - this._minYaw;
  88253. }
  88254. },
  88255. enumerable: true,
  88256. configurable: true
  88257. });
  88258. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  88259. /**
  88260. * Gets or sets the minimum pitch angle that the bone can look to
  88261. */
  88262. get: function () {
  88263. return this._minPitch;
  88264. },
  88265. set: function (value) {
  88266. this._minPitch = value;
  88267. this._minPitchTan = Math.tan(value);
  88268. },
  88269. enumerable: true,
  88270. configurable: true
  88271. });
  88272. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  88273. /**
  88274. * Gets or sets the maximum pitch angle that the bone can look to
  88275. */
  88276. get: function () {
  88277. return this._maxPitch;
  88278. },
  88279. set: function (value) {
  88280. this._maxPitch = value;
  88281. this._maxPitchTan = Math.tan(value);
  88282. },
  88283. enumerable: true,
  88284. configurable: true
  88285. });
  88286. /**
  88287. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  88288. */
  88289. BoneLookController.prototype.update = function () {
  88290. //skip the first frame when slerping so that the mesh rotation is correct
  88291. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  88292. this._firstFrameSkipped = true;
  88293. return;
  88294. }
  88295. var bone = this.bone;
  88296. var bonePos = BoneLookController._tmpVecs[0];
  88297. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  88298. var target = this.target;
  88299. var _tmpMat1 = BoneLookController._tmpMats[0];
  88300. var _tmpMat2 = BoneLookController._tmpMats[1];
  88301. var mesh = this.mesh;
  88302. var parentBone = bone.getParent();
  88303. var upAxis = BoneLookController._tmpVecs[1];
  88304. upAxis.copyFrom(this.upAxis);
  88305. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  88306. if (this._transformYawPitch) {
  88307. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  88308. }
  88309. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  88310. }
  88311. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  88312. mesh.getDirectionToRef(upAxis, upAxis);
  88313. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  88314. upAxis.normalize();
  88315. }
  88316. }
  88317. var checkYaw = false;
  88318. var checkPitch = false;
  88319. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  88320. checkYaw = true;
  88321. }
  88322. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  88323. checkPitch = true;
  88324. }
  88325. if (checkYaw || checkPitch) {
  88326. var spaceMat = BoneLookController._tmpMats[2];
  88327. var spaceMatInv = BoneLookController._tmpMats[3];
  88328. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  88329. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  88330. }
  88331. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  88332. spaceMat.copyFrom(mesh.getWorldMatrix());
  88333. }
  88334. else {
  88335. var forwardAxis = BoneLookController._tmpVecs[2];
  88336. forwardAxis.copyFrom(this._fowardAxis);
  88337. if (this._transformYawPitch) {
  88338. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  88339. }
  88340. if (parentBone) {
  88341. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  88342. }
  88343. else {
  88344. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  88345. }
  88346. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  88347. rightAxis.normalize();
  88348. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  88349. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  88350. }
  88351. spaceMat.invertToRef(spaceMatInv);
  88352. var xzlen = null;
  88353. if (checkPitch) {
  88354. var localTarget = BoneLookController._tmpVecs[3];
  88355. target.subtractToRef(bonePos, localTarget);
  88356. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88357. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88358. var pitch = Math.atan2(localTarget.y, xzlen);
  88359. var newPitch = pitch;
  88360. if (pitch > this._maxPitch) {
  88361. localTarget.y = this._maxPitchTan * xzlen;
  88362. newPitch = this._maxPitch;
  88363. }
  88364. else if (pitch < this._minPitch) {
  88365. localTarget.y = this._minPitchTan * xzlen;
  88366. newPitch = this._minPitch;
  88367. }
  88368. if (pitch != newPitch) {
  88369. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88370. localTarget.addInPlace(bonePos);
  88371. target = localTarget;
  88372. }
  88373. }
  88374. if (checkYaw) {
  88375. var localTarget = BoneLookController._tmpVecs[4];
  88376. target.subtractToRef(bonePos, localTarget);
  88377. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88378. var yaw = Math.atan2(localTarget.x, localTarget.z);
  88379. var newYaw = yaw;
  88380. if (yaw > this._maxYaw || yaw < this._minYaw) {
  88381. if (xzlen == null) {
  88382. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88383. }
  88384. if (this._yawRange > Math.PI) {
  88385. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  88386. localTarget.z = this._maxYawCos * xzlen;
  88387. localTarget.x = this._maxYawSin * xzlen;
  88388. newYaw = this._maxYaw;
  88389. }
  88390. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  88391. localTarget.z = this._minYawCos * xzlen;
  88392. localTarget.x = this._minYawSin * xzlen;
  88393. newYaw = this._minYaw;
  88394. }
  88395. }
  88396. else {
  88397. if (yaw > this._maxYaw) {
  88398. localTarget.z = this._maxYawCos * xzlen;
  88399. localTarget.x = this._maxYawSin * xzlen;
  88400. newYaw = this._maxYaw;
  88401. }
  88402. else if (yaw < this._minYaw) {
  88403. localTarget.z = this._minYawCos * xzlen;
  88404. localTarget.x = this._minYawSin * xzlen;
  88405. newYaw = this._minYaw;
  88406. }
  88407. }
  88408. }
  88409. if (this._slerping && this._yawRange > Math.PI) {
  88410. //are we going to be crossing into the min/max region?
  88411. var boneFwd = BoneLookController._tmpVecs[8];
  88412. boneFwd.copyFrom(BABYLON.Axis.Z);
  88413. if (this._transformYawPitch) {
  88414. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  88415. }
  88416. var boneRotMat = BoneLookController._tmpMats[4];
  88417. this._boneQuat.toRotationMatrix(boneRotMat);
  88418. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  88419. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  88420. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  88421. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  88422. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  88423. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  88424. if (angBtwTar > angBtwMidYaw) {
  88425. if (xzlen == null) {
  88426. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88427. }
  88428. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  88429. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  88430. if (angBtwMin < angBtwMax) {
  88431. newYaw = boneYaw + Math.PI * .75;
  88432. localTarget.z = Math.cos(newYaw) * xzlen;
  88433. localTarget.x = Math.sin(newYaw) * xzlen;
  88434. }
  88435. else {
  88436. newYaw = boneYaw - Math.PI * .75;
  88437. localTarget.z = Math.cos(newYaw) * xzlen;
  88438. localTarget.x = Math.sin(newYaw) * xzlen;
  88439. }
  88440. }
  88441. }
  88442. if (yaw != newYaw) {
  88443. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88444. localTarget.addInPlace(bonePos);
  88445. target = localTarget;
  88446. }
  88447. }
  88448. }
  88449. var zaxis = BoneLookController._tmpVecs[5];
  88450. var xaxis = BoneLookController._tmpVecs[6];
  88451. var yaxis = BoneLookController._tmpVecs[7];
  88452. var _tmpQuat = BoneLookController._tmpQuat;
  88453. target.subtractToRef(bonePos, zaxis);
  88454. zaxis.normalize();
  88455. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  88456. xaxis.normalize();
  88457. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  88458. yaxis.normalize();
  88459. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  88460. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  88461. return;
  88462. }
  88463. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  88464. return;
  88465. }
  88466. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  88467. return;
  88468. }
  88469. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  88470. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  88471. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  88472. }
  88473. if (this.slerpAmount < 1) {
  88474. if (!this._slerping) {
  88475. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  88476. }
  88477. if (this._transformYawPitch) {
  88478. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88479. }
  88480. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  88481. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  88482. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  88483. this._slerping = true;
  88484. }
  88485. else {
  88486. if (this._transformYawPitch) {
  88487. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88488. }
  88489. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  88490. this._slerping = false;
  88491. }
  88492. };
  88493. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  88494. var angDiff = ang2 - ang1;
  88495. angDiff %= Math.PI * 2;
  88496. if (angDiff > Math.PI) {
  88497. angDiff -= Math.PI * 2;
  88498. }
  88499. else if (angDiff < -Math.PI) {
  88500. angDiff += Math.PI * 2;
  88501. }
  88502. return angDiff;
  88503. };
  88504. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  88505. ang1 %= (2 * Math.PI);
  88506. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88507. ang2 %= (2 * Math.PI);
  88508. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88509. var ab = 0;
  88510. if (ang1 < ang2) {
  88511. ab = ang2 - ang1;
  88512. }
  88513. else {
  88514. ab = ang1 - ang2;
  88515. }
  88516. if (ab > Math.PI) {
  88517. ab = Math.PI * 2 - ab;
  88518. }
  88519. return ab;
  88520. };
  88521. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  88522. ang %= (2 * Math.PI);
  88523. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  88524. ang1 %= (2 * Math.PI);
  88525. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88526. ang2 %= (2 * Math.PI);
  88527. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88528. if (ang1 < ang2) {
  88529. if (ang > ang1 && ang < ang2) {
  88530. return true;
  88531. }
  88532. }
  88533. else {
  88534. if (ang > ang2 && ang < ang1) {
  88535. return true;
  88536. }
  88537. }
  88538. return false;
  88539. };
  88540. 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()];
  88541. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88542. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88543. return BoneLookController;
  88544. }());
  88545. BABYLON.BoneLookController = BoneLookController;
  88546. })(BABYLON || (BABYLON = {}));
  88547. //# sourceMappingURL=babylon.boneLookController.js.map
  88548. var BABYLON;
  88549. (function (BABYLON) {
  88550. /**
  88551. * Class used to handle skinning animations
  88552. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88553. */
  88554. var Skeleton = /** @class */ (function () {
  88555. /**
  88556. * Creates a new skeleton
  88557. * @param name defines the skeleton name
  88558. * @param id defines the skeleton Id
  88559. * @param scene defines the hosting scene
  88560. */
  88561. function Skeleton(
  88562. /** defines the skeleton name */
  88563. name,
  88564. /** defines the skeleton Id */
  88565. id, scene) {
  88566. this.name = name;
  88567. this.id = id;
  88568. /**
  88569. * Gets the list of child bones
  88570. */
  88571. this.bones = new Array();
  88572. /**
  88573. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88574. */
  88575. this.needInitialSkinMatrix = false;
  88576. this._isDirty = true;
  88577. this._meshesWithPoseMatrix = new Array();
  88578. this._identity = BABYLON.Matrix.Identity();
  88579. this._ranges = {};
  88580. this._lastAbsoluteTransformsUpdateId = -1;
  88581. /**
  88582. * Specifies if the skeleton should be serialized
  88583. */
  88584. this.doNotSerialize = false;
  88585. this._animationPropertiesOverride = null;
  88586. // Events
  88587. /**
  88588. * An observable triggered before computing the skeleton's matrices
  88589. */
  88590. this.onBeforeComputeObservable = new BABYLON.Observable();
  88591. this.bones = [];
  88592. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88593. scene.skeletons.push(this);
  88594. //make sure it will recalculate the matrix next time prepare is called.
  88595. this._isDirty = true;
  88596. }
  88597. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88598. /**
  88599. * Gets or sets the animation properties override
  88600. */
  88601. get: function () {
  88602. if (!this._animationPropertiesOverride) {
  88603. return this._scene.animationPropertiesOverride;
  88604. }
  88605. return this._animationPropertiesOverride;
  88606. },
  88607. set: function (value) {
  88608. this._animationPropertiesOverride = value;
  88609. },
  88610. enumerable: true,
  88611. configurable: true
  88612. });
  88613. // Members
  88614. /**
  88615. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88616. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88617. * @returns a Float32Array containing matrices data
  88618. */
  88619. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88620. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88621. return mesh._bonesTransformMatrices;
  88622. }
  88623. if (!this._transformMatrices) {
  88624. this.prepare();
  88625. }
  88626. return this._transformMatrices;
  88627. };
  88628. /**
  88629. * Gets the current hosting scene
  88630. * @returns a scene object
  88631. */
  88632. Skeleton.prototype.getScene = function () {
  88633. return this._scene;
  88634. };
  88635. // Methods
  88636. /**
  88637. * Gets a string representing the current skeleton data
  88638. * @param fullDetails defines a boolean indicating if we want a verbose version
  88639. * @returns a string representing the current skeleton data
  88640. */
  88641. Skeleton.prototype.toString = function (fullDetails) {
  88642. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88643. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88644. if (fullDetails) {
  88645. ret += ", Ranges: {";
  88646. var first = true;
  88647. for (var name_1 in this._ranges) {
  88648. if (first) {
  88649. ret += ", ";
  88650. first = false;
  88651. }
  88652. ret += name_1;
  88653. }
  88654. ret += "}";
  88655. }
  88656. return ret;
  88657. };
  88658. /**
  88659. * Get bone's index searching by name
  88660. * @param name defines bone's name to search for
  88661. * @return the indice of the bone. Returns -1 if not found
  88662. */
  88663. Skeleton.prototype.getBoneIndexByName = function (name) {
  88664. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  88665. if (this.bones[boneIndex].name === name) {
  88666. return boneIndex;
  88667. }
  88668. }
  88669. return -1;
  88670. };
  88671. /**
  88672. * Creater a new animation range
  88673. * @param name defines the name of the range
  88674. * @param from defines the start key
  88675. * @param to defines the end key
  88676. */
  88677. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  88678. // check name not already in use
  88679. if (!this._ranges[name]) {
  88680. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  88681. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88682. if (this.bones[i].animations[0]) {
  88683. this.bones[i].animations[0].createRange(name, from, to);
  88684. }
  88685. }
  88686. }
  88687. };
  88688. /**
  88689. * Delete a specific animation range
  88690. * @param name defines the name of the range
  88691. * @param deleteFrames defines if frames must be removed as well
  88692. */
  88693. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  88694. if (deleteFrames === void 0) { deleteFrames = true; }
  88695. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88696. if (this.bones[i].animations[0]) {
  88697. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  88698. }
  88699. }
  88700. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  88701. };
  88702. /**
  88703. * Gets a specific animation range
  88704. * @param name defines the name of the range to look for
  88705. * @returns the requested animation range or null if not found
  88706. */
  88707. Skeleton.prototype.getAnimationRange = function (name) {
  88708. return this._ranges[name];
  88709. };
  88710. /**
  88711. * Gets the list of all animation ranges defined on this skeleton
  88712. * @returns an array
  88713. */
  88714. Skeleton.prototype.getAnimationRanges = function () {
  88715. var animationRanges = [];
  88716. var name;
  88717. var i = 0;
  88718. for (name in this._ranges) {
  88719. animationRanges[i] = this._ranges[name];
  88720. i++;
  88721. }
  88722. return animationRanges;
  88723. };
  88724. /**
  88725. * Copy animation range from a source skeleton.
  88726. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  88727. * @param source defines the source skeleton
  88728. * @param name defines the name of the range to copy
  88729. * @param rescaleAsRequired defines if rescaling must be applied if required
  88730. * @returns true if operation was successful
  88731. */
  88732. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  88733. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88734. if (this._ranges[name] || !source.getAnimationRange(name)) {
  88735. return false;
  88736. }
  88737. var ret = true;
  88738. var frameOffset = this._getHighestAnimationFrame() + 1;
  88739. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  88740. var boneDict = {};
  88741. var sourceBones = source.bones;
  88742. var nBones;
  88743. var i;
  88744. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  88745. boneDict[sourceBones[i].name] = sourceBones[i];
  88746. }
  88747. if (this.bones.length !== sourceBones.length) {
  88748. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  88749. ret = false;
  88750. }
  88751. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  88752. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  88753. var boneName = this.bones[i].name;
  88754. var sourceBone = boneDict[boneName];
  88755. if (sourceBone) {
  88756. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  88757. }
  88758. else {
  88759. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  88760. ret = false;
  88761. }
  88762. }
  88763. // do not call createAnimationRange(), since it also is done to bones, which was already done
  88764. var range = source.getAnimationRange(name);
  88765. if (range) {
  88766. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  88767. }
  88768. return ret;
  88769. };
  88770. /**
  88771. * Forces the skeleton to go to rest pose
  88772. */
  88773. Skeleton.prototype.returnToRest = function () {
  88774. for (var index = 0; index < this.bones.length; index++) {
  88775. this.bones[index].returnToRest();
  88776. }
  88777. };
  88778. Skeleton.prototype._getHighestAnimationFrame = function () {
  88779. var ret = 0;
  88780. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88781. if (this.bones[i].animations[0]) {
  88782. var highest = this.bones[i].animations[0].getHighestFrame();
  88783. if (ret < highest) {
  88784. ret = highest;
  88785. }
  88786. }
  88787. }
  88788. return ret;
  88789. };
  88790. /**
  88791. * Begin a specific animation range
  88792. * @param name defines the name of the range to start
  88793. * @param loop defines if looping must be turned on (false by default)
  88794. * @param speedRatio defines the speed ratio to apply (1 by default)
  88795. * @param onAnimationEnd defines a callback which will be called when animation will end
  88796. * @returns a new animatable
  88797. */
  88798. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  88799. var range = this.getAnimationRange(name);
  88800. if (!range) {
  88801. return null;
  88802. }
  88803. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  88804. };
  88805. /** @hidden */
  88806. Skeleton.prototype._markAsDirty = function () {
  88807. this._isDirty = true;
  88808. };
  88809. /** @hidden */
  88810. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  88811. this._meshesWithPoseMatrix.push(mesh);
  88812. };
  88813. /** @hidden */
  88814. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  88815. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  88816. if (index > -1) {
  88817. this._meshesWithPoseMatrix.splice(index, 1);
  88818. }
  88819. };
  88820. /** @hidden */
  88821. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  88822. this.onBeforeComputeObservable.notifyObservers(this);
  88823. for (var index = 0; index < this.bones.length; index++) {
  88824. var bone = this.bones[index];
  88825. var parentBone = bone.getParent();
  88826. if (parentBone) {
  88827. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  88828. }
  88829. else {
  88830. if (initialSkinMatrix) {
  88831. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  88832. }
  88833. else {
  88834. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  88835. }
  88836. }
  88837. if (bone._index !== -1) {
  88838. var mappedIndex = bone._index === null ? index : bone._index;
  88839. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  88840. }
  88841. }
  88842. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  88843. };
  88844. /**
  88845. * Build all resources required to render a skeleton
  88846. */
  88847. Skeleton.prototype.prepare = function () {
  88848. if (!this._isDirty) {
  88849. return;
  88850. }
  88851. if (this.needInitialSkinMatrix) {
  88852. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  88853. var mesh = this._meshesWithPoseMatrix[index];
  88854. var poseMatrix = mesh.getPoseMatrix();
  88855. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  88856. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88857. }
  88858. if (this._synchronizedWithMesh !== mesh) {
  88859. this._synchronizedWithMesh = mesh;
  88860. // Prepare bones
  88861. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  88862. var bone = this.bones[boneIndex];
  88863. if (!bone.getParent()) {
  88864. var matrix = bone.getBaseMatrix();
  88865. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  88866. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  88867. }
  88868. }
  88869. }
  88870. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  88871. }
  88872. }
  88873. else {
  88874. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  88875. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88876. }
  88877. this._computeTransformMatrices(this._transformMatrices, null);
  88878. }
  88879. this._isDirty = false;
  88880. this._scene._activeBones.addCount(this.bones.length, false);
  88881. };
  88882. /**
  88883. * Gets the list of animatables currently running for this skeleton
  88884. * @returns an array of animatables
  88885. */
  88886. Skeleton.prototype.getAnimatables = function () {
  88887. if (!this._animatables || this._animatables.length !== this.bones.length) {
  88888. this._animatables = [];
  88889. for (var index = 0; index < this.bones.length; index++) {
  88890. this._animatables.push(this.bones[index]);
  88891. }
  88892. }
  88893. return this._animatables;
  88894. };
  88895. /**
  88896. * Clone the current skeleton
  88897. * @param name defines the name of the new skeleton
  88898. * @param id defines the id of the enw skeleton
  88899. * @returns the new skeleton
  88900. */
  88901. Skeleton.prototype.clone = function (name, id) {
  88902. var result = new Skeleton(name, id || name, this._scene);
  88903. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88904. for (var index = 0; index < this.bones.length; index++) {
  88905. var source = this.bones[index];
  88906. var parentBone = null;
  88907. var parent_1 = source.getParent();
  88908. if (parent_1) {
  88909. var parentIndex = this.bones.indexOf(parent_1);
  88910. parentBone = result.bones[parentIndex];
  88911. }
  88912. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88913. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88914. }
  88915. if (this._ranges) {
  88916. result._ranges = {};
  88917. for (var rangeName in this._ranges) {
  88918. var range = this._ranges[rangeName];
  88919. if (range) {
  88920. result._ranges[rangeName] = range.clone();
  88921. }
  88922. }
  88923. }
  88924. this._isDirty = true;
  88925. return result;
  88926. };
  88927. /**
  88928. * Enable animation blending for this skeleton
  88929. * @param blendingSpeed defines the blending speed to apply
  88930. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88931. */
  88932. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88933. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88934. this.bones.forEach(function (bone) {
  88935. bone.animations.forEach(function (animation) {
  88936. animation.enableBlending = true;
  88937. animation.blendingSpeed = blendingSpeed;
  88938. });
  88939. });
  88940. };
  88941. /**
  88942. * Releases all resources associated with the current skeleton
  88943. */
  88944. Skeleton.prototype.dispose = function () {
  88945. this._meshesWithPoseMatrix = [];
  88946. // Animations
  88947. this.getScene().stopAnimation(this);
  88948. // Remove from scene
  88949. this.getScene().removeSkeleton(this);
  88950. };
  88951. /**
  88952. * Serialize the skeleton in a JSON object
  88953. * @returns a JSON object
  88954. */
  88955. Skeleton.prototype.serialize = function () {
  88956. var serializationObject = {};
  88957. serializationObject.name = this.name;
  88958. serializationObject.id = this.id;
  88959. if (this.dimensionsAtRest) {
  88960. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88961. }
  88962. serializationObject.bones = [];
  88963. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88964. for (var index = 0; index < this.bones.length; index++) {
  88965. var bone = this.bones[index];
  88966. var parent_2 = bone.getParent();
  88967. var serializedBone = {
  88968. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88969. name: bone.name,
  88970. matrix: bone.getBaseMatrix().toArray(),
  88971. rest: bone.getRestPose().toArray()
  88972. };
  88973. serializationObject.bones.push(serializedBone);
  88974. if (bone.length) {
  88975. serializedBone.length = bone.length;
  88976. }
  88977. if (bone.metadata) {
  88978. serializedBone.metadata = bone.metadata;
  88979. }
  88980. if (bone.animations && bone.animations.length > 0) {
  88981. serializedBone.animation = bone.animations[0].serialize();
  88982. }
  88983. serializationObject.ranges = [];
  88984. for (var name in this._ranges) {
  88985. var source = this._ranges[name];
  88986. if (!source) {
  88987. continue;
  88988. }
  88989. var range = {};
  88990. range.name = name;
  88991. range.from = source.from;
  88992. range.to = source.to;
  88993. serializationObject.ranges.push(range);
  88994. }
  88995. }
  88996. return serializationObject;
  88997. };
  88998. /**
  88999. * Creates a new skeleton from serialized data
  89000. * @param parsedSkeleton defines the serialized data
  89001. * @param scene defines the hosting scene
  89002. * @returns a new skeleton
  89003. */
  89004. Skeleton.Parse = function (parsedSkeleton, scene) {
  89005. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  89006. if (parsedSkeleton.dimensionsAtRest) {
  89007. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  89008. }
  89009. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  89010. var index;
  89011. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  89012. var parsedBone = parsedSkeleton.bones[index];
  89013. var parentBone = null;
  89014. if (parsedBone.parentBoneIndex > -1) {
  89015. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  89016. }
  89017. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  89018. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  89019. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  89020. bone.id = parsedBone.id;
  89021. }
  89022. if (parsedBone.length) {
  89023. bone.length = parsedBone.length;
  89024. }
  89025. if (parsedBone.metadata) {
  89026. bone.metadata = parsedBone.metadata;
  89027. }
  89028. if (parsedBone.animation) {
  89029. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  89030. }
  89031. }
  89032. // placed after bones, so createAnimationRange can cascade down
  89033. if (parsedSkeleton.ranges) {
  89034. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  89035. var data = parsedSkeleton.ranges[index];
  89036. skeleton.createAnimationRange(data.name, data.from, data.to);
  89037. }
  89038. }
  89039. return skeleton;
  89040. };
  89041. /**
  89042. * Compute all node absolute transforms
  89043. * @param forceUpdate defines if computation must be done even if cache is up to date
  89044. */
  89045. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  89046. if (forceUpdate === void 0) { forceUpdate = false; }
  89047. var renderId = this._scene.getRenderId();
  89048. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  89049. this.bones[0].computeAbsoluteTransforms();
  89050. this._lastAbsoluteTransformsUpdateId = renderId;
  89051. }
  89052. };
  89053. /**
  89054. * Gets the root pose matrix
  89055. * @returns a matrix
  89056. */
  89057. Skeleton.prototype.getPoseMatrix = function () {
  89058. var poseMatrix = null;
  89059. if (this._meshesWithPoseMatrix.length > 0) {
  89060. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  89061. }
  89062. return poseMatrix;
  89063. };
  89064. /**
  89065. * Sorts bones per internal index
  89066. */
  89067. Skeleton.prototype.sortBones = function () {
  89068. var bones = new Array();
  89069. var visited = new Array(this.bones.length);
  89070. for (var index = 0; index < this.bones.length; index++) {
  89071. this._sortBones(index, bones, visited);
  89072. }
  89073. this.bones = bones;
  89074. };
  89075. Skeleton.prototype._sortBones = function (index, bones, visited) {
  89076. if (visited[index]) {
  89077. return;
  89078. }
  89079. visited[index] = true;
  89080. var bone = this.bones[index];
  89081. if (bone._index === undefined) {
  89082. bone._index = index;
  89083. }
  89084. var parentBone = bone.getParent();
  89085. if (parentBone) {
  89086. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  89087. }
  89088. bones.push(bone);
  89089. };
  89090. return Skeleton;
  89091. }());
  89092. BABYLON.Skeleton = Skeleton;
  89093. })(BABYLON || (BABYLON = {}));
  89094. //# sourceMappingURL=babylon.skeleton.js.map
  89095. var BABYLON;
  89096. (function (BABYLON) {
  89097. ;
  89098. /**
  89099. * This groups tools to convert HDR texture to native colors array.
  89100. */
  89101. var HDRTools = /** @class */ (function () {
  89102. function HDRTools() {
  89103. }
  89104. HDRTools.Ldexp = function (mantissa, exponent) {
  89105. if (exponent > 1023) {
  89106. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  89107. }
  89108. if (exponent < -1074) {
  89109. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  89110. }
  89111. return mantissa * Math.pow(2, exponent);
  89112. };
  89113. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  89114. if (exponent > 0) { /*nonzero pixel*/
  89115. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  89116. float32array[index + 0] = red * exponent;
  89117. float32array[index + 1] = green * exponent;
  89118. float32array[index + 2] = blue * exponent;
  89119. }
  89120. else {
  89121. float32array[index + 0] = 0;
  89122. float32array[index + 1] = 0;
  89123. float32array[index + 2] = 0;
  89124. }
  89125. };
  89126. HDRTools.readStringLine = function (uint8array, startIndex) {
  89127. var line = "";
  89128. var character = "";
  89129. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  89130. character = String.fromCharCode(uint8array[i]);
  89131. if (character == "\n") {
  89132. break;
  89133. }
  89134. line += character;
  89135. }
  89136. return line;
  89137. };
  89138. /**
  89139. * Reads header information from an RGBE texture stored in a native array.
  89140. * More information on this format are available here:
  89141. * https://en.wikipedia.org/wiki/RGBE_image_format
  89142. *
  89143. * @param uint8array The binary file stored in native array.
  89144. * @return The header information.
  89145. */
  89146. HDRTools.RGBE_ReadHeader = function (uint8array) {
  89147. var height = 0;
  89148. var width = 0;
  89149. var line = this.readStringLine(uint8array, 0);
  89150. if (line[0] != '#' || line[1] != '?') {
  89151. throw "Bad HDR Format.";
  89152. }
  89153. var endOfHeader = false;
  89154. var findFormat = false;
  89155. var lineIndex = 0;
  89156. do {
  89157. lineIndex += (line.length + 1);
  89158. line = this.readStringLine(uint8array, lineIndex);
  89159. if (line == "FORMAT=32-bit_rle_rgbe") {
  89160. findFormat = true;
  89161. }
  89162. else if (line.length == 0) {
  89163. endOfHeader = true;
  89164. }
  89165. } while (!endOfHeader);
  89166. if (!findFormat) {
  89167. throw "HDR Bad header format, unsupported FORMAT";
  89168. }
  89169. lineIndex += (line.length + 1);
  89170. line = this.readStringLine(uint8array, lineIndex);
  89171. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  89172. var match = sizeRegexp.exec(line);
  89173. // TODO. Support +Y and -X if needed.
  89174. if (!match || match.length < 3) {
  89175. throw "HDR Bad header format, no size";
  89176. }
  89177. width = parseInt(match[2]);
  89178. height = parseInt(match[1]);
  89179. if (width < 8 || width > 0x7fff) {
  89180. throw "HDR Bad header format, unsupported size";
  89181. }
  89182. lineIndex += (line.length + 1);
  89183. return {
  89184. height: height,
  89185. width: width,
  89186. dataPosition: lineIndex
  89187. };
  89188. };
  89189. /**
  89190. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  89191. * This RGBE texture needs to store the information as a panorama.
  89192. *
  89193. * More information on this format are available here:
  89194. * https://en.wikipedia.org/wiki/RGBE_image_format
  89195. *
  89196. * @param buffer The binary file stored in an array buffer.
  89197. * @param size The expected size of the extracted cubemap.
  89198. * @return The Cube Map information.
  89199. */
  89200. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  89201. var uint8array = new Uint8Array(buffer);
  89202. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  89203. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89204. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  89205. return cubeMapData;
  89206. };
  89207. /**
  89208. * Returns the pixels data extracted from an RGBE texture.
  89209. * This pixels will be stored left to right up to down in the R G B order in one array.
  89210. *
  89211. * More information on this format are available here:
  89212. * https://en.wikipedia.org/wiki/RGBE_image_format
  89213. *
  89214. * @param uint8array The binary file stored in an array buffer.
  89215. * @param hdrInfo The header information of the file.
  89216. * @return The pixels data in RGB right to left up to down order.
  89217. */
  89218. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  89219. // Keep for multi format supports.
  89220. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89221. };
  89222. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  89223. var num_scanlines = hdrInfo.height;
  89224. var scanline_width = hdrInfo.width;
  89225. var a, b, c, d, count;
  89226. var dataIndex = hdrInfo.dataPosition;
  89227. var index = 0, endIndex = 0, i = 0;
  89228. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  89229. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  89230. // 3 channels of 4 bytes per pixel in float.
  89231. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  89232. var resultArray = new Float32Array(resultBuffer);
  89233. // read in each successive scanline
  89234. while (num_scanlines > 0) {
  89235. a = uint8array[dataIndex++];
  89236. b = uint8array[dataIndex++];
  89237. c = uint8array[dataIndex++];
  89238. d = uint8array[dataIndex++];
  89239. if (a != 2 || b != 2 || (c & 0x80)) {
  89240. // this file is not run length encoded
  89241. throw "HDR Bad header format, not RLE";
  89242. }
  89243. if (((c << 8) | d) != scanline_width) {
  89244. throw "HDR Bad header format, wrong scan line width";
  89245. }
  89246. index = 0;
  89247. // read each of the four channels for the scanline into the buffer
  89248. for (i = 0; i < 4; i++) {
  89249. endIndex = (i + 1) * scanline_width;
  89250. while (index < endIndex) {
  89251. a = uint8array[dataIndex++];
  89252. b = uint8array[dataIndex++];
  89253. if (a > 128) {
  89254. // a run of the same value
  89255. count = a - 128;
  89256. if ((count == 0) || (count > endIndex - index)) {
  89257. throw "HDR Bad Format, bad scanline data (run)";
  89258. }
  89259. while (count-- > 0) {
  89260. scanLineArray[index++] = b;
  89261. }
  89262. }
  89263. else {
  89264. // a non-run
  89265. count = a;
  89266. if ((count == 0) || (count > endIndex - index)) {
  89267. throw "HDR Bad Format, bad scanline data (non-run)";
  89268. }
  89269. scanLineArray[index++] = b;
  89270. if (--count > 0) {
  89271. for (var j = 0; j < count; j++) {
  89272. scanLineArray[index++] = uint8array[dataIndex++];
  89273. }
  89274. }
  89275. }
  89276. }
  89277. }
  89278. // now convert data from buffer into floats
  89279. for (i = 0; i < scanline_width; i++) {
  89280. a = scanLineArray[i];
  89281. b = scanLineArray[i + scanline_width];
  89282. c = scanLineArray[i + 2 * scanline_width];
  89283. d = scanLineArray[i + 3 * scanline_width];
  89284. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  89285. }
  89286. num_scanlines--;
  89287. }
  89288. return resultArray;
  89289. };
  89290. return HDRTools;
  89291. }());
  89292. BABYLON.HDRTools = HDRTools;
  89293. })(BABYLON || (BABYLON = {}));
  89294. //# sourceMappingURL=babylon.hdr.js.map
  89295. var BABYLON;
  89296. (function (BABYLON) {
  89297. /**
  89298. * This represents a texture coming from an HDR input.
  89299. *
  89300. * The only supported format is currently panorama picture stored in RGBE format.
  89301. * Example of such files can be found on HDRLib: http://hdrlib.com/
  89302. */
  89303. var HDRCubeTexture = /** @class */ (function (_super) {
  89304. __extends(HDRCubeTexture, _super);
  89305. /**
  89306. * Instantiates an HDRTexture from the following parameters.
  89307. *
  89308. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  89309. * @param scene The scene the texture will be used in
  89310. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  89311. * @param noMipmap Forces to not generate the mipmap if true
  89312. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  89313. * @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)
  89314. * @param reserved Reserved flag for internal use.
  89315. */
  89316. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  89317. if (noMipmap === void 0) { noMipmap = false; }
  89318. if (generateHarmonics === void 0) { generateHarmonics = true; }
  89319. if (gammaSpace === void 0) { gammaSpace = false; }
  89320. if (reserved === void 0) { reserved = false; }
  89321. if (onLoad === void 0) { onLoad = null; }
  89322. if (onError === void 0) { onError = null; }
  89323. var _this = _super.call(this, scene) || this;
  89324. _this._generateHarmonics = true;
  89325. _this._onLoad = null;
  89326. _this._onError = null;
  89327. /**
  89328. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  89329. */
  89330. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  89331. _this._isBlocking = true;
  89332. _this._rotationY = 0;
  89333. /**
  89334. * Gets or sets the center of the bounding box associated with the cube texture
  89335. * It must define where the camera used to render the texture was set
  89336. */
  89337. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  89338. if (!url) {
  89339. return _this;
  89340. }
  89341. _this.name = url;
  89342. _this.url = url;
  89343. _this.hasAlpha = false;
  89344. _this.isCube = true;
  89345. _this._textureMatrix = BABYLON.Matrix.Identity();
  89346. _this._onLoad = onLoad;
  89347. _this._onError = onError;
  89348. _this.gammaSpace = gammaSpace;
  89349. _this._noMipmap = noMipmap;
  89350. _this._size = size;
  89351. _this._texture = _this._getFromCache(url, _this._noMipmap);
  89352. if (!_this._texture) {
  89353. if (!scene.useDelayedTextureLoading) {
  89354. _this.loadTexture();
  89355. }
  89356. else {
  89357. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89358. }
  89359. }
  89360. return _this;
  89361. }
  89362. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  89363. /**
  89364. * Gets wether or not the texture is blocking during loading.
  89365. */
  89366. get: function () {
  89367. return this._isBlocking;
  89368. },
  89369. /**
  89370. * Sets wether or not the texture is blocking during loading.
  89371. */
  89372. set: function (value) {
  89373. this._isBlocking = value;
  89374. },
  89375. enumerable: true,
  89376. configurable: true
  89377. });
  89378. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  89379. /**
  89380. * Gets texture matrix rotation angle around Y axis radians.
  89381. */
  89382. get: function () {
  89383. return this._rotationY;
  89384. },
  89385. /**
  89386. * Sets texture matrix rotation angle around Y axis in radians.
  89387. */
  89388. set: function (value) {
  89389. this._rotationY = value;
  89390. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  89391. },
  89392. enumerable: true,
  89393. configurable: true
  89394. });
  89395. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  89396. get: function () {
  89397. return this._boundingBoxSize;
  89398. },
  89399. /**
  89400. * Gets or sets the size of the bounding box associated with the cube texture
  89401. * When defined, the cubemap will switch to local mode
  89402. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  89403. * @example https://www.babylonjs-playground.com/#RNASML
  89404. */
  89405. set: function (value) {
  89406. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  89407. return;
  89408. }
  89409. this._boundingBoxSize = value;
  89410. var scene = this.getScene();
  89411. if (scene) {
  89412. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  89413. }
  89414. },
  89415. enumerable: true,
  89416. configurable: true
  89417. });
  89418. /**
  89419. * Occurs when the file is raw .hdr file.
  89420. */
  89421. HDRCubeTexture.prototype.loadTexture = function () {
  89422. var _this = this;
  89423. var callback = function (buffer) {
  89424. _this.lodGenerationOffset = 0.0;
  89425. _this.lodGenerationScale = 0.8;
  89426. var scene = _this.getScene();
  89427. if (!scene) {
  89428. return null;
  89429. }
  89430. // Extract the raw linear data.
  89431. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  89432. // Generate harmonics if needed.
  89433. if (_this._generateHarmonics) {
  89434. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  89435. _this.sphericalPolynomial = sphericalPolynomial;
  89436. }
  89437. var results = [];
  89438. var byteArray = null;
  89439. // Push each faces.
  89440. for (var j = 0; j < 6; j++) {
  89441. // Create uintarray fallback.
  89442. if (!scene.getEngine().getCaps().textureFloat) {
  89443. // 3 channels of 1 bytes per pixel in bytes.
  89444. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  89445. byteArray = new Uint8Array(byteBuffer);
  89446. }
  89447. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  89448. // If special cases.
  89449. if (_this.gammaSpace || byteArray) {
  89450. for (var i = 0; i < _this._size * _this._size; i++) {
  89451. // Put in gamma space if requested.
  89452. if (_this.gammaSpace) {
  89453. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  89454. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  89455. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  89456. }
  89457. // Convert to int texture for fallback.
  89458. if (byteArray) {
  89459. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  89460. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  89461. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  89462. // May use luminance instead if the result is not accurate.
  89463. var max = Math.max(Math.max(r, g), b);
  89464. if (max > 255) {
  89465. var scale = 255 / max;
  89466. r *= scale;
  89467. g *= scale;
  89468. b *= scale;
  89469. }
  89470. byteArray[(i * 3) + 0] = r;
  89471. byteArray[(i * 3) + 1] = g;
  89472. byteArray[(i * 3) + 2] = b;
  89473. }
  89474. }
  89475. }
  89476. if (byteArray) {
  89477. results.push(byteArray);
  89478. }
  89479. else {
  89480. results.push(dataFace);
  89481. }
  89482. }
  89483. return results;
  89484. };
  89485. var scene = this.getScene();
  89486. if (scene) {
  89487. 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);
  89488. }
  89489. };
  89490. HDRCubeTexture.prototype.clone = function () {
  89491. var scene = this.getScene();
  89492. if (!scene) {
  89493. return this;
  89494. }
  89495. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  89496. // Base texture
  89497. newTexture.level = this.level;
  89498. newTexture.wrapU = this.wrapU;
  89499. newTexture.wrapV = this.wrapV;
  89500. newTexture.coordinatesIndex = this.coordinatesIndex;
  89501. newTexture.coordinatesMode = this.coordinatesMode;
  89502. return newTexture;
  89503. };
  89504. // Methods
  89505. HDRCubeTexture.prototype.delayLoad = function () {
  89506. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89507. return;
  89508. }
  89509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89510. this._texture = this._getFromCache(this.url, this._noMipmap);
  89511. if (!this._texture) {
  89512. this.loadTexture();
  89513. }
  89514. };
  89515. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  89516. return this._textureMatrix;
  89517. };
  89518. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  89519. this._textureMatrix = value;
  89520. };
  89521. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89522. var texture = null;
  89523. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89524. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  89525. texture.name = parsedTexture.name;
  89526. texture.hasAlpha = parsedTexture.hasAlpha;
  89527. texture.level = parsedTexture.level;
  89528. texture.coordinatesMode = parsedTexture.coordinatesMode;
  89529. texture.isBlocking = parsedTexture.isBlocking;
  89530. }
  89531. if (texture) {
  89532. if (parsedTexture.boundingBoxPosition) {
  89533. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  89534. }
  89535. if (parsedTexture.boundingBoxSize) {
  89536. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89537. }
  89538. if (parsedTexture.rotationY) {
  89539. texture.rotationY = parsedTexture.rotationY;
  89540. }
  89541. }
  89542. return texture;
  89543. };
  89544. HDRCubeTexture.prototype.serialize = function () {
  89545. if (!this.name) {
  89546. return null;
  89547. }
  89548. var serializationObject = {};
  89549. serializationObject.name = this.name;
  89550. serializationObject.hasAlpha = this.hasAlpha;
  89551. serializationObject.isCube = true;
  89552. serializationObject.level = this.level;
  89553. serializationObject.size = this._size;
  89554. serializationObject.coordinatesMode = this.coordinatesMode;
  89555. serializationObject.useInGammaSpace = this.gammaSpace;
  89556. serializationObject.generateHarmonics = this._generateHarmonics;
  89557. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89558. serializationObject.noMipmap = this._noMipmap;
  89559. serializationObject.isBlocking = this._isBlocking;
  89560. serializationObject.rotationY = this._rotationY;
  89561. return serializationObject;
  89562. };
  89563. HDRCubeTexture._facesMapping = [
  89564. "right",
  89565. "left",
  89566. "up",
  89567. "down",
  89568. "front",
  89569. "back"
  89570. ];
  89571. return HDRCubeTexture;
  89572. }(BABYLON.BaseTexture));
  89573. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89574. })(BABYLON || (BABYLON = {}));
  89575. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89576. var BABYLON;
  89577. (function (BABYLON) {
  89578. /**
  89579. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89580. */
  89581. var PanoramaToCubeMapTools = /** @class */ (function () {
  89582. function PanoramaToCubeMapTools() {
  89583. }
  89584. /**
  89585. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89586. *
  89587. * @param float32Array The source data.
  89588. * @param inputWidth The width of the input panorama.
  89589. * @param inputhHeight The height of the input panorama.
  89590. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89591. * @return The cubemap data
  89592. */
  89593. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89594. if (!float32Array) {
  89595. throw "ConvertPanoramaToCubemap: input cannot be null";
  89596. }
  89597. if (float32Array.length != inputWidth * inputHeight * 3) {
  89598. throw "ConvertPanoramaToCubemap: input size is wrong";
  89599. }
  89600. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89601. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89602. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89603. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89604. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89605. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89606. return {
  89607. front: textureFront,
  89608. back: textureBack,
  89609. left: textureLeft,
  89610. right: textureRight,
  89611. up: textureUp,
  89612. down: textureDown,
  89613. size: size,
  89614. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89615. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89616. gammaSpace: false,
  89617. };
  89618. };
  89619. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89620. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89621. var textureArray = new Float32Array(buffer);
  89622. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89623. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89624. var dy = 1 / texSize;
  89625. var fy = 0;
  89626. for (var y = 0; y < texSize; y++) {
  89627. var xv1 = faceData[0];
  89628. var xv2 = faceData[2];
  89629. for (var x = 0; x < texSize; x++) {
  89630. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89631. v.normalize();
  89632. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89633. // 3 channels per pixels
  89634. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89635. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89636. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89637. xv1 = xv1.add(rotDX1);
  89638. xv2 = xv2.add(rotDX2);
  89639. }
  89640. fy += dy;
  89641. }
  89642. return textureArray;
  89643. };
  89644. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  89645. var theta = Math.atan2(vDir.z, vDir.x);
  89646. var phi = Math.acos(vDir.y);
  89647. while (theta < -Math.PI)
  89648. theta += 2 * Math.PI;
  89649. while (theta > Math.PI)
  89650. theta -= 2 * Math.PI;
  89651. var dx = theta / Math.PI;
  89652. var dy = phi / Math.PI;
  89653. // recenter.
  89654. dx = dx * 0.5 + 0.5;
  89655. var px = Math.round(dx * inputWidth);
  89656. if (px < 0)
  89657. px = 0;
  89658. else if (px >= inputWidth)
  89659. px = inputWidth - 1;
  89660. var py = Math.round(dy * inputHeight);
  89661. if (py < 0)
  89662. py = 0;
  89663. else if (py >= inputHeight)
  89664. py = inputHeight - 1;
  89665. var inputY = (inputHeight - py - 1);
  89666. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  89667. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  89668. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  89669. return {
  89670. r: r,
  89671. g: g,
  89672. b: b
  89673. };
  89674. };
  89675. PanoramaToCubeMapTools.FACE_FRONT = [
  89676. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89677. new BABYLON.Vector3(1.0, -1.0, -1.0),
  89678. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  89679. new BABYLON.Vector3(1.0, 1.0, -1.0)
  89680. ];
  89681. PanoramaToCubeMapTools.FACE_BACK = [
  89682. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89683. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89684. new BABYLON.Vector3(1.0, 1.0, 1.0),
  89685. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  89686. ];
  89687. PanoramaToCubeMapTools.FACE_RIGHT = [
  89688. new BABYLON.Vector3(1.0, -1.0, -1.0),
  89689. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89690. new BABYLON.Vector3(1.0, 1.0, -1.0),
  89691. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89692. ];
  89693. PanoramaToCubeMapTools.FACE_LEFT = [
  89694. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89695. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89696. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  89697. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  89698. ];
  89699. PanoramaToCubeMapTools.FACE_DOWN = [
  89700. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  89701. new BABYLON.Vector3(1.0, 1.0, -1.0),
  89702. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  89703. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89704. ];
  89705. PanoramaToCubeMapTools.FACE_UP = [
  89706. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  89707. new BABYLON.Vector3(1.0, -1.0, 1.0),
  89708. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  89709. new BABYLON.Vector3(1.0, -1.0, -1.0)
  89710. ];
  89711. return PanoramaToCubeMapTools;
  89712. }());
  89713. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  89714. })(BABYLON || (BABYLON = {}));
  89715. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  89716. var BABYLON;
  89717. (function (BABYLON) {
  89718. var IndexedVector2 = /** @class */ (function (_super) {
  89719. __extends(IndexedVector2, _super);
  89720. function IndexedVector2(original, index) {
  89721. var _this = _super.call(this, original.x, original.y) || this;
  89722. _this.index = index;
  89723. return _this;
  89724. }
  89725. return IndexedVector2;
  89726. }(BABYLON.Vector2));
  89727. var PolygonPoints = /** @class */ (function () {
  89728. function PolygonPoints() {
  89729. this.elements = new Array();
  89730. }
  89731. PolygonPoints.prototype.add = function (originalPoints) {
  89732. var _this = this;
  89733. var result = new Array();
  89734. originalPoints.forEach(function (point) {
  89735. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  89736. var newPoint = new IndexedVector2(point, _this.elements.length);
  89737. result.push(newPoint);
  89738. _this.elements.push(newPoint);
  89739. }
  89740. });
  89741. return result;
  89742. };
  89743. PolygonPoints.prototype.computeBounds = function () {
  89744. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89745. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89746. this.elements.forEach(function (point) {
  89747. // x
  89748. if (point.x < lmin.x) {
  89749. lmin.x = point.x;
  89750. }
  89751. else if (point.x > lmax.x) {
  89752. lmax.x = point.x;
  89753. }
  89754. // y
  89755. if (point.y < lmin.y) {
  89756. lmin.y = point.y;
  89757. }
  89758. else if (point.y > lmax.y) {
  89759. lmax.y = point.y;
  89760. }
  89761. });
  89762. return {
  89763. min: lmin,
  89764. max: lmax,
  89765. width: lmax.x - lmin.x,
  89766. height: lmax.y - lmin.y
  89767. };
  89768. };
  89769. return PolygonPoints;
  89770. }());
  89771. var Polygon = /** @class */ (function () {
  89772. function Polygon() {
  89773. }
  89774. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  89775. return [
  89776. new BABYLON.Vector2(xmin, ymin),
  89777. new BABYLON.Vector2(xmax, ymin),
  89778. new BABYLON.Vector2(xmax, ymax),
  89779. new BABYLON.Vector2(xmin, ymax)
  89780. ];
  89781. };
  89782. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  89783. if (cx === void 0) { cx = 0; }
  89784. if (cy === void 0) { cy = 0; }
  89785. if (numberOfSides === void 0) { numberOfSides = 32; }
  89786. var result = new Array();
  89787. var angle = 0;
  89788. var increment = (Math.PI * 2) / numberOfSides;
  89789. for (var i = 0; i < numberOfSides; i++) {
  89790. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  89791. angle -= increment;
  89792. }
  89793. return result;
  89794. };
  89795. Polygon.Parse = function (input) {
  89796. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  89797. var i, result = [];
  89798. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  89799. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  89800. }
  89801. return result;
  89802. };
  89803. Polygon.StartingAt = function (x, y) {
  89804. return BABYLON.Path2.StartingAt(x, y);
  89805. };
  89806. return Polygon;
  89807. }());
  89808. BABYLON.Polygon = Polygon;
  89809. var PolygonMeshBuilder = /** @class */ (function () {
  89810. function PolygonMeshBuilder(name, contours, scene) {
  89811. this._points = new PolygonPoints();
  89812. this._outlinepoints = new PolygonPoints();
  89813. this._holes = new Array();
  89814. this._epoints = new Array();
  89815. this._eholes = new Array();
  89816. this._name = name;
  89817. this._scene = scene;
  89818. var points;
  89819. if (contours instanceof BABYLON.Path2) {
  89820. points = contours.getPoints();
  89821. }
  89822. else {
  89823. points = contours;
  89824. }
  89825. this._addToepoint(points);
  89826. this._points.add(points);
  89827. this._outlinepoints.add(points);
  89828. if (typeof earcut === 'undefined') {
  89829. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  89830. }
  89831. }
  89832. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  89833. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  89834. var p = points_1[_i];
  89835. this._epoints.push(p.x, p.y);
  89836. }
  89837. };
  89838. PolygonMeshBuilder.prototype.addHole = function (hole) {
  89839. this._points.add(hole);
  89840. var holepoints = new PolygonPoints();
  89841. holepoints.add(hole);
  89842. this._holes.push(holepoints);
  89843. this._eholes.push(this._epoints.length / 2);
  89844. this._addToepoint(hole);
  89845. return this;
  89846. };
  89847. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  89848. var _this = this;
  89849. if (updatable === void 0) { updatable = false; }
  89850. if (depth === void 0) { depth = 0; }
  89851. var result = new BABYLON.Mesh(this._name, this._scene);
  89852. var normals = new Array();
  89853. var positions = new Array();
  89854. var uvs = new Array();
  89855. var bounds = this._points.computeBounds();
  89856. this._points.elements.forEach(function (p) {
  89857. normals.push(0, 1.0, 0);
  89858. positions.push(p.x, 0, p.y);
  89859. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  89860. });
  89861. var indices = new Array();
  89862. var res = earcut(this._epoints, this._eholes, 2);
  89863. for (var i = 0; i < res.length; i++) {
  89864. indices.push(res[i]);
  89865. }
  89866. if (depth > 0) {
  89867. var positionscount = (positions.length / 3); //get the current pointcount
  89868. this._points.elements.forEach(function (p) {
  89869. normals.push(0, -1.0, 0);
  89870. positions.push(p.x, -depth, p.y);
  89871. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  89872. });
  89873. var totalCount = indices.length;
  89874. for (var i = 0; i < totalCount; i += 3) {
  89875. var i0 = indices[i + 0];
  89876. var i1 = indices[i + 1];
  89877. var i2 = indices[i + 2];
  89878. indices.push(i2 + positionscount);
  89879. indices.push(i1 + positionscount);
  89880. indices.push(i0 + positionscount);
  89881. }
  89882. //Add the sides
  89883. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  89884. this._holes.forEach(function (hole) {
  89885. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  89886. });
  89887. }
  89888. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  89889. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  89890. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  89891. result.setIndices(indices);
  89892. return result;
  89893. };
  89894. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  89895. var StartIndex = positions.length / 3;
  89896. var ulength = 0;
  89897. for (var i = 0; i < points.elements.length; i++) {
  89898. var p = points.elements[i];
  89899. var p1;
  89900. if ((i + 1) > points.elements.length - 1) {
  89901. p1 = points.elements[0];
  89902. }
  89903. else {
  89904. p1 = points.elements[i + 1];
  89905. }
  89906. positions.push(p.x, 0, p.y);
  89907. positions.push(p.x, -depth, p.y);
  89908. positions.push(p1.x, 0, p1.y);
  89909. positions.push(p1.x, -depth, p1.y);
  89910. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89911. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89912. var v3 = v2.subtract(v1);
  89913. var v4 = new BABYLON.Vector3(0, 1, 0);
  89914. var vn = BABYLON.Vector3.Cross(v3, v4);
  89915. vn = vn.normalize();
  89916. uvs.push(ulength / bounds.width, 0);
  89917. uvs.push(ulength / bounds.width, 1);
  89918. ulength += v3.length();
  89919. uvs.push((ulength / bounds.width), 0);
  89920. uvs.push((ulength / bounds.width), 1);
  89921. if (!flip) {
  89922. normals.push(-vn.x, -vn.y, -vn.z);
  89923. normals.push(-vn.x, -vn.y, -vn.z);
  89924. normals.push(-vn.x, -vn.y, -vn.z);
  89925. normals.push(-vn.x, -vn.y, -vn.z);
  89926. indices.push(StartIndex);
  89927. indices.push(StartIndex + 1);
  89928. indices.push(StartIndex + 2);
  89929. indices.push(StartIndex + 1);
  89930. indices.push(StartIndex + 3);
  89931. indices.push(StartIndex + 2);
  89932. }
  89933. else {
  89934. normals.push(vn.x, vn.y, vn.z);
  89935. normals.push(vn.x, vn.y, vn.z);
  89936. normals.push(vn.x, vn.y, vn.z);
  89937. normals.push(vn.x, vn.y, vn.z);
  89938. indices.push(StartIndex);
  89939. indices.push(StartIndex + 2);
  89940. indices.push(StartIndex + 1);
  89941. indices.push(StartIndex + 1);
  89942. indices.push(StartIndex + 2);
  89943. indices.push(StartIndex + 3);
  89944. }
  89945. StartIndex += 4;
  89946. }
  89947. ;
  89948. };
  89949. return PolygonMeshBuilder;
  89950. }());
  89951. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89952. })(BABYLON || (BABYLON = {}));
  89953. //# sourceMappingURL=babylon.polygonMesh.js.map
  89954. var BABYLON;
  89955. (function (BABYLON) {
  89956. // Unique ID when we import meshes from Babylon to CSG
  89957. var currentCSGMeshId = 0;
  89958. // # class Vertex
  89959. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89960. // one to provide additional features like texture coordinates and vertex
  89961. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89962. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89963. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89964. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89965. // is not used anywhere else.
  89966. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89967. var Vertex = /** @class */ (function () {
  89968. function Vertex(pos, normal, uv) {
  89969. this.pos = pos;
  89970. this.normal = normal;
  89971. this.uv = uv;
  89972. }
  89973. Vertex.prototype.clone = function () {
  89974. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89975. };
  89976. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89977. // orientation of a polygon is flipped.
  89978. Vertex.prototype.flip = function () {
  89979. this.normal = this.normal.scale(-1);
  89980. };
  89981. // Create a new vertex between this vertex and `other` by linearly
  89982. // interpolating all properties using a parameter of `t`. Subclasses should
  89983. // override this to interpolate additional properties.
  89984. Vertex.prototype.interpolate = function (other, t) {
  89985. 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));
  89986. };
  89987. return Vertex;
  89988. }());
  89989. // # class Plane
  89990. // Represents a plane in 3D space.
  89991. var Plane = /** @class */ (function () {
  89992. function Plane(normal, w) {
  89993. this.normal = normal;
  89994. this.w = w;
  89995. }
  89996. Plane.FromPoints = function (a, b, c) {
  89997. var v0 = c.subtract(a);
  89998. var v1 = b.subtract(a);
  89999. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  90000. return null;
  90001. }
  90002. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  90003. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  90004. };
  90005. Plane.prototype.clone = function () {
  90006. return new Plane(this.normal.clone(), this.w);
  90007. };
  90008. Plane.prototype.flip = function () {
  90009. this.normal.scaleInPlace(-1);
  90010. this.w = -this.w;
  90011. };
  90012. // Split `polygon` by this plane if needed, then put the polygon or polygon
  90013. // fragments in the appropriate lists. Coplanar polygons go into either
  90014. // `coplanarFront` or `coplanarBack` depending on their orientation with
  90015. // respect to this plane. Polygons in front or in back of this plane go into
  90016. // either `front` or `back`.
  90017. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  90018. var COPLANAR = 0;
  90019. var FRONT = 1;
  90020. var BACK = 2;
  90021. var SPANNING = 3;
  90022. // Classify each point as well as the entire polygon into one of the above
  90023. // four classes.
  90024. var polygonType = 0;
  90025. var types = [];
  90026. var i;
  90027. var t;
  90028. for (i = 0; i < polygon.vertices.length; i++) {
  90029. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  90030. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  90031. polygonType |= type;
  90032. types.push(type);
  90033. }
  90034. // Put the polygon in the correct list, splitting it when necessary.
  90035. switch (polygonType) {
  90036. case COPLANAR:
  90037. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  90038. break;
  90039. case FRONT:
  90040. front.push(polygon);
  90041. break;
  90042. case BACK:
  90043. back.push(polygon);
  90044. break;
  90045. case SPANNING:
  90046. var f = [], b = [];
  90047. for (i = 0; i < polygon.vertices.length; i++) {
  90048. var j = (i + 1) % polygon.vertices.length;
  90049. var ti = types[i], tj = types[j];
  90050. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  90051. if (ti !== BACK)
  90052. f.push(vi);
  90053. if (ti !== FRONT)
  90054. b.push(ti !== BACK ? vi.clone() : vi);
  90055. if ((ti | tj) === SPANNING) {
  90056. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  90057. var v = vi.interpolate(vj, t);
  90058. f.push(v);
  90059. b.push(v.clone());
  90060. }
  90061. }
  90062. var poly;
  90063. if (f.length >= 3) {
  90064. poly = new Polygon(f, polygon.shared);
  90065. if (poly.plane)
  90066. front.push(poly);
  90067. }
  90068. if (b.length >= 3) {
  90069. poly = new Polygon(b, polygon.shared);
  90070. if (poly.plane)
  90071. back.push(poly);
  90072. }
  90073. break;
  90074. }
  90075. };
  90076. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  90077. // point is on the plane.
  90078. Plane.EPSILON = 1e-5;
  90079. return Plane;
  90080. }());
  90081. // # class Polygon
  90082. // Represents a convex polygon. The vertices used to initialize a polygon must
  90083. // be coplanar and form a convex loop.
  90084. //
  90085. // Each convex polygon has a `shared` property, which is shared between all
  90086. // polygons that are clones of each other or were split from the same polygon.
  90087. // This can be used to define per-polygon properties (such as surface color).
  90088. var Polygon = /** @class */ (function () {
  90089. function Polygon(vertices, shared) {
  90090. this.vertices = vertices;
  90091. this.shared = shared;
  90092. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  90093. }
  90094. Polygon.prototype.clone = function () {
  90095. var vertices = this.vertices.map(function (v) { return v.clone(); });
  90096. return new Polygon(vertices, this.shared);
  90097. };
  90098. Polygon.prototype.flip = function () {
  90099. this.vertices.reverse().map(function (v) { v.flip(); });
  90100. this.plane.flip();
  90101. };
  90102. return Polygon;
  90103. }());
  90104. // # class Node
  90105. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  90106. // by picking a polygon to split along. That polygon (and all other coplanar
  90107. // polygons) are added directly to that node and the other polygons are added to
  90108. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  90109. // no distinction between internal and leaf nodes.
  90110. var Node = /** @class */ (function () {
  90111. function Node(polygons) {
  90112. this.plane = null;
  90113. this.front = null;
  90114. this.back = null;
  90115. this.polygons = new Array();
  90116. if (polygons) {
  90117. this.build(polygons);
  90118. }
  90119. }
  90120. Node.prototype.clone = function () {
  90121. var node = new Node();
  90122. node.plane = this.plane && this.plane.clone();
  90123. node.front = this.front && this.front.clone();
  90124. node.back = this.back && this.back.clone();
  90125. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  90126. return node;
  90127. };
  90128. // Convert solid space to empty space and empty space to solid space.
  90129. Node.prototype.invert = function () {
  90130. for (var i = 0; i < this.polygons.length; i++) {
  90131. this.polygons[i].flip();
  90132. }
  90133. if (this.plane) {
  90134. this.plane.flip();
  90135. }
  90136. if (this.front) {
  90137. this.front.invert();
  90138. }
  90139. if (this.back) {
  90140. this.back.invert();
  90141. }
  90142. var temp = this.front;
  90143. this.front = this.back;
  90144. this.back = temp;
  90145. };
  90146. // Recursively remove all polygons in `polygons` that are inside this BSP
  90147. // tree.
  90148. Node.prototype.clipPolygons = function (polygons) {
  90149. if (!this.plane)
  90150. return polygons.slice();
  90151. var front = new Array(), back = new Array();
  90152. for (var i = 0; i < polygons.length; i++) {
  90153. this.plane.splitPolygon(polygons[i], front, back, front, back);
  90154. }
  90155. if (this.front) {
  90156. front = this.front.clipPolygons(front);
  90157. }
  90158. if (this.back) {
  90159. back = this.back.clipPolygons(back);
  90160. }
  90161. else {
  90162. back = [];
  90163. }
  90164. return front.concat(back);
  90165. };
  90166. // Remove all polygons in this BSP tree that are inside the other BSP tree
  90167. // `bsp`.
  90168. Node.prototype.clipTo = function (bsp) {
  90169. this.polygons = bsp.clipPolygons(this.polygons);
  90170. if (this.front)
  90171. this.front.clipTo(bsp);
  90172. if (this.back)
  90173. this.back.clipTo(bsp);
  90174. };
  90175. // Return a list of all polygons in this BSP tree.
  90176. Node.prototype.allPolygons = function () {
  90177. var polygons = this.polygons.slice();
  90178. if (this.front)
  90179. polygons = polygons.concat(this.front.allPolygons());
  90180. if (this.back)
  90181. polygons = polygons.concat(this.back.allPolygons());
  90182. return polygons;
  90183. };
  90184. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  90185. // new polygons are filtered down to the bottom of the tree and become new
  90186. // nodes there. Each set of polygons is partitioned using the first polygon
  90187. // (no heuristic is used to pick a good split).
  90188. Node.prototype.build = function (polygons) {
  90189. if (!polygons.length)
  90190. return;
  90191. if (!this.plane)
  90192. this.plane = polygons[0].plane.clone();
  90193. var front = new Array(), back = new Array();
  90194. for (var i = 0; i < polygons.length; i++) {
  90195. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  90196. }
  90197. if (front.length) {
  90198. if (!this.front)
  90199. this.front = new Node();
  90200. this.front.build(front);
  90201. }
  90202. if (back.length) {
  90203. if (!this.back)
  90204. this.back = new Node();
  90205. this.back.build(back);
  90206. }
  90207. };
  90208. return Node;
  90209. }());
  90210. var CSG = /** @class */ (function () {
  90211. function CSG() {
  90212. this.polygons = new Array();
  90213. }
  90214. // Convert BABYLON.Mesh to BABYLON.CSG
  90215. CSG.FromMesh = function (mesh) {
  90216. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  90217. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  90218. if (mesh instanceof BABYLON.Mesh) {
  90219. mesh.computeWorldMatrix(true);
  90220. matrix = mesh.getWorldMatrix();
  90221. meshPosition = mesh.position.clone();
  90222. meshRotation = mesh.rotation.clone();
  90223. if (mesh.rotationQuaternion) {
  90224. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  90225. }
  90226. meshScaling = mesh.scaling.clone();
  90227. }
  90228. else {
  90229. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  90230. }
  90231. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90232. var subMeshes = mesh.subMeshes;
  90233. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  90234. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  90235. vertices = [];
  90236. for (var j = 0; j < 3; j++) {
  90237. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  90238. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  90239. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  90240. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  90241. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  90242. vertex = new Vertex(position, normal, uv);
  90243. vertices.push(vertex);
  90244. }
  90245. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  90246. // To handle the case of degenerated triangle
  90247. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  90248. if (polygon.plane)
  90249. polygons.push(polygon);
  90250. }
  90251. }
  90252. var csg = CSG.FromPolygons(polygons);
  90253. csg.matrix = matrix;
  90254. csg.position = meshPosition;
  90255. csg.rotation = meshRotation;
  90256. csg.scaling = meshScaling;
  90257. csg.rotationQuaternion = meshRotationQuaternion;
  90258. currentCSGMeshId++;
  90259. return csg;
  90260. };
  90261. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  90262. CSG.FromPolygons = function (polygons) {
  90263. var csg = new CSG();
  90264. csg.polygons = polygons;
  90265. return csg;
  90266. };
  90267. CSG.prototype.clone = function () {
  90268. var csg = new CSG();
  90269. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  90270. csg.copyTransformAttributes(this);
  90271. return csg;
  90272. };
  90273. CSG.prototype.union = function (csg) {
  90274. var a = new Node(this.clone().polygons);
  90275. var b = new Node(csg.clone().polygons);
  90276. a.clipTo(b);
  90277. b.clipTo(a);
  90278. b.invert();
  90279. b.clipTo(a);
  90280. b.invert();
  90281. a.build(b.allPolygons());
  90282. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90283. };
  90284. CSG.prototype.unionInPlace = function (csg) {
  90285. var a = new Node(this.polygons);
  90286. var b = new Node(csg.polygons);
  90287. a.clipTo(b);
  90288. b.clipTo(a);
  90289. b.invert();
  90290. b.clipTo(a);
  90291. b.invert();
  90292. a.build(b.allPolygons());
  90293. this.polygons = a.allPolygons();
  90294. };
  90295. CSG.prototype.subtract = function (csg) {
  90296. var a = new Node(this.clone().polygons);
  90297. var b = new Node(csg.clone().polygons);
  90298. a.invert();
  90299. a.clipTo(b);
  90300. b.clipTo(a);
  90301. b.invert();
  90302. b.clipTo(a);
  90303. b.invert();
  90304. a.build(b.allPolygons());
  90305. a.invert();
  90306. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90307. };
  90308. CSG.prototype.subtractInPlace = function (csg) {
  90309. var a = new Node(this.polygons);
  90310. var b = new Node(csg.polygons);
  90311. a.invert();
  90312. a.clipTo(b);
  90313. b.clipTo(a);
  90314. b.invert();
  90315. b.clipTo(a);
  90316. b.invert();
  90317. a.build(b.allPolygons());
  90318. a.invert();
  90319. this.polygons = a.allPolygons();
  90320. };
  90321. CSG.prototype.intersect = function (csg) {
  90322. var a = new Node(this.clone().polygons);
  90323. var b = new Node(csg.clone().polygons);
  90324. a.invert();
  90325. b.clipTo(a);
  90326. b.invert();
  90327. a.clipTo(b);
  90328. b.clipTo(a);
  90329. a.build(b.allPolygons());
  90330. a.invert();
  90331. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90332. };
  90333. CSG.prototype.intersectInPlace = function (csg) {
  90334. var a = new Node(this.polygons);
  90335. var b = new Node(csg.polygons);
  90336. a.invert();
  90337. b.clipTo(a);
  90338. b.invert();
  90339. a.clipTo(b);
  90340. b.clipTo(a);
  90341. a.build(b.allPolygons());
  90342. a.invert();
  90343. this.polygons = a.allPolygons();
  90344. };
  90345. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  90346. // not modified.
  90347. CSG.prototype.inverse = function () {
  90348. var csg = this.clone();
  90349. csg.inverseInPlace();
  90350. return csg;
  90351. };
  90352. CSG.prototype.inverseInPlace = function () {
  90353. this.polygons.map(function (p) { p.flip(); });
  90354. };
  90355. // This is used to keep meshes transformations so they can be restored
  90356. // when we build back a Babylon Mesh
  90357. // NB : All CSG operations are performed in world coordinates
  90358. CSG.prototype.copyTransformAttributes = function (csg) {
  90359. this.matrix = csg.matrix;
  90360. this.position = csg.position;
  90361. this.rotation = csg.rotation;
  90362. this.scaling = csg.scaling;
  90363. this.rotationQuaternion = csg.rotationQuaternion;
  90364. return this;
  90365. };
  90366. // Build Raw mesh from CSG
  90367. // Coordinates here are in world space
  90368. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  90369. var matrix = this.matrix.clone();
  90370. matrix.invert();
  90371. 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;
  90372. if (keepSubMeshes) {
  90373. // Sort Polygons, since subMeshes are indices range
  90374. polygons.sort(function (a, b) {
  90375. if (a.shared.meshId === b.shared.meshId) {
  90376. return a.shared.subMeshId - b.shared.subMeshId;
  90377. }
  90378. else {
  90379. return a.shared.meshId - b.shared.meshId;
  90380. }
  90381. });
  90382. }
  90383. for (var i = 0, il = polygons.length; i < il; i++) {
  90384. polygon = polygons[i];
  90385. // Building SubMeshes
  90386. if (!subMesh_dict[polygon.shared.meshId]) {
  90387. subMesh_dict[polygon.shared.meshId] = {};
  90388. }
  90389. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  90390. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  90391. indexStart: +Infinity,
  90392. indexEnd: -Infinity,
  90393. materialIndex: polygon.shared.materialIndex
  90394. };
  90395. }
  90396. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  90397. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  90398. polygonIndices[0] = 0;
  90399. polygonIndices[1] = j - 1;
  90400. polygonIndices[2] = j;
  90401. for (var k = 0; k < 3; k++) {
  90402. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  90403. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  90404. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  90405. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  90406. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  90407. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  90408. // Check if 2 points can be merged
  90409. if (!(typeof vertex_idx !== 'undefined' &&
  90410. normals[vertex_idx * 3] === localNormal.x &&
  90411. normals[vertex_idx * 3 + 1] === localNormal.y &&
  90412. normals[vertex_idx * 3 + 2] === localNormal.z &&
  90413. uvs[vertex_idx * 2] === uv.x &&
  90414. uvs[vertex_idx * 2 + 1] === uv.y)) {
  90415. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  90416. uvs.push(uv.x, uv.y);
  90417. normals.push(normal.x, normal.y, normal.z);
  90418. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  90419. }
  90420. indices.push(vertex_idx);
  90421. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  90422. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  90423. currentIndex++;
  90424. }
  90425. }
  90426. }
  90427. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  90428. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  90429. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  90430. mesh.setIndices(indices, null);
  90431. if (keepSubMeshes) {
  90432. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  90433. var materialIndexOffset = 0, materialMaxIndex;
  90434. mesh.subMeshes = new Array();
  90435. for (var m in subMesh_dict) {
  90436. materialMaxIndex = -1;
  90437. for (var sm in subMesh_dict[m]) {
  90438. subMesh_obj = subMesh_dict[m][sm];
  90439. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  90440. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  90441. }
  90442. materialIndexOffset += ++materialMaxIndex;
  90443. }
  90444. }
  90445. return mesh;
  90446. };
  90447. // Build Mesh from CSG taking material and transforms into account
  90448. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  90449. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  90450. mesh.material = material;
  90451. mesh.position.copyFrom(this.position);
  90452. mesh.rotation.copyFrom(this.rotation);
  90453. if (this.rotationQuaternion) {
  90454. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  90455. }
  90456. mesh.scaling.copyFrom(this.scaling);
  90457. mesh.computeWorldMatrix(true);
  90458. return mesh;
  90459. };
  90460. return CSG;
  90461. }());
  90462. BABYLON.CSG = CSG;
  90463. })(BABYLON || (BABYLON = {}));
  90464. //# sourceMappingURL=babylon.csg.js.map
  90465. var BABYLON;
  90466. (function (BABYLON) {
  90467. /**
  90468. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90469. * It controls one of the indiviual texture used in the effect.
  90470. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90471. */
  90472. var LensFlare = /** @class */ (function () {
  90473. /**
  90474. * Instantiates a new Lens Flare.
  90475. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90476. * It controls one of the indiviual texture used in the effect.
  90477. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90478. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  90479. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  90480. * @param color Define the lens color
  90481. * @param imgUrl Define the lens texture url
  90482. * @param system Define the `lensFlareSystem` this flare is part of
  90483. */
  90484. function LensFlare(
  90485. /**
  90486. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  90487. */
  90488. size,
  90489. /**
  90490. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  90491. */
  90492. position, color, imgUrl, system) {
  90493. this.size = size;
  90494. this.position = position;
  90495. /**
  90496. * Define the alpha mode to render this particular lens.
  90497. */
  90498. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90499. this.color = color || new BABYLON.Color3(1, 1, 1);
  90500. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  90501. this._system = system;
  90502. system.lensFlares.push(this);
  90503. }
  90504. /**
  90505. * Creates a new Lens Flare.
  90506. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90507. * It controls one of the indiviual texture used in the effect.
  90508. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90509. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  90510. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  90511. * @param color Define the lens color
  90512. * @param imgUrl Define the lens texture url
  90513. * @param system Define the `lensFlareSystem` this flare is part of
  90514. * @returns The newly created Lens Flare
  90515. */
  90516. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  90517. return new LensFlare(size, position, color, imgUrl, system);
  90518. };
  90519. /**
  90520. * Dispose and release the lens flare with its associated resources.
  90521. */
  90522. LensFlare.prototype.dispose = function () {
  90523. if (this.texture) {
  90524. this.texture.dispose();
  90525. }
  90526. // Remove from scene
  90527. var index = this._system.lensFlares.indexOf(this);
  90528. this._system.lensFlares.splice(index, 1);
  90529. };
  90530. ;
  90531. return LensFlare;
  90532. }());
  90533. BABYLON.LensFlare = LensFlare;
  90534. })(BABYLON || (BABYLON = {}));
  90535. //# sourceMappingURL=babylon.lensFlare.js.map
  90536. var BABYLON;
  90537. (function (BABYLON) {
  90538. // Adds the parser to the scene parsers.
  90539. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  90540. // Lens flares
  90541. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  90542. if (!container.lensFlareSystems) {
  90543. container.lensFlareSystems = new Array();
  90544. }
  90545. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  90546. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  90547. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  90548. container.lensFlareSystems.push(lf);
  90549. }
  90550. }
  90551. });
  90552. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  90553. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90554. if (this.lensFlareSystems[index].name === name) {
  90555. return this.lensFlareSystems[index];
  90556. }
  90557. }
  90558. return null;
  90559. };
  90560. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  90561. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90562. if (this.lensFlareSystems[index].id === id) {
  90563. return this.lensFlareSystems[index];
  90564. }
  90565. }
  90566. return null;
  90567. };
  90568. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  90569. var index = this.lensFlareSystems.indexOf(toRemove);
  90570. if (index !== -1) {
  90571. this.lensFlareSystems.splice(index, 1);
  90572. }
  90573. return index;
  90574. };
  90575. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  90576. this.lensFlareSystems.push(newLensFlareSystem);
  90577. };
  90578. /**
  90579. * Defines the lens flare scene component responsible to manage any lens flares
  90580. * in a given scene.
  90581. */
  90582. var LensFlareSystemSceneComponent = /** @class */ (function () {
  90583. /**
  90584. * Creates a new instance of the component for the given scene
  90585. * @param scene Defines the scene to register the component in
  90586. */
  90587. function LensFlareSystemSceneComponent(scene) {
  90588. /**
  90589. * The component name helpfull to identify the component in the list of scene components.
  90590. */
  90591. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  90592. this.scene = scene;
  90593. scene.lensFlareSystems = new Array();
  90594. }
  90595. /**
  90596. * Registers the component in a given scene
  90597. */
  90598. LensFlareSystemSceneComponent.prototype.register = function () {
  90599. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  90600. };
  90601. /**
  90602. * Rebuilds the elements related to this component in case of
  90603. * context lost for instance.
  90604. */
  90605. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  90606. // Nothing to do for lens flare
  90607. };
  90608. /**
  90609. * Adds all the element from the container to the scene
  90610. * @param container the container holding the elements
  90611. */
  90612. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  90613. var _this = this;
  90614. if (!container.lensFlareSystems) {
  90615. return;
  90616. }
  90617. container.lensFlareSystems.forEach(function (o) {
  90618. _this.scene.addLensFlareSystem(o);
  90619. });
  90620. };
  90621. /**
  90622. * Removes all the elements in the container from the scene
  90623. * @param container contains the elements to remove
  90624. */
  90625. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  90626. var _this = this;
  90627. if (!container.lensFlareSystems) {
  90628. return;
  90629. }
  90630. container.lensFlareSystems.forEach(function (o) {
  90631. _this.scene.removeLensFlareSystem(o);
  90632. });
  90633. };
  90634. /**
  90635. * Serializes the component data to the specified json object
  90636. * @param serializationObject The object to serialize to
  90637. */
  90638. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  90639. // Lens flares
  90640. serializationObject.lensFlareSystems = [];
  90641. var lensFlareSystems = this.scene.lensFlareSystems;
  90642. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  90643. var lensFlareSystem = lensFlareSystems_1[_i];
  90644. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  90645. }
  90646. };
  90647. /**
  90648. * Disposes the component and the associated ressources.
  90649. */
  90650. LensFlareSystemSceneComponent.prototype.dispose = function () {
  90651. var lensFlareSystems = this.scene.lensFlareSystems;
  90652. while (lensFlareSystems.length) {
  90653. lensFlareSystems[0].dispose();
  90654. }
  90655. };
  90656. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  90657. // Lens flares
  90658. if (this.scene.lensFlaresEnabled) {
  90659. var lensFlareSystems = this.scene.lensFlareSystems;
  90660. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90661. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  90662. var lensFlareSystem = lensFlareSystems_2[_i];
  90663. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  90664. lensFlareSystem.render();
  90665. }
  90666. }
  90667. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90668. }
  90669. };
  90670. return LensFlareSystemSceneComponent;
  90671. }());
  90672. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  90673. })(BABYLON || (BABYLON = {}));
  90674. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  90675. var BABYLON;
  90676. (function (BABYLON) {
  90677. /**
  90678. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90679. * It is usually composed of several `BABYLON.lensFlare`.
  90680. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90681. */
  90682. var LensFlareSystem = /** @class */ (function () {
  90683. /**
  90684. * Instantiates a lens flare system.
  90685. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90686. * It is usually composed of several `BABYLON.lensFlare`.
  90687. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90688. * @param name Define the name of the lens flare system in the scene
  90689. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  90690. * @param scene Define the scene the lens flare system belongs to
  90691. */
  90692. function LensFlareSystem(
  90693. /**
  90694. * Define the name of the lens flare system
  90695. */
  90696. name, emitter, scene) {
  90697. this.name = name;
  90698. /**
  90699. * List of lens flares used in this system.
  90700. */
  90701. this.lensFlares = new Array();
  90702. /**
  90703. * Define a limit from the border the lens flare can be visible.
  90704. */
  90705. this.borderLimit = 300;
  90706. /**
  90707. * Define a viewport border we do not want to see the lens flare in.
  90708. */
  90709. this.viewportBorder = 0;
  90710. /**
  90711. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  90712. */
  90713. this.layerMask = 0x0FFFFFFF;
  90714. this._vertexBuffers = {};
  90715. this._isEnabled = true;
  90716. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90717. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  90718. if (!component) {
  90719. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  90720. scene._addComponent(component);
  90721. }
  90722. this._emitter = emitter;
  90723. this.id = name;
  90724. scene.lensFlareSystems.push(this);
  90725. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  90726. var engine = scene.getEngine();
  90727. // VBO
  90728. var vertices = [];
  90729. vertices.push(1, 1);
  90730. vertices.push(-1, 1);
  90731. vertices.push(-1, -1);
  90732. vertices.push(1, -1);
  90733. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90734. // Indices
  90735. var indices = [];
  90736. indices.push(0);
  90737. indices.push(1);
  90738. indices.push(2);
  90739. indices.push(0);
  90740. indices.push(2);
  90741. indices.push(3);
  90742. this._indexBuffer = engine.createIndexBuffer(indices);
  90743. // Effects
  90744. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  90745. }
  90746. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  90747. /**
  90748. * Define if the lens flare system is enabled.
  90749. */
  90750. get: function () {
  90751. return this._isEnabled;
  90752. },
  90753. set: function (value) {
  90754. this._isEnabled = value;
  90755. },
  90756. enumerable: true,
  90757. configurable: true
  90758. });
  90759. /**
  90760. * Get the scene the effects belongs to.
  90761. * @returns the scene holding the lens flare system
  90762. */
  90763. LensFlareSystem.prototype.getScene = function () {
  90764. return this._scene;
  90765. };
  90766. /**
  90767. * Get the emitter of the lens flare system.
  90768. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90769. * @returns the emitter of the lens flare system
  90770. */
  90771. LensFlareSystem.prototype.getEmitter = function () {
  90772. return this._emitter;
  90773. };
  90774. /**
  90775. * Set the emitter of the lens flare system.
  90776. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90777. * @param newEmitter Define the new emitter of the system
  90778. */
  90779. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  90780. this._emitter = newEmitter;
  90781. };
  90782. /**
  90783. * Get the lens flare system emitter position.
  90784. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  90785. * @returns the position
  90786. */
  90787. LensFlareSystem.prototype.getEmitterPosition = function () {
  90788. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  90789. };
  90790. /**
  90791. * @hidden
  90792. */
  90793. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  90794. var position = this.getEmitterPosition();
  90795. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  90796. this._positionX = position.x;
  90797. this._positionY = position.y;
  90798. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  90799. if (this.viewportBorder > 0) {
  90800. globalViewport.x -= this.viewportBorder;
  90801. globalViewport.y -= this.viewportBorder;
  90802. globalViewport.width += this.viewportBorder * 2;
  90803. globalViewport.height += this.viewportBorder * 2;
  90804. position.x += this.viewportBorder;
  90805. position.y += this.viewportBorder;
  90806. this._positionX += this.viewportBorder;
  90807. this._positionY += this.viewportBorder;
  90808. }
  90809. if (position.z > 0) {
  90810. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  90811. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  90812. return true;
  90813. }
  90814. return true;
  90815. }
  90816. return false;
  90817. };
  90818. /** @hidden */
  90819. LensFlareSystem.prototype._isVisible = function () {
  90820. if (!this._isEnabled || !this._scene.activeCamera) {
  90821. return false;
  90822. }
  90823. var emitterPosition = this.getEmitterPosition();
  90824. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  90825. var distance = direction.length();
  90826. direction.normalize();
  90827. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  90828. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  90829. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  90830. };
  90831. /**
  90832. * @hidden
  90833. */
  90834. LensFlareSystem.prototype.render = function () {
  90835. if (!this._effect.isReady() || !this._scene.activeCamera)
  90836. return false;
  90837. var engine = this._scene.getEngine();
  90838. var viewport = this._scene.activeCamera.viewport;
  90839. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  90840. // Position
  90841. if (!this.computeEffectivePosition(globalViewport)) {
  90842. return false;
  90843. }
  90844. // Visibility
  90845. if (!this._isVisible()) {
  90846. return false;
  90847. }
  90848. // Intensity
  90849. var awayX;
  90850. var awayY;
  90851. if (this._positionX < this.borderLimit + globalViewport.x) {
  90852. awayX = this.borderLimit + globalViewport.x - this._positionX;
  90853. }
  90854. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  90855. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  90856. }
  90857. else {
  90858. awayX = 0;
  90859. }
  90860. if (this._positionY < this.borderLimit + globalViewport.y) {
  90861. awayY = this.borderLimit + globalViewport.y - this._positionY;
  90862. }
  90863. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  90864. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  90865. }
  90866. else {
  90867. awayY = 0;
  90868. }
  90869. var away = (awayX > awayY) ? awayX : awayY;
  90870. away -= this.viewportBorder;
  90871. if (away > this.borderLimit) {
  90872. away = this.borderLimit;
  90873. }
  90874. var intensity = 1.0 - (away / this.borderLimit);
  90875. if (intensity < 0) {
  90876. return false;
  90877. }
  90878. if (intensity > 1.0) {
  90879. intensity = 1.0;
  90880. }
  90881. if (this.viewportBorder > 0) {
  90882. globalViewport.x += this.viewportBorder;
  90883. globalViewport.y += this.viewportBorder;
  90884. globalViewport.width -= this.viewportBorder * 2;
  90885. globalViewport.height -= this.viewportBorder * 2;
  90886. this._positionX -= this.viewportBorder;
  90887. this._positionY -= this.viewportBorder;
  90888. }
  90889. // Position
  90890. var centerX = globalViewport.x + globalViewport.width / 2;
  90891. var centerY = globalViewport.y + globalViewport.height / 2;
  90892. var distX = centerX - this._positionX;
  90893. var distY = centerY - this._positionY;
  90894. // Effects
  90895. engine.enableEffect(this._effect);
  90896. engine.setState(false);
  90897. engine.setDepthBuffer(false);
  90898. // VBOs
  90899. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  90900. // Flares
  90901. for (var index = 0; index < this.lensFlares.length; index++) {
  90902. var flare = this.lensFlares[index];
  90903. engine.setAlphaMode(flare.alphaMode);
  90904. var x = centerX - (distX * flare.position);
  90905. var y = centerY - (distY * flare.position);
  90906. var cw = flare.size;
  90907. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  90908. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  90909. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  90910. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  90911. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  90912. // Texture
  90913. this._effect.setTexture("textureSampler", flare.texture);
  90914. // Color
  90915. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  90916. // Draw order
  90917. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90918. }
  90919. engine.setDepthBuffer(true);
  90920. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90921. return true;
  90922. };
  90923. /**
  90924. * Dispose and release the lens flare with its associated resources.
  90925. */
  90926. LensFlareSystem.prototype.dispose = function () {
  90927. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90928. if (vertexBuffer) {
  90929. vertexBuffer.dispose();
  90930. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90931. }
  90932. if (this._indexBuffer) {
  90933. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90934. this._indexBuffer = null;
  90935. }
  90936. while (this.lensFlares.length) {
  90937. this.lensFlares[0].dispose();
  90938. }
  90939. // Remove from scene
  90940. var index = this._scene.lensFlareSystems.indexOf(this);
  90941. this._scene.lensFlareSystems.splice(index, 1);
  90942. };
  90943. /**
  90944. * Parse a lens flare system from a JSON repressentation
  90945. * @param parsedLensFlareSystem Define the JSON to parse
  90946. * @param scene Define the scene the parsed system should be instantiated in
  90947. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  90948. * @returns the parsed system
  90949. */
  90950. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  90951. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  90952. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  90953. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  90954. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  90955. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  90956. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  90957. var parsedFlare = parsedLensFlareSystem.flares[index];
  90958. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  90959. }
  90960. return lensFlareSystem;
  90961. };
  90962. /**
  90963. * Serialize the current Lens Flare System into a JSON representation.
  90964. * @returns the serialized JSON
  90965. */
  90966. LensFlareSystem.prototype.serialize = function () {
  90967. var serializationObject = {};
  90968. serializationObject.id = this.id;
  90969. serializationObject.name = this.name;
  90970. serializationObject.emitterId = this.getEmitter().id;
  90971. serializationObject.borderLimit = this.borderLimit;
  90972. serializationObject.flares = [];
  90973. for (var index = 0; index < this.lensFlares.length; index++) {
  90974. var flare = this.lensFlares[index];
  90975. serializationObject.flares.push({
  90976. size: flare.size,
  90977. position: flare.position,
  90978. color: flare.color.asArray(),
  90979. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  90980. });
  90981. }
  90982. return serializationObject;
  90983. };
  90984. return LensFlareSystem;
  90985. }());
  90986. BABYLON.LensFlareSystem = LensFlareSystem;
  90987. })(BABYLON || (BABYLON = {}));
  90988. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  90989. var BABYLON;
  90990. (function (BABYLON) {
  90991. /**
  90992. * This is a holder class for the physics joint created by the physics plugin.
  90993. * It holds a set of functions to control the underlying joint.
  90994. */
  90995. var PhysicsJoint = /** @class */ (function () {
  90996. function PhysicsJoint(type, jointData) {
  90997. this.type = type;
  90998. this.jointData = jointData;
  90999. jointData.nativeParams = jointData.nativeParams || {};
  91000. }
  91001. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  91002. get: function () {
  91003. return this._physicsJoint;
  91004. },
  91005. set: function (newJoint) {
  91006. if (this._physicsJoint) {
  91007. //remove from the wolrd
  91008. }
  91009. this._physicsJoint = newJoint;
  91010. },
  91011. enumerable: true,
  91012. configurable: true
  91013. });
  91014. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  91015. set: function (physicsPlugin) {
  91016. this._physicsPlugin = physicsPlugin;
  91017. },
  91018. enumerable: true,
  91019. configurable: true
  91020. });
  91021. /**
  91022. * Execute a function that is physics-plugin specific.
  91023. * @param {Function} func the function that will be executed.
  91024. * It accepts two parameters: the physics world and the physics joint.
  91025. */
  91026. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  91027. func(this._physicsPlugin.world, this._physicsJoint);
  91028. };
  91029. //TODO check if the native joints are the same
  91030. //Joint Types
  91031. PhysicsJoint.DistanceJoint = 0;
  91032. PhysicsJoint.HingeJoint = 1;
  91033. PhysicsJoint.BallAndSocketJoint = 2;
  91034. PhysicsJoint.WheelJoint = 3;
  91035. PhysicsJoint.SliderJoint = 4;
  91036. //OIMO
  91037. PhysicsJoint.PrismaticJoint = 5;
  91038. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  91039. PhysicsJoint.UniversalJoint = 6;
  91040. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  91041. //Cannon
  91042. //Similar to a Ball-Joint. Different in params
  91043. PhysicsJoint.PointToPointJoint = 8;
  91044. //Cannon only at the moment
  91045. PhysicsJoint.SpringJoint = 9;
  91046. PhysicsJoint.LockJoint = 10;
  91047. return PhysicsJoint;
  91048. }());
  91049. BABYLON.PhysicsJoint = PhysicsJoint;
  91050. /**
  91051. * A class representing a physics distance joint.
  91052. */
  91053. var DistanceJoint = /** @class */ (function (_super) {
  91054. __extends(DistanceJoint, _super);
  91055. function DistanceJoint(jointData) {
  91056. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  91057. }
  91058. /**
  91059. * Update the predefined distance.
  91060. */
  91061. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  91062. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  91063. };
  91064. return DistanceJoint;
  91065. }(PhysicsJoint));
  91066. BABYLON.DistanceJoint = DistanceJoint;
  91067. var MotorEnabledJoint = /** @class */ (function (_super) {
  91068. __extends(MotorEnabledJoint, _super);
  91069. function MotorEnabledJoint(type, jointData) {
  91070. return _super.call(this, type, jointData) || this;
  91071. }
  91072. /**
  91073. * Set the motor values.
  91074. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91075. * @param {number} force the force to apply
  91076. * @param {number} maxForce max force for this motor.
  91077. */
  91078. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  91079. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91080. };
  91081. /**
  91082. * Set the motor's limits.
  91083. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91084. */
  91085. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91086. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91087. };
  91088. return MotorEnabledJoint;
  91089. }(PhysicsJoint));
  91090. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  91091. /**
  91092. * This class represents a single hinge physics joint
  91093. */
  91094. var HingeJoint = /** @class */ (function (_super) {
  91095. __extends(HingeJoint, _super);
  91096. function HingeJoint(jointData) {
  91097. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  91098. }
  91099. /**
  91100. * Set the motor values.
  91101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91102. * @param {number} force the force to apply
  91103. * @param {number} maxForce max force for this motor.
  91104. */
  91105. HingeJoint.prototype.setMotor = function (force, maxForce) {
  91106. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91107. };
  91108. /**
  91109. * Set the motor's limits.
  91110. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91111. */
  91112. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91113. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91114. };
  91115. return HingeJoint;
  91116. }(MotorEnabledJoint));
  91117. BABYLON.HingeJoint = HingeJoint;
  91118. /**
  91119. * This class represents a dual hinge physics joint (same as wheel joint)
  91120. */
  91121. var Hinge2Joint = /** @class */ (function (_super) {
  91122. __extends(Hinge2Joint, _super);
  91123. function Hinge2Joint(jointData) {
  91124. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  91125. }
  91126. /**
  91127. * Set the motor values.
  91128. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91129. * @param {number} force the force to apply
  91130. * @param {number} maxForce max force for this motor.
  91131. * @param {motorIndex} the motor's index, 0 or 1.
  91132. */
  91133. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  91134. if (motorIndex === void 0) { motorIndex = 0; }
  91135. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  91136. };
  91137. /**
  91138. * Set the motor limits.
  91139. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91140. * @param {number} upperLimit the upper limit
  91141. * @param {number} lowerLimit lower limit
  91142. * @param {motorIndex} the motor's index, 0 or 1.
  91143. */
  91144. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  91145. if (motorIndex === void 0) { motorIndex = 0; }
  91146. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  91147. };
  91148. return Hinge2Joint;
  91149. }(MotorEnabledJoint));
  91150. BABYLON.Hinge2Joint = Hinge2Joint;
  91151. })(BABYLON || (BABYLON = {}));
  91152. //# sourceMappingURL=babylon.physicsJoint.js.map
  91153. var BABYLON;
  91154. (function (BABYLON) {
  91155. var PhysicsImpostor = /** @class */ (function () {
  91156. function PhysicsImpostor(object, type, _options, _scene) {
  91157. if (_options === void 0) { _options = { mass: 0 }; }
  91158. var _this = this;
  91159. this.object = object;
  91160. this.type = type;
  91161. this._options = _options;
  91162. this._scene = _scene;
  91163. this._bodyUpdateRequired = false;
  91164. this._onBeforePhysicsStepCallbacks = new Array();
  91165. this._onAfterPhysicsStepCallbacks = new Array();
  91166. this._onPhysicsCollideCallbacks = [];
  91167. this._deltaPosition = BABYLON.Vector3.Zero();
  91168. this._isDisposed = false;
  91169. //temp variables for parent rotation calculations
  91170. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  91171. this._tmpQuat = new BABYLON.Quaternion();
  91172. this._tmpQuat2 = new BABYLON.Quaternion();
  91173. /**
  91174. * this function is executed by the physics engine.
  91175. */
  91176. this.beforeStep = function () {
  91177. if (!_this._physicsEngine) {
  91178. return;
  91179. }
  91180. _this.object.translate(_this._deltaPosition, -1);
  91181. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  91182. _this.object.computeWorldMatrix(false);
  91183. if (_this.object.parent && _this.object.rotationQuaternion) {
  91184. _this.getParentsRotation();
  91185. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  91186. }
  91187. else {
  91188. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  91189. }
  91190. if (!_this._options.disableBidirectionalTransformation) {
  91191. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  91192. }
  91193. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  91194. func(_this);
  91195. });
  91196. };
  91197. /**
  91198. * this function is executed by the physics engine.
  91199. */
  91200. this.afterStep = function () {
  91201. if (!_this._physicsEngine) {
  91202. return;
  91203. }
  91204. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  91205. func(_this);
  91206. });
  91207. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  91208. // object has now its world rotation. needs to be converted to local.
  91209. if (_this.object.parent && _this.object.rotationQuaternion) {
  91210. _this.getParentsRotation();
  91211. _this._tmpQuat.conjugateInPlace();
  91212. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  91213. }
  91214. // take the position set and make it the absolute position of this object.
  91215. _this.object.setAbsolutePosition(_this.object.position);
  91216. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  91217. _this.object.translate(_this._deltaPosition, 1);
  91218. };
  91219. /**
  91220. * Legacy collision detection event support
  91221. */
  91222. this.onCollideEvent = null;
  91223. //event and body object due to cannon's event-based architecture.
  91224. this.onCollide = function (e) {
  91225. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  91226. return;
  91227. }
  91228. if (!_this._physicsEngine) {
  91229. return;
  91230. }
  91231. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  91232. if (otherImpostor) {
  91233. // Legacy collision detection event support
  91234. if (_this.onCollideEvent) {
  91235. _this.onCollideEvent(_this, otherImpostor);
  91236. }
  91237. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  91238. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  91239. }).forEach(function (obj) {
  91240. obj.callback(_this, otherImpostor);
  91241. });
  91242. }
  91243. };
  91244. //sanity check!
  91245. if (!this.object) {
  91246. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  91247. return;
  91248. }
  91249. //legacy support for old syntax.
  91250. if (!this._scene && object.getScene) {
  91251. this._scene = object.getScene();
  91252. }
  91253. if (!this._scene) {
  91254. return;
  91255. }
  91256. this._physicsEngine = this._scene.getPhysicsEngine();
  91257. if (!this._physicsEngine) {
  91258. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  91259. }
  91260. else {
  91261. //set the object's quaternion, if not set
  91262. if (!this.object.rotationQuaternion) {
  91263. if (this.object.rotation) {
  91264. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  91265. }
  91266. else {
  91267. this.object.rotationQuaternion = new BABYLON.Quaternion();
  91268. }
  91269. }
  91270. //default options params
  91271. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  91272. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  91273. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  91274. this._joints = [];
  91275. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  91276. if (!this.object.parent || this._options.ignoreParent) {
  91277. this._init();
  91278. }
  91279. else if (this.object.parent.physicsImpostor) {
  91280. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  91281. }
  91282. }
  91283. }
  91284. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  91285. get: function () {
  91286. return this._isDisposed;
  91287. },
  91288. enumerable: true,
  91289. configurable: true
  91290. });
  91291. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  91292. get: function () {
  91293. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  91294. },
  91295. set: function (value) {
  91296. this.setMass(value);
  91297. },
  91298. enumerable: true,
  91299. configurable: true
  91300. });
  91301. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  91302. get: function () {
  91303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  91304. },
  91305. set: function (value) {
  91306. if (!this._physicsEngine) {
  91307. return;
  91308. }
  91309. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  91310. },
  91311. enumerable: true,
  91312. configurable: true
  91313. });
  91314. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  91315. get: function () {
  91316. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  91317. },
  91318. set: function (value) {
  91319. if (!this._physicsEngine) {
  91320. return;
  91321. }
  91322. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  91323. },
  91324. enumerable: true,
  91325. configurable: true
  91326. });
  91327. /**
  91328. * This function will completly initialize this impostor.
  91329. * It will create a new body - but only if this mesh has no parent.
  91330. * If it has, this impostor will not be used other than to define the impostor
  91331. * of the child mesh.
  91332. * @hidden
  91333. */
  91334. PhysicsImpostor.prototype._init = function () {
  91335. if (!this._physicsEngine) {
  91336. return;
  91337. }
  91338. this._physicsEngine.removeImpostor(this);
  91339. this.physicsBody = null;
  91340. this._parent = this._parent || this._getPhysicsParent();
  91341. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  91342. this._physicsEngine.addImpostor(this);
  91343. }
  91344. };
  91345. PhysicsImpostor.prototype._getPhysicsParent = function () {
  91346. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  91347. var parentMesh = this.object.parent;
  91348. return parentMesh.physicsImpostor;
  91349. }
  91350. return null;
  91351. };
  91352. /**
  91353. * Should a new body be generated.
  91354. */
  91355. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  91356. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  91357. };
  91358. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  91359. this.forceUpdate();
  91360. };
  91361. /**
  91362. * Force a regeneration of this or the parent's impostor's body.
  91363. * Use under cautious - This will remove all joints already implemented.
  91364. */
  91365. PhysicsImpostor.prototype.forceUpdate = function () {
  91366. this._init();
  91367. if (this.parent && !this._options.ignoreParent) {
  91368. this.parent.forceUpdate();
  91369. }
  91370. };
  91371. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  91372. /*public get mesh(): AbstractMesh {
  91373. return this._mesh;
  91374. }*/
  91375. /**
  91376. * Gets the body that holds this impostor. Either its own, or its parent.
  91377. */
  91378. get: function () {
  91379. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  91380. },
  91381. /**
  91382. * Set the physics body. Used mainly by the physics engine/plugin
  91383. */
  91384. set: function (physicsBody) {
  91385. if (this._physicsBody && this._physicsEngine) {
  91386. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  91387. }
  91388. this._physicsBody = physicsBody;
  91389. this.resetUpdateFlags();
  91390. },
  91391. enumerable: true,
  91392. configurable: true
  91393. });
  91394. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  91395. get: function () {
  91396. return !this._options.ignoreParent && this._parent ? this._parent : null;
  91397. },
  91398. set: function (value) {
  91399. this._parent = value;
  91400. },
  91401. enumerable: true,
  91402. configurable: true
  91403. });
  91404. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  91405. this._bodyUpdateRequired = false;
  91406. };
  91407. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  91408. if (this.object.getBoundingInfo) {
  91409. var q = this.object.rotationQuaternion;
  91410. //reset rotation
  91411. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  91412. //calculate the world matrix with no rotation
  91413. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91414. var boundingInfo = this.object.getBoundingInfo();
  91415. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  91416. //bring back the rotation
  91417. this.object.rotationQuaternion = q;
  91418. //calculate the world matrix with the new rotation
  91419. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91420. return size;
  91421. }
  91422. else {
  91423. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  91424. }
  91425. };
  91426. PhysicsImpostor.prototype.getObjectCenter = function () {
  91427. if (this.object.getBoundingInfo) {
  91428. var boundingInfo = this.object.getBoundingInfo();
  91429. return boundingInfo.boundingBox.centerWorld;
  91430. }
  91431. else {
  91432. return this.object.position;
  91433. }
  91434. };
  91435. /**
  91436. * Get a specific parametes from the options parameter.
  91437. */
  91438. PhysicsImpostor.prototype.getParam = function (paramName) {
  91439. return this._options[paramName];
  91440. };
  91441. /**
  91442. * Sets a specific parameter in the options given to the physics plugin
  91443. */
  91444. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  91445. this._options[paramName] = value;
  91446. this._bodyUpdateRequired = true;
  91447. };
  91448. /**
  91449. * Specifically change the body's mass option. Won't recreate the physics body object
  91450. */
  91451. PhysicsImpostor.prototype.setMass = function (mass) {
  91452. if (this.getParam("mass") !== mass) {
  91453. this.setParam("mass", mass);
  91454. }
  91455. if (this._physicsEngine) {
  91456. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  91457. }
  91458. };
  91459. PhysicsImpostor.prototype.getLinearVelocity = function () {
  91460. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  91461. };
  91462. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  91463. if (this._physicsEngine) {
  91464. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  91465. }
  91466. };
  91467. PhysicsImpostor.prototype.getAngularVelocity = function () {
  91468. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  91469. };
  91470. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  91471. if (this._physicsEngine) {
  91472. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  91473. }
  91474. };
  91475. /**
  91476. * Execute a function with the physics plugin native code.
  91477. * Provide a function the will have two variables - the world object and the physics body object.
  91478. */
  91479. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  91480. if (this._physicsEngine) {
  91481. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  91482. }
  91483. };
  91484. /**
  91485. * Register a function that will be executed before the physics world is stepping forward.
  91486. */
  91487. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  91488. this._onBeforePhysicsStepCallbacks.push(func);
  91489. };
  91490. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  91491. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  91492. if (index > -1) {
  91493. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  91494. }
  91495. else {
  91496. BABYLON.Tools.Warn("Function to remove was not found");
  91497. }
  91498. };
  91499. /**
  91500. * Register a function that will be executed after the physics step
  91501. */
  91502. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  91503. this._onAfterPhysicsStepCallbacks.push(func);
  91504. };
  91505. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  91506. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  91507. if (index > -1) {
  91508. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  91509. }
  91510. else {
  91511. BABYLON.Tools.Warn("Function to remove was not found");
  91512. }
  91513. };
  91514. /**
  91515. * register a function that will be executed when this impostor collides against a different body.
  91516. */
  91517. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  91518. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91519. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  91520. };
  91521. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  91522. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91523. var index = -1;
  91524. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  91525. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  91526. // chcek the arrays match
  91527. var sameList = cbDef.otherImpostors.every(function (impostor) {
  91528. return collidedAgainstList.indexOf(impostor) > -1;
  91529. });
  91530. if (sameList) {
  91531. index = idx;
  91532. }
  91533. return sameList;
  91534. }
  91535. return false;
  91536. });
  91537. if (found) {
  91538. this._onPhysicsCollideCallbacks.splice(index, 1);
  91539. }
  91540. else {
  91541. BABYLON.Tools.Warn("Function to remove was not found");
  91542. }
  91543. };
  91544. PhysicsImpostor.prototype.getParentsRotation = function () {
  91545. var parent = this.object.parent;
  91546. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  91547. while (parent) {
  91548. if (parent.rotationQuaternion) {
  91549. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  91550. }
  91551. else {
  91552. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  91553. }
  91554. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  91555. parent = parent.parent;
  91556. }
  91557. return this._tmpQuat;
  91558. };
  91559. /**
  91560. * Apply a force
  91561. */
  91562. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  91563. if (this._physicsEngine) {
  91564. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  91565. }
  91566. return this;
  91567. };
  91568. /**
  91569. * Apply an impulse
  91570. */
  91571. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  91572. if (this._physicsEngine) {
  91573. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  91574. }
  91575. return this;
  91576. };
  91577. /**
  91578. * A help function to create a joint.
  91579. */
  91580. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  91581. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  91582. this.addJoint(otherImpostor, joint);
  91583. return this;
  91584. };
  91585. /**
  91586. * Add a joint to this impostor with a different impostor.
  91587. */
  91588. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  91589. this._joints.push({
  91590. otherImpostor: otherImpostor,
  91591. joint: joint
  91592. });
  91593. if (this._physicsEngine) {
  91594. this._physicsEngine.addJoint(this, otherImpostor, joint);
  91595. }
  91596. return this;
  91597. };
  91598. /**
  91599. * Will keep this body still, in a sleep mode.
  91600. */
  91601. PhysicsImpostor.prototype.sleep = function () {
  91602. if (this._physicsEngine) {
  91603. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  91604. }
  91605. return this;
  91606. };
  91607. /**
  91608. * Wake the body up.
  91609. */
  91610. PhysicsImpostor.prototype.wakeUp = function () {
  91611. if (this._physicsEngine) {
  91612. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  91613. }
  91614. return this;
  91615. };
  91616. PhysicsImpostor.prototype.clone = function (newObject) {
  91617. if (!newObject)
  91618. return null;
  91619. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  91620. };
  91621. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  91622. var _this = this;
  91623. //no dispose if no physics engine is available.
  91624. if (!this._physicsEngine) {
  91625. return;
  91626. }
  91627. this._joints.forEach(function (j) {
  91628. if (_this._physicsEngine) {
  91629. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  91630. }
  91631. });
  91632. //dispose the physics body
  91633. this._physicsEngine.removeImpostor(this);
  91634. if (this.parent) {
  91635. this.parent.forceUpdate();
  91636. }
  91637. else {
  91638. /*this._object.getChildMeshes().forEach(function(mesh) {
  91639. if (mesh.physicsImpostor) {
  91640. if (disposeChildren) {
  91641. mesh.physicsImpostor.dispose();
  91642. mesh.physicsImpostor = null;
  91643. }
  91644. }
  91645. })*/
  91646. }
  91647. this._isDisposed = true;
  91648. };
  91649. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  91650. this._deltaPosition.copyFrom(position);
  91651. };
  91652. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  91653. if (!this._deltaRotation) {
  91654. this._deltaRotation = new BABYLON.Quaternion();
  91655. }
  91656. this._deltaRotation.copyFrom(rotation);
  91657. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  91658. };
  91659. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  91660. if (this._physicsEngine) {
  91661. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  91662. }
  91663. return this;
  91664. };
  91665. PhysicsImpostor.prototype.getRadius = function () {
  91666. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  91667. };
  91668. /**
  91669. * Sync a bone with this impostor
  91670. * @param bone The bone to sync to the impostor.
  91671. * @param boneMesh The mesh that the bone is influencing.
  91672. * @param jointPivot The pivot of the joint / bone in local space.
  91673. * @param distToJoint Optional distance from the impostor to the joint.
  91674. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91675. */
  91676. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  91677. var tempVec = PhysicsImpostor._tmpVecs[0];
  91678. var mesh = this.object;
  91679. if (mesh.rotationQuaternion) {
  91680. if (adjustRotation) {
  91681. var tempQuat = PhysicsImpostor._tmpQuat;
  91682. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  91683. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  91684. }
  91685. else {
  91686. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  91687. }
  91688. }
  91689. tempVec.x = 0;
  91690. tempVec.y = 0;
  91691. tempVec.z = 0;
  91692. if (jointPivot) {
  91693. tempVec.x = jointPivot.x;
  91694. tempVec.y = jointPivot.y;
  91695. tempVec.z = jointPivot.z;
  91696. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  91697. if (distToJoint === undefined || distToJoint === null) {
  91698. distToJoint = jointPivot.length();
  91699. }
  91700. tempVec.x *= distToJoint;
  91701. tempVec.y *= distToJoint;
  91702. tempVec.z *= distToJoint;
  91703. }
  91704. if (bone.getParent()) {
  91705. tempVec.addInPlace(mesh.getAbsolutePosition());
  91706. bone.setAbsolutePosition(tempVec, boneMesh);
  91707. }
  91708. else {
  91709. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  91710. boneMesh.position.x -= tempVec.x;
  91711. boneMesh.position.y -= tempVec.y;
  91712. boneMesh.position.z -= tempVec.z;
  91713. }
  91714. };
  91715. /**
  91716. * Sync impostor to a bone
  91717. * @param bone The bone that the impostor will be synced to.
  91718. * @param boneMesh The mesh that the bone is influencing.
  91719. * @param jointPivot The pivot of the joint / bone in local space.
  91720. * @param distToJoint Optional distance from the impostor to the joint.
  91721. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91722. * @param boneAxis Optional vector3 axis the bone is aligned with
  91723. */
  91724. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  91725. var mesh = this.object;
  91726. if (mesh.rotationQuaternion) {
  91727. if (adjustRotation) {
  91728. var tempQuat = PhysicsImpostor._tmpQuat;
  91729. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  91730. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  91731. }
  91732. else {
  91733. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  91734. }
  91735. }
  91736. var pos = PhysicsImpostor._tmpVecs[0];
  91737. var boneDir = PhysicsImpostor._tmpVecs[1];
  91738. if (!boneAxis) {
  91739. boneAxis = PhysicsImpostor._tmpVecs[2];
  91740. boneAxis.x = 0;
  91741. boneAxis.y = 1;
  91742. boneAxis.z = 0;
  91743. }
  91744. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  91745. bone.getAbsolutePositionToRef(boneMesh, pos);
  91746. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  91747. distToJoint = jointPivot.length();
  91748. }
  91749. if (distToJoint !== undefined && distToJoint !== null) {
  91750. pos.x += boneDir.x * distToJoint;
  91751. pos.y += boneDir.y * distToJoint;
  91752. pos.z += boneDir.z * distToJoint;
  91753. }
  91754. mesh.setAbsolutePosition(pos);
  91755. };
  91756. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  91757. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  91758. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91759. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  91760. //Impostor types
  91761. PhysicsImpostor.NoImpostor = 0;
  91762. PhysicsImpostor.SphereImpostor = 1;
  91763. PhysicsImpostor.BoxImpostor = 2;
  91764. PhysicsImpostor.PlaneImpostor = 3;
  91765. PhysicsImpostor.MeshImpostor = 4;
  91766. PhysicsImpostor.CylinderImpostor = 7;
  91767. PhysicsImpostor.ParticleImpostor = 8;
  91768. PhysicsImpostor.HeightmapImpostor = 9;
  91769. return PhysicsImpostor;
  91770. }());
  91771. BABYLON.PhysicsImpostor = PhysicsImpostor;
  91772. })(BABYLON || (BABYLON = {}));
  91773. //# sourceMappingURL=babylon.physicsImpostor.js.map
  91774. var BABYLON;
  91775. (function (BABYLON) {
  91776. /**
  91777. * Class used to control physics engine
  91778. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91779. */
  91780. var PhysicsEngine = /** @class */ (function () {
  91781. /**
  91782. * Creates a new Physics Engine
  91783. * @param gravity defines the gravity vector used by the simulation
  91784. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  91785. */
  91786. function PhysicsEngine(gravity, _physicsPlugin) {
  91787. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  91788. this._physicsPlugin = _physicsPlugin;
  91789. this._impostors = [];
  91790. this._joints = [];
  91791. if (!this._physicsPlugin.isSupported()) {
  91792. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  91793. + "Please make sure it is included.");
  91794. }
  91795. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  91796. this.setGravity(gravity);
  91797. this.setTimeStep();
  91798. }
  91799. /**
  91800. * Sets the gravity vector used by the simulation
  91801. * @param gravity defines the gravity vector to use
  91802. */
  91803. PhysicsEngine.prototype.setGravity = function (gravity) {
  91804. this.gravity = gravity;
  91805. this._physicsPlugin.setGravity(this.gravity);
  91806. };
  91807. /**
  91808. * Set the time step of the physics engine.
  91809. * Default is 1/60.
  91810. * To slow it down, enter 1/600 for example.
  91811. * To speed it up, 1/30
  91812. * @param newTimeStep defines the new timestep to apply to this world.
  91813. */
  91814. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  91815. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  91816. this._physicsPlugin.setTimeStep(newTimeStep);
  91817. };
  91818. /**
  91819. * Get the time step of the physics engine.
  91820. * @returns the current time step
  91821. */
  91822. PhysicsEngine.prototype.getTimeStep = function () {
  91823. return this._physicsPlugin.getTimeStep();
  91824. };
  91825. /**
  91826. * Release all resources
  91827. */
  91828. PhysicsEngine.prototype.dispose = function () {
  91829. this._impostors.forEach(function (impostor) {
  91830. impostor.dispose();
  91831. });
  91832. this._physicsPlugin.dispose();
  91833. };
  91834. /**
  91835. * Gets the name of the current physics plugin
  91836. * @returns the name of the plugin
  91837. */
  91838. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  91839. return this._physicsPlugin.name;
  91840. };
  91841. /**
  91842. * Adding a new impostor for the impostor tracking.
  91843. * This will be done by the impostor itself.
  91844. * @param impostor the impostor to add
  91845. */
  91846. PhysicsEngine.prototype.addImpostor = function (impostor) {
  91847. impostor.uniqueId = this._impostors.push(impostor);
  91848. //if no parent, generate the body
  91849. if (!impostor.parent) {
  91850. this._physicsPlugin.generatePhysicsBody(impostor);
  91851. }
  91852. };
  91853. /**
  91854. * Remove an impostor from the engine.
  91855. * This impostor and its mesh will not longer be updated by the physics engine.
  91856. * @param impostor the impostor to remove
  91857. */
  91858. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  91859. var index = this._impostors.indexOf(impostor);
  91860. if (index > -1) {
  91861. var removed = this._impostors.splice(index, 1);
  91862. //Is it needed?
  91863. if (removed.length) {
  91864. //this will also remove it from the world.
  91865. removed[0].physicsBody = null;
  91866. }
  91867. }
  91868. };
  91869. /**
  91870. * Add a joint to the physics engine
  91871. * @param mainImpostor defines the main impostor to which the joint is added.
  91872. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  91873. * @param joint defines the joint that will connect both impostors.
  91874. */
  91875. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  91876. var impostorJoint = {
  91877. mainImpostor: mainImpostor,
  91878. connectedImpostor: connectedImpostor,
  91879. joint: joint
  91880. };
  91881. joint.physicsPlugin = this._physicsPlugin;
  91882. this._joints.push(impostorJoint);
  91883. this._physicsPlugin.generateJoint(impostorJoint);
  91884. };
  91885. /**
  91886. * Removes a joint from the simulation
  91887. * @param mainImpostor defines the impostor used with the joint
  91888. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  91889. * @param joint defines the joint to remove
  91890. */
  91891. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  91892. var matchingJoints = this._joints.filter(function (impostorJoint) {
  91893. return (impostorJoint.connectedImpostor === connectedImpostor
  91894. && impostorJoint.joint === joint
  91895. && impostorJoint.mainImpostor === mainImpostor);
  91896. });
  91897. if (matchingJoints.length) {
  91898. this._physicsPlugin.removeJoint(matchingJoints[0]);
  91899. //TODO remove it from the list as well
  91900. }
  91901. };
  91902. /**
  91903. * Called by the scene. No need to call it.
  91904. * @param delta defines the timespam between frames
  91905. */
  91906. PhysicsEngine.prototype._step = function (delta) {
  91907. var _this = this;
  91908. //check if any mesh has no body / requires an update
  91909. this._impostors.forEach(function (impostor) {
  91910. if (impostor.isBodyInitRequired()) {
  91911. _this._physicsPlugin.generatePhysicsBody(impostor);
  91912. }
  91913. });
  91914. if (delta > 0.1) {
  91915. delta = 0.1;
  91916. }
  91917. else if (delta <= 0) {
  91918. delta = 1.0 / 60.0;
  91919. }
  91920. this._physicsPlugin.executeStep(delta, this._impostors);
  91921. };
  91922. /**
  91923. * Gets the current plugin used to run the simulation
  91924. * @returns current plugin
  91925. */
  91926. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  91927. return this._physicsPlugin;
  91928. };
  91929. /**
  91930. * Gets the list of physic impostors
  91931. * @returns an array of PhysicsImpostor
  91932. */
  91933. PhysicsEngine.prototype.getImpostors = function () {
  91934. return this._impostors;
  91935. };
  91936. /**
  91937. * Gets the impostor for a physics enabled object
  91938. * @param object defines the object impersonated by the impostor
  91939. * @returns the PhysicsImpostor or null if not found
  91940. */
  91941. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  91942. for (var i = 0; i < this._impostors.length; ++i) {
  91943. if (this._impostors[i].object === object) {
  91944. return this._impostors[i];
  91945. }
  91946. }
  91947. return null;
  91948. };
  91949. /**
  91950. * Gets the impostor for a physics body object
  91951. * @param body defines physics body used by the impostor
  91952. * @returns the PhysicsImpostor or null if not found
  91953. */
  91954. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  91955. for (var i = 0; i < this._impostors.length; ++i) {
  91956. if (this._impostors[i].physicsBody === body) {
  91957. return this._impostors[i];
  91958. }
  91959. }
  91960. return null;
  91961. };
  91962. /**
  91963. * Global value used to control the smallest number supported by the simulation
  91964. */
  91965. PhysicsEngine.Epsilon = 0.001;
  91966. return PhysicsEngine;
  91967. }());
  91968. BABYLON.PhysicsEngine = PhysicsEngine;
  91969. })(BABYLON || (BABYLON = {}));
  91970. //# sourceMappingURL=babylon.physicsEngine.js.map
  91971. var BABYLON;
  91972. (function (BABYLON) {
  91973. var PhysicsHelper = /** @class */ (function () {
  91974. function PhysicsHelper(scene) {
  91975. this._scene = scene;
  91976. this._physicsEngine = this._scene.getPhysicsEngine();
  91977. if (!this._physicsEngine) {
  91978. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  91979. }
  91980. }
  91981. /**
  91982. * @param {Vector3} origin the origin of the explosion
  91983. * @param {number} radius the explosion radius
  91984. * @param {number} strength the explosion strength
  91985. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91986. */
  91987. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  91988. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91989. if (!this._physicsEngine) {
  91990. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  91991. return null;
  91992. }
  91993. var impostors = this._physicsEngine.getImpostors();
  91994. if (impostors.length === 0) {
  91995. return null;
  91996. }
  91997. var event = new PhysicsRadialExplosionEvent(this._scene);
  91998. impostors.forEach(function (impostor) {
  91999. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92000. if (!impostorForceAndContactPoint) {
  92001. return;
  92002. }
  92003. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92004. });
  92005. event.dispose(false);
  92006. return event;
  92007. };
  92008. /**
  92009. * @param {Vector3} origin the origin of the explosion
  92010. * @param {number} radius the explosion radius
  92011. * @param {number} strength the explosion strength
  92012. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92013. */
  92014. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  92015. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92016. if (!this._physicsEngine) {
  92017. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92018. return null;
  92019. }
  92020. var impostors = this._physicsEngine.getImpostors();
  92021. if (impostors.length === 0) {
  92022. return null;
  92023. }
  92024. var event = new PhysicsRadialExplosionEvent(this._scene);
  92025. impostors.forEach(function (impostor) {
  92026. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92027. if (!impostorForceAndContactPoint) {
  92028. return;
  92029. }
  92030. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92031. });
  92032. event.dispose(false);
  92033. return event;
  92034. };
  92035. /**
  92036. * @param {Vector3} origin the origin of the explosion
  92037. * @param {number} radius the explosion radius
  92038. * @param {number} strength the explosion strength
  92039. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92040. */
  92041. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  92042. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92043. if (!this._physicsEngine) {
  92044. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92045. return null;
  92046. }
  92047. var impostors = this._physicsEngine.getImpostors();
  92048. if (impostors.length === 0) {
  92049. return null;
  92050. }
  92051. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  92052. event.dispose(false);
  92053. return event;
  92054. };
  92055. /**
  92056. * @param {Vector3} origin the origin of the updraft
  92057. * @param {number} radius the radius of the updraft
  92058. * @param {number} strength the strength of the updraft
  92059. * @param {number} height the height of the updraft
  92060. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  92061. */
  92062. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  92063. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  92064. if (!this._physicsEngine) {
  92065. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92066. return null;
  92067. }
  92068. if (this._physicsEngine.getImpostors().length === 0) {
  92069. return null;
  92070. }
  92071. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  92072. event.dispose(false);
  92073. return event;
  92074. };
  92075. /**
  92076. * @param {Vector3} origin the of the vortex
  92077. * @param {number} radius the radius of the vortex
  92078. * @param {number} strength the strength of the vortex
  92079. * @param {number} height the height of the vortex
  92080. */
  92081. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  92082. if (!this._physicsEngine) {
  92083. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92084. return null;
  92085. }
  92086. if (this._physicsEngine.getImpostors().length === 0) {
  92087. return null;
  92088. }
  92089. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  92090. event.dispose(false);
  92091. return event;
  92092. };
  92093. return PhysicsHelper;
  92094. }());
  92095. BABYLON.PhysicsHelper = PhysicsHelper;
  92096. /***** Radial explosion *****/
  92097. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  92098. function PhysicsRadialExplosionEvent(scene) {
  92099. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  92100. this._rays = [];
  92101. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  92102. this._scene = scene;
  92103. }
  92104. /**
  92105. * Returns the data related to the radial explosion event (sphere & rays).
  92106. * @returns {PhysicsRadialExplosionEventData}
  92107. */
  92108. PhysicsRadialExplosionEvent.prototype.getData = function () {
  92109. this._dataFetched = true;
  92110. return {
  92111. sphere: this._sphere,
  92112. rays: this._rays,
  92113. };
  92114. };
  92115. /**
  92116. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  92117. * @param impostor
  92118. * @param {Vector3} origin the origin of the explosion
  92119. * @param {number} radius the explosion radius
  92120. * @param {number} strength the explosion strength
  92121. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  92122. * @returns {Nullable<PhysicsForceAndContactPoint>}
  92123. */
  92124. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  92125. if (impostor.mass === 0) {
  92126. return null;
  92127. }
  92128. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  92129. return null;
  92130. }
  92131. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92132. return null;
  92133. }
  92134. var impostorObjectCenter = impostor.getObjectCenter();
  92135. var direction = impostorObjectCenter.subtract(origin);
  92136. var ray = new BABYLON.Ray(origin, direction, radius);
  92137. this._rays.push(ray);
  92138. var hit = ray.intersectsMesh(impostor.object);
  92139. var contactPoint = hit.pickedPoint;
  92140. if (!contactPoint) {
  92141. return null;
  92142. }
  92143. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  92144. if (distanceFromOrigin > radius) {
  92145. return null;
  92146. }
  92147. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  92148. ? strength
  92149. : strength * (1 - (distanceFromOrigin / radius));
  92150. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92151. return { force: force, contactPoint: contactPoint };
  92152. };
  92153. /**
  92154. * Disposes the sphere.
  92155. * @param {bolean} force
  92156. */
  92157. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  92158. var _this = this;
  92159. if (force === void 0) { force = true; }
  92160. if (force) {
  92161. this._sphere.dispose();
  92162. }
  92163. else {
  92164. setTimeout(function () {
  92165. if (!_this._dataFetched) {
  92166. _this._sphere.dispose();
  92167. }
  92168. }, 0);
  92169. }
  92170. };
  92171. /*** Helpers ***/
  92172. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  92173. if (!this._sphere) {
  92174. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  92175. this._sphere.isVisible = false;
  92176. }
  92177. };
  92178. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  92179. var impostorObject = impostor.object;
  92180. this._prepareSphere();
  92181. this._sphere.position = origin;
  92182. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  92183. this._sphere._updateBoundingInfo();
  92184. this._sphere.computeWorldMatrix(true);
  92185. return this._sphere.intersectsMesh(impostorObject, true);
  92186. };
  92187. return PhysicsRadialExplosionEvent;
  92188. }());
  92189. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  92190. /***** Gravitational Field *****/
  92191. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  92192. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  92193. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92194. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92195. this._physicsHelper = physicsHelper;
  92196. this._scene = scene;
  92197. this._origin = origin;
  92198. this._radius = radius;
  92199. this._strength = strength;
  92200. this._falloff = falloff;
  92201. this._tickCallback = this._tick.bind(this);
  92202. }
  92203. /**
  92204. * Returns the data related to the gravitational field event (sphere).
  92205. * @returns {PhysicsGravitationalFieldEventData}
  92206. */
  92207. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  92208. this._dataFetched = true;
  92209. return {
  92210. sphere: this._sphere,
  92211. };
  92212. };
  92213. /**
  92214. * Enables the gravitational field.
  92215. */
  92216. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  92217. this._tickCallback.call(this);
  92218. this._scene.registerBeforeRender(this._tickCallback);
  92219. };
  92220. /**
  92221. * Disables the gravitational field.
  92222. */
  92223. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  92224. this._scene.unregisterBeforeRender(this._tickCallback);
  92225. };
  92226. /**
  92227. * Disposes the sphere.
  92228. * @param {bolean} force
  92229. */
  92230. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  92231. var _this = this;
  92232. if (force === void 0) { force = true; }
  92233. if (force) {
  92234. this._sphere.dispose();
  92235. }
  92236. else {
  92237. setTimeout(function () {
  92238. if (!_this._dataFetched) {
  92239. _this._sphere.dispose();
  92240. }
  92241. }, 0);
  92242. }
  92243. };
  92244. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  92245. // Since the params won't change, we fetch the event only once
  92246. if (this._sphere) {
  92247. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92248. }
  92249. else {
  92250. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92251. if (radialExplosionEvent) {
  92252. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  92253. }
  92254. }
  92255. };
  92256. return PhysicsGravitationalFieldEvent;
  92257. }());
  92258. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  92259. /***** Updraft *****/
  92260. var PhysicsUpdraftEvent = /** @class */ (function () {
  92261. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  92262. this._scene = _scene;
  92263. this._origin = _origin;
  92264. this._radius = _radius;
  92265. this._strength = _strength;
  92266. this._height = _height;
  92267. this._updraftMode = _updraftMode;
  92268. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92269. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  92270. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92271. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92272. this._physicsEngine = this._scene.getPhysicsEngine();
  92273. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92274. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92275. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92276. this._originDirection = this._origin.subtract(this._originTop).normalize();
  92277. }
  92278. this._tickCallback = this._tick.bind(this);
  92279. }
  92280. /**
  92281. * Returns the data related to the updraft event (cylinder).
  92282. * @returns {PhysicsUpdraftEventData}
  92283. */
  92284. PhysicsUpdraftEvent.prototype.getData = function () {
  92285. this._dataFetched = true;
  92286. return {
  92287. cylinder: this._cylinder,
  92288. };
  92289. };
  92290. /**
  92291. * Enables the updraft.
  92292. */
  92293. PhysicsUpdraftEvent.prototype.enable = function () {
  92294. this._tickCallback.call(this);
  92295. this._scene.registerBeforeRender(this._tickCallback);
  92296. };
  92297. /**
  92298. * Disables the cortex.
  92299. */
  92300. PhysicsUpdraftEvent.prototype.disable = function () {
  92301. this._scene.unregisterBeforeRender(this._tickCallback);
  92302. };
  92303. /**
  92304. * Disposes the sphere.
  92305. * @param {bolean} force
  92306. */
  92307. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  92308. var _this = this;
  92309. if (force === void 0) { force = true; }
  92310. if (force) {
  92311. this._cylinder.dispose();
  92312. }
  92313. else {
  92314. setTimeout(function () {
  92315. if (!_this._dataFetched) {
  92316. _this._cylinder.dispose();
  92317. }
  92318. }, 0);
  92319. }
  92320. };
  92321. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92322. if (impostor.mass === 0) {
  92323. return null;
  92324. }
  92325. if (!this._intersectsWithCylinder(impostor)) {
  92326. return null;
  92327. }
  92328. var impostorObjectCenter = impostor.getObjectCenter();
  92329. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92330. var direction = this._originDirection;
  92331. }
  92332. else {
  92333. var direction = impostorObjectCenter.subtract(this._originTop);
  92334. }
  92335. var multiplier = this._strength * -1;
  92336. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92337. return { force: force, contactPoint: impostorObjectCenter };
  92338. };
  92339. PhysicsUpdraftEvent.prototype._tick = function () {
  92340. var _this = this;
  92341. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92342. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92343. if (!impostorForceAndContactPoint) {
  92344. return;
  92345. }
  92346. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92347. });
  92348. };
  92349. /*** Helpers ***/
  92350. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  92351. if (!this._cylinder) {
  92352. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  92353. height: this._height,
  92354. diameter: this._radius * 2,
  92355. }, this._scene);
  92356. this._cylinder.isVisible = false;
  92357. }
  92358. };
  92359. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  92360. var impostorObject = impostor.object;
  92361. this._prepareCylinder();
  92362. this._cylinder.position = this._cylinderPosition;
  92363. return this._cylinder.intersectsMesh(impostorObject, true);
  92364. };
  92365. return PhysicsUpdraftEvent;
  92366. }());
  92367. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  92368. /***** Vortex *****/
  92369. var PhysicsVortexEvent = /** @class */ (function () {
  92370. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  92371. this._scene = _scene;
  92372. this._origin = _origin;
  92373. this._radius = _radius;
  92374. this._strength = _strength;
  92375. this._height = _height;
  92376. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92377. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  92378. this._updraftMultiplier = 0.02;
  92379. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92380. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92381. this._physicsEngine = this._scene.getPhysicsEngine();
  92382. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92383. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92384. this._tickCallback = this._tick.bind(this);
  92385. }
  92386. /**
  92387. * Returns the data related to the vortex event (cylinder).
  92388. * @returns {PhysicsVortexEventData}
  92389. */
  92390. PhysicsVortexEvent.prototype.getData = function () {
  92391. this._dataFetched = true;
  92392. return {
  92393. cylinder: this._cylinder,
  92394. };
  92395. };
  92396. /**
  92397. * Enables the vortex.
  92398. */
  92399. PhysicsVortexEvent.prototype.enable = function () {
  92400. this._tickCallback.call(this);
  92401. this._scene.registerBeforeRender(this._tickCallback);
  92402. };
  92403. /**
  92404. * Disables the cortex.
  92405. */
  92406. PhysicsVortexEvent.prototype.disable = function () {
  92407. this._scene.unregisterBeforeRender(this._tickCallback);
  92408. };
  92409. /**
  92410. * Disposes the sphere.
  92411. * @param {bolean} force
  92412. */
  92413. PhysicsVortexEvent.prototype.dispose = function (force) {
  92414. var _this = this;
  92415. if (force === void 0) { force = true; }
  92416. if (force) {
  92417. this._cylinder.dispose();
  92418. }
  92419. else {
  92420. setTimeout(function () {
  92421. if (!_this._dataFetched) {
  92422. _this._cylinder.dispose();
  92423. }
  92424. }, 0);
  92425. }
  92426. };
  92427. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92428. if (impostor.mass === 0) {
  92429. return null;
  92430. }
  92431. if (!this._intersectsWithCylinder(impostor)) {
  92432. return null;
  92433. }
  92434. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92435. return null;
  92436. }
  92437. var impostorObjectCenter = impostor.getObjectCenter();
  92438. 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)
  92439. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  92440. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  92441. var hit = ray.intersectsMesh(impostor.object);
  92442. var contactPoint = hit.pickedPoint;
  92443. if (!contactPoint) {
  92444. return null;
  92445. }
  92446. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  92447. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  92448. var directionToOrigin = contactPoint.normalize();
  92449. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92450. directionToOrigin = directionToOrigin.negate();
  92451. }
  92452. // TODO: find a more physically based solution
  92453. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92454. var forceX = directionToOrigin.x * this._strength / 8;
  92455. var forceY = directionToOrigin.y * this._updraftMultiplier;
  92456. var forceZ = directionToOrigin.z * this._strength / 8;
  92457. }
  92458. else {
  92459. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  92460. var forceY = this._originTop.y * this._updraftMultiplier;
  92461. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  92462. }
  92463. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  92464. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  92465. return { force: force, contactPoint: impostorObjectCenter };
  92466. };
  92467. PhysicsVortexEvent.prototype._tick = function () {
  92468. var _this = this;
  92469. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92470. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92471. if (!impostorForceAndContactPoint) {
  92472. return;
  92473. }
  92474. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92475. });
  92476. };
  92477. /*** Helpers ***/
  92478. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  92479. if (!this._cylinder) {
  92480. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  92481. height: this._height,
  92482. diameter: this._radius * 2,
  92483. }, this._scene);
  92484. this._cylinder.isVisible = false;
  92485. }
  92486. };
  92487. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  92488. var impostorObject = impostor.object;
  92489. this._prepareCylinder();
  92490. this._cylinder.position = this._cylinderPosition;
  92491. return this._cylinder.intersectsMesh(impostorObject, true);
  92492. };
  92493. return PhysicsVortexEvent;
  92494. }());
  92495. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  92496. /***** Enums *****/
  92497. /**
  92498. * The strenght of the force in correspondence to the distance of the affected object
  92499. */
  92500. var PhysicsRadialImpulseFalloff;
  92501. (function (PhysicsRadialImpulseFalloff) {
  92502. /** Defines that impulse is constant in strength across it's whole radius */
  92503. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  92504. /** DEfines that impulse gets weaker if it's further from the origin */
  92505. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  92506. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  92507. /**
  92508. * The strenght of the force in correspondence to the distance of the affected object
  92509. */
  92510. var PhysicsUpdraftMode;
  92511. (function (PhysicsUpdraftMode) {
  92512. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  92513. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  92514. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  92515. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  92516. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  92517. })(BABYLON || (BABYLON = {}));
  92518. //# sourceMappingURL=babylon.physicsHelper.js.map
  92519. var BABYLON;
  92520. (function (BABYLON) {
  92521. /** @hidden */
  92522. var CannonJSPlugin = /** @class */ (function () {
  92523. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  92524. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  92525. if (iterations === void 0) { iterations = 10; }
  92526. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  92527. this.name = "CannonJSPlugin";
  92528. this._physicsMaterials = new Array();
  92529. this._fixedTimeStep = 1 / 60;
  92530. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  92531. this.BJSCANNON = CANNON;
  92532. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  92533. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  92534. this._tmpPosition = BABYLON.Vector3.Zero();
  92535. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  92536. this._tmpUnityRotation = new BABYLON.Quaternion();
  92537. if (!this.isSupported()) {
  92538. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  92539. return;
  92540. }
  92541. this._extendNamespace();
  92542. this.world = new this.BJSCANNON.World();
  92543. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  92544. this.world.solver.iterations = iterations;
  92545. }
  92546. CannonJSPlugin.prototype.setGravity = function (gravity) {
  92547. this.world.gravity.copy(gravity);
  92548. };
  92549. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  92550. this._fixedTimeStep = timeStep;
  92551. };
  92552. CannonJSPlugin.prototype.getTimeStep = function () {
  92553. return this._fixedTimeStep;
  92554. };
  92555. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  92556. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  92557. };
  92558. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92559. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92560. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92561. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  92562. };
  92563. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92564. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92565. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92566. impostor.physicsBody.applyForce(impulse, worldPoint);
  92567. };
  92568. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92569. //parent-child relationship. Does this impostor has a parent impostor?
  92570. if (impostor.parent) {
  92571. if (impostor.physicsBody) {
  92572. this.removePhysicsBody(impostor);
  92573. //TODO is that needed?
  92574. impostor.forceUpdate();
  92575. }
  92576. return;
  92577. }
  92578. //should a new body be created for this impostor?
  92579. if (impostor.isBodyInitRequired()) {
  92580. var shape = this._createShape(impostor);
  92581. //unregister events, if body is being changed
  92582. var oldBody = impostor.physicsBody;
  92583. if (oldBody) {
  92584. this.removePhysicsBody(impostor);
  92585. }
  92586. //create the body and material
  92587. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  92588. var bodyCreationObject = {
  92589. mass: impostor.getParam("mass"),
  92590. material: material
  92591. };
  92592. // A simple extend, in case native options were used.
  92593. var nativeOptions = impostor.getParam("nativeOptions");
  92594. for (var key in nativeOptions) {
  92595. if (nativeOptions.hasOwnProperty(key)) {
  92596. bodyCreationObject[key] = nativeOptions[key];
  92597. }
  92598. }
  92599. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  92600. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  92601. this.world.addEventListener("preStep", impostor.beforeStep);
  92602. this.world.addEventListener("postStep", impostor.afterStep);
  92603. impostor.physicsBody.addShape(shape);
  92604. this.world.add(impostor.physicsBody);
  92605. //try to keep the body moving in the right direction by taking old properties.
  92606. //Should be tested!
  92607. if (oldBody) {
  92608. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  92609. impostor.physicsBody[param].copy(oldBody[param]);
  92610. });
  92611. }
  92612. this._processChildMeshes(impostor);
  92613. }
  92614. //now update the body's transformation
  92615. this._updatePhysicsBodyTransformation(impostor);
  92616. };
  92617. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  92618. var _this = this;
  92619. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  92620. var currentRotation = mainImpostor.object.rotationQuaternion;
  92621. if (meshChildren.length) {
  92622. var processMesh = function (localPosition, mesh) {
  92623. if (!currentRotation || !mesh.rotationQuaternion) {
  92624. return;
  92625. }
  92626. var childImpostor = mesh.getPhysicsImpostor();
  92627. if (childImpostor) {
  92628. var parent = childImpostor.parent;
  92629. if (parent !== mainImpostor) {
  92630. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  92631. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  92632. if (childImpostor.physicsBody) {
  92633. _this.removePhysicsBody(childImpostor);
  92634. childImpostor.physicsBody = null;
  92635. }
  92636. childImpostor.parent = mainImpostor;
  92637. childImpostor.resetUpdateFlags();
  92638. 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));
  92639. //Add the mass of the children.
  92640. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  92641. }
  92642. }
  92643. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  92644. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  92645. };
  92646. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  92647. }
  92648. };
  92649. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92650. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  92651. this.world.removeEventListener("preStep", impostor.beforeStep);
  92652. this.world.removeEventListener("postStep", impostor.afterStep);
  92653. this.world.remove(impostor.physicsBody);
  92654. };
  92655. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92656. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92657. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92658. if (!mainBody || !connectedBody) {
  92659. return;
  92660. }
  92661. var constraint;
  92662. var jointData = impostorJoint.joint.jointData;
  92663. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  92664. var constraintData = {
  92665. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  92666. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  92667. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  92668. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  92669. maxForce: jointData.nativeParams.maxForce,
  92670. collideConnected: !!jointData.collision
  92671. };
  92672. switch (impostorJoint.joint.type) {
  92673. case BABYLON.PhysicsJoint.HingeJoint:
  92674. case BABYLON.PhysicsJoint.Hinge2Joint:
  92675. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  92676. break;
  92677. case BABYLON.PhysicsJoint.DistanceJoint:
  92678. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  92679. break;
  92680. case BABYLON.PhysicsJoint.SpringJoint:
  92681. var springData = jointData;
  92682. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  92683. restLength: springData.length,
  92684. stiffness: springData.stiffness,
  92685. damping: springData.damping,
  92686. localAnchorA: constraintData.pivotA,
  92687. localAnchorB: constraintData.pivotB
  92688. });
  92689. break;
  92690. case BABYLON.PhysicsJoint.LockJoint:
  92691. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  92692. break;
  92693. case BABYLON.PhysicsJoint.PointToPointJoint:
  92694. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92695. default:
  92696. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  92697. break;
  92698. }
  92699. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  92700. constraint.collideConnected = !!jointData.collision;
  92701. impostorJoint.joint.physicsJoint = constraint;
  92702. //don't add spring as constraint, as it is not one.
  92703. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92704. this.world.addConstraint(constraint);
  92705. }
  92706. else {
  92707. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  92708. constraint.applyForce();
  92709. };
  92710. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92711. }
  92712. };
  92713. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92714. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92715. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  92716. }
  92717. else {
  92718. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92719. }
  92720. };
  92721. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  92722. var index;
  92723. var mat;
  92724. for (index = 0; index < this._physicsMaterials.length; index++) {
  92725. mat = this._physicsMaterials[index];
  92726. if (mat.friction === friction && mat.restitution === restitution) {
  92727. return mat;
  92728. }
  92729. }
  92730. var currentMat = new this.BJSCANNON.Material(name);
  92731. currentMat.friction = friction;
  92732. currentMat.restitution = restitution;
  92733. this._physicsMaterials.push(currentMat);
  92734. return currentMat;
  92735. };
  92736. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  92737. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  92738. };
  92739. CannonJSPlugin.prototype._createShape = function (impostor) {
  92740. var object = impostor.object;
  92741. var returnValue;
  92742. var extendSize = impostor.getObjectExtendSize();
  92743. switch (impostor.type) {
  92744. case BABYLON.PhysicsImpostor.SphereImpostor:
  92745. var radiusX = extendSize.x;
  92746. var radiusY = extendSize.y;
  92747. var radiusZ = extendSize.z;
  92748. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  92749. break;
  92750. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  92751. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92752. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  92753. break;
  92754. case BABYLON.PhysicsImpostor.BoxImpostor:
  92755. var box = extendSize.scale(0.5);
  92756. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  92757. break;
  92758. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92759. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  92760. returnValue = new this.BJSCANNON.Plane();
  92761. break;
  92762. case BABYLON.PhysicsImpostor.MeshImpostor:
  92763. // should transform the vertex data to world coordinates!!
  92764. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  92765. var rawFaces = object.getIndices ? object.getIndices() : [];
  92766. if (!rawVerts)
  92767. return;
  92768. // get only scale! so the object could transform correctly.
  92769. var oldPosition = object.position.clone();
  92770. var oldRotation = object.rotation && object.rotation.clone();
  92771. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  92772. object.position.copyFromFloats(0, 0, 0);
  92773. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92774. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92775. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92776. var transform = object.computeWorldMatrix(true);
  92777. // convert rawVerts to object space
  92778. var temp = new Array();
  92779. var index;
  92780. for (index = 0; index < rawVerts.length; index += 3) {
  92781. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  92782. }
  92783. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  92784. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  92785. //now set back the transformation!
  92786. object.position.copyFrom(oldPosition);
  92787. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  92788. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  92789. break;
  92790. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  92791. var oldPosition2 = object.position.clone();
  92792. var oldRotation2 = object.rotation && object.rotation.clone();
  92793. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  92794. object.position.copyFromFloats(0, 0, 0);
  92795. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92796. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92797. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92798. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  92799. returnValue = this._createHeightmap(object);
  92800. object.position.copyFrom(oldPosition2);
  92801. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  92802. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  92803. object.computeWorldMatrix(true);
  92804. break;
  92805. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92806. returnValue = new this.BJSCANNON.Particle();
  92807. break;
  92808. }
  92809. return returnValue;
  92810. };
  92811. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  92812. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92813. var transform = object.computeWorldMatrix(true);
  92814. // convert rawVerts to object space
  92815. var temp = new Array();
  92816. var index;
  92817. for (index = 0; index < pos.length; index += 3) {
  92818. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  92819. }
  92820. pos = temp;
  92821. var matrix = new Array();
  92822. //For now pointDepth will not be used and will be automatically calculated.
  92823. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  92824. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  92825. var boundingInfo = object.getBoundingInfo();
  92826. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  92827. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  92828. var elementSize = dim * 2 / arraySize;
  92829. for (var i = 0; i < pos.length; i = i + 3) {
  92830. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  92831. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  92832. var y = -pos[i + 2] + minY;
  92833. if (!matrix[x]) {
  92834. matrix[x] = [];
  92835. }
  92836. if (!matrix[x][z]) {
  92837. matrix[x][z] = y;
  92838. }
  92839. matrix[x][z] = Math.max(y, matrix[x][z]);
  92840. }
  92841. for (var x = 0; x <= arraySize; ++x) {
  92842. if (!matrix[x]) {
  92843. var loc = 1;
  92844. while (!matrix[(x + loc) % arraySize]) {
  92845. loc++;
  92846. }
  92847. matrix[x] = matrix[(x + loc) % arraySize].slice();
  92848. //console.log("missing x", x);
  92849. }
  92850. for (var z = 0; z <= arraySize; ++z) {
  92851. if (!matrix[x][z]) {
  92852. var loc = 1;
  92853. var newValue;
  92854. while (newValue === undefined) {
  92855. newValue = matrix[x][(z + loc++) % arraySize];
  92856. }
  92857. matrix[x][z] = newValue;
  92858. }
  92859. }
  92860. }
  92861. var shape = new this.BJSCANNON.Heightfield(matrix, {
  92862. elementSize: elementSize
  92863. });
  92864. //For future reference, needed for body transformation
  92865. shape.minY = minY;
  92866. return shape;
  92867. };
  92868. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  92869. var object = impostor.object;
  92870. //make sure it is updated...
  92871. object.computeWorldMatrix && object.computeWorldMatrix(true);
  92872. // The delta between the mesh position and the mesh bounding box center
  92873. var bInfo = object.getBoundingInfo();
  92874. if (!bInfo)
  92875. return;
  92876. var center = impostor.getObjectCenter();
  92877. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  92878. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  92879. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  92880. this._tmpPosition.copyFrom(center);
  92881. var quaternion = object.rotationQuaternion;
  92882. if (!quaternion) {
  92883. return;
  92884. }
  92885. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  92886. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  92887. //-90 DEG in X, precalculated
  92888. quaternion = quaternion.multiply(this._minus90X);
  92889. //Invert! (Precalculated, 90 deg in X)
  92890. //No need to clone. this will never change.
  92891. impostor.setDeltaRotation(this._plus90X);
  92892. }
  92893. //If it is a heightfield, if should be centered.
  92894. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  92895. var mesh = object;
  92896. var boundingInfo = mesh.getBoundingInfo();
  92897. //calculate the correct body position:
  92898. var rotationQuaternion = mesh.rotationQuaternion;
  92899. mesh.rotationQuaternion = this._tmpUnityRotation;
  92900. mesh.computeWorldMatrix(true);
  92901. //get original center with no rotation
  92902. var c = center.clone();
  92903. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  92904. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  92905. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  92906. mesh.setPreTransformMatrix(p);
  92907. mesh.computeWorldMatrix(true);
  92908. //calculate the translation
  92909. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  92910. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  92911. //add it inverted to the delta
  92912. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  92913. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  92914. //rotation is back
  92915. mesh.rotationQuaternion = rotationQuaternion;
  92916. mesh.setPreTransformMatrix(oldPivot);
  92917. mesh.computeWorldMatrix(true);
  92918. }
  92919. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  92920. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  92921. //this._tmpPosition.copyFrom(object.position);
  92922. }
  92923. impostor.setDeltaPosition(this._tmpDeltaPosition);
  92924. //Now update the impostor object
  92925. impostor.physicsBody.position.copy(this._tmpPosition);
  92926. impostor.physicsBody.quaternion.copy(quaternion);
  92927. };
  92928. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92929. impostor.object.position.copyFrom(impostor.physicsBody.position);
  92930. if (impostor.object.rotationQuaternion) {
  92931. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  92932. }
  92933. };
  92934. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92935. impostor.physicsBody.position.copy(newPosition);
  92936. impostor.physicsBody.quaternion.copy(newRotation);
  92937. };
  92938. CannonJSPlugin.prototype.isSupported = function () {
  92939. return this.BJSCANNON !== undefined;
  92940. };
  92941. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92942. impostor.physicsBody.velocity.copy(velocity);
  92943. };
  92944. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92945. impostor.physicsBody.angularVelocity.copy(velocity);
  92946. };
  92947. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92948. var v = impostor.physicsBody.velocity;
  92949. if (!v) {
  92950. return null;
  92951. }
  92952. return new BABYLON.Vector3(v.x, v.y, v.z);
  92953. };
  92954. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92955. var v = impostor.physicsBody.angularVelocity;
  92956. if (!v) {
  92957. return null;
  92958. }
  92959. return new BABYLON.Vector3(v.x, v.y, v.z);
  92960. };
  92961. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92962. impostor.physicsBody.mass = mass;
  92963. impostor.physicsBody.updateMassProperties();
  92964. };
  92965. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  92966. return impostor.physicsBody.mass;
  92967. };
  92968. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  92969. return impostor.physicsBody.material.friction;
  92970. };
  92971. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92972. impostor.physicsBody.material.friction = friction;
  92973. };
  92974. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92975. return impostor.physicsBody.material.restitution;
  92976. };
  92977. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92978. impostor.physicsBody.material.restitution = restitution;
  92979. };
  92980. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  92981. impostor.physicsBody.sleep();
  92982. };
  92983. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  92984. impostor.physicsBody.wakeUp();
  92985. };
  92986. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92987. joint.physicsJoint.distance = maxDistance;
  92988. };
  92989. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92990. // if (!motorIndex) {
  92991. // joint.physicsJoint.enableMotor();
  92992. // }
  92993. // }
  92994. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92995. // if (!motorIndex) {
  92996. // joint.physicsJoint.disableMotor();
  92997. // }
  92998. // }
  92999. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93000. if (!motorIndex) {
  93001. joint.physicsJoint.enableMotor();
  93002. joint.physicsJoint.setMotorSpeed(speed);
  93003. if (maxForce) {
  93004. this.setLimit(joint, maxForce);
  93005. }
  93006. }
  93007. };
  93008. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  93009. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  93010. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  93011. };
  93012. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93013. var body = impostor.physicsBody;
  93014. mesh.position.x = body.position.x;
  93015. mesh.position.y = body.position.y;
  93016. mesh.position.z = body.position.z;
  93017. if (mesh.rotationQuaternion) {
  93018. mesh.rotationQuaternion.x = body.quaternion.x;
  93019. mesh.rotationQuaternion.y = body.quaternion.y;
  93020. mesh.rotationQuaternion.z = body.quaternion.z;
  93021. mesh.rotationQuaternion.w = body.quaternion.w;
  93022. }
  93023. };
  93024. CannonJSPlugin.prototype.getRadius = function (impostor) {
  93025. var shape = impostor.physicsBody.shapes[0];
  93026. return shape.boundingSphereRadius;
  93027. };
  93028. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93029. var shape = impostor.physicsBody.shapes[0];
  93030. result.x = shape.halfExtents.x * 2;
  93031. result.y = shape.halfExtents.y * 2;
  93032. result.z = shape.halfExtents.z * 2;
  93033. };
  93034. CannonJSPlugin.prototype.dispose = function () {
  93035. };
  93036. CannonJSPlugin.prototype._extendNamespace = function () {
  93037. //this will force cannon to execute at least one step when using interpolation
  93038. var step_tmp1 = new this.BJSCANNON.Vec3();
  93039. var Engine = this.BJSCANNON;
  93040. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  93041. maxSubSteps = maxSubSteps || 10;
  93042. timeSinceLastCalled = timeSinceLastCalled || 0;
  93043. if (timeSinceLastCalled === 0) {
  93044. this.internalStep(dt);
  93045. this.time += dt;
  93046. }
  93047. else {
  93048. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  93049. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  93050. var t0 = performance.now();
  93051. for (var i = 0; i !== internalSteps; i++) {
  93052. this.internalStep(dt);
  93053. if (performance.now() - t0 > dt * 1000) {
  93054. break;
  93055. }
  93056. }
  93057. this.time += timeSinceLastCalled;
  93058. var h = this.time % dt;
  93059. var h_div_dt = h / dt;
  93060. var interpvelo = step_tmp1;
  93061. var bodies = this.bodies;
  93062. for (var j = 0; j !== bodies.length; j++) {
  93063. var b = bodies[j];
  93064. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  93065. b.position.vsub(b.previousPosition, interpvelo);
  93066. interpvelo.scale(h_div_dt, interpvelo);
  93067. b.position.vadd(interpvelo, b.interpolatedPosition);
  93068. }
  93069. else {
  93070. b.interpolatedPosition.copy(b.position);
  93071. b.interpolatedQuaternion.copy(b.quaternion);
  93072. }
  93073. }
  93074. }
  93075. };
  93076. };
  93077. return CannonJSPlugin;
  93078. }());
  93079. BABYLON.CannonJSPlugin = CannonJSPlugin;
  93080. })(BABYLON || (BABYLON = {}));
  93081. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  93082. var BABYLON;
  93083. (function (BABYLON) {
  93084. /** @hidden */
  93085. var OimoJSPlugin = /** @class */ (function () {
  93086. function OimoJSPlugin(iterations) {
  93087. this.name = "OimoJSPlugin";
  93088. this._tmpImpostorsArray = [];
  93089. this._tmpPositionVector = BABYLON.Vector3.Zero();
  93090. this.BJSOIMO = OIMO;
  93091. this.world = new this.BJSOIMO.World({
  93092. iterations: iterations
  93093. });
  93094. this.world.clear();
  93095. }
  93096. OimoJSPlugin.prototype.setGravity = function (gravity) {
  93097. this.world.gravity.copy(gravity);
  93098. };
  93099. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  93100. this.world.timeStep = timeStep;
  93101. };
  93102. OimoJSPlugin.prototype.getTimeStep = function () {
  93103. return this.world.timeStep;
  93104. };
  93105. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  93106. var _this = this;
  93107. impostors.forEach(function (impostor) {
  93108. impostor.beforeStep();
  93109. });
  93110. this.world.step();
  93111. impostors.forEach(function (impostor) {
  93112. impostor.afterStep();
  93113. //update the ordered impostors array
  93114. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  93115. });
  93116. //check for collisions
  93117. var contact = this.world.contacts;
  93118. while (contact !== null) {
  93119. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  93120. contact = contact.next;
  93121. continue;
  93122. }
  93123. //is this body colliding with any other? get the impostor
  93124. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  93125. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  93126. if (!mainImpostor || !collidingImpostor) {
  93127. contact = contact.next;
  93128. continue;
  93129. }
  93130. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  93131. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  93132. contact = contact.next;
  93133. }
  93134. };
  93135. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93136. var mass = impostor.physicsBody.mass;
  93137. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  93138. };
  93139. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93140. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  93141. this.applyImpulse(impostor, force, contactPoint);
  93142. };
  93143. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93144. var _this = this;
  93145. //parent-child relationship. Does this impostor has a parent impostor?
  93146. if (impostor.parent) {
  93147. if (impostor.physicsBody) {
  93148. this.removePhysicsBody(impostor);
  93149. //TODO is that needed?
  93150. impostor.forceUpdate();
  93151. }
  93152. return;
  93153. }
  93154. if (impostor.isBodyInitRequired()) {
  93155. var bodyConfig = {
  93156. name: impostor.uniqueId,
  93157. //Oimo must have mass, also for static objects.
  93158. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  93159. size: [],
  93160. type: [],
  93161. pos: [],
  93162. posShape: [],
  93163. rot: [],
  93164. rotShape: [],
  93165. move: impostor.getParam("mass") !== 0,
  93166. density: impostor.getParam("mass"),
  93167. friction: impostor.getParam("friction"),
  93168. restitution: impostor.getParam("restitution"),
  93169. //Supporting older versions of Oimo
  93170. world: this.world
  93171. };
  93172. var impostors = [impostor];
  93173. var addToArray = function (parent) {
  93174. if (!parent.getChildMeshes)
  93175. return;
  93176. parent.getChildMeshes().forEach(function (m) {
  93177. if (m.physicsImpostor) {
  93178. impostors.push(m.physicsImpostor);
  93179. //m.physicsImpostor._init();
  93180. }
  93181. });
  93182. };
  93183. addToArray(impostor.object);
  93184. var checkWithEpsilon_1 = function (value) {
  93185. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  93186. };
  93187. var globalQuaternion_1 = new BABYLON.Quaternion();
  93188. impostors.forEach(function (i) {
  93189. if (!i.object.rotationQuaternion) {
  93190. return;
  93191. }
  93192. //get the correct bounding box
  93193. var oldQuaternion = i.object.rotationQuaternion;
  93194. globalQuaternion_1 = oldQuaternion.clone();
  93195. var rot = oldQuaternion.toEulerAngles();
  93196. var extendSize = i.getObjectExtendSize();
  93197. var radToDeg = 57.295779513082320876;
  93198. if (i === impostor) {
  93199. var center = impostor.getObjectCenter();
  93200. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  93201. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  93202. //Can also use Array.prototype.push.apply
  93203. bodyConfig.pos.push(center.x);
  93204. bodyConfig.pos.push(center.y);
  93205. bodyConfig.pos.push(center.z);
  93206. bodyConfig.posShape.push(0, 0, 0);
  93207. //tmp solution
  93208. bodyConfig.rot.push(0);
  93209. bodyConfig.rot.push(0);
  93210. bodyConfig.rot.push(0);
  93211. bodyConfig.rotShape.push(0, 0, 0);
  93212. }
  93213. else {
  93214. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  93215. bodyConfig.posShape.push(localPosition.x);
  93216. bodyConfig.posShape.push(localPosition.y);
  93217. bodyConfig.posShape.push(localPosition.z);
  93218. bodyConfig.pos.push(0, 0, 0);
  93219. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  93220. bodyConfig.rot.push(0);
  93221. bodyConfig.rot.push(0);
  93222. bodyConfig.rot.push(0);
  93223. bodyConfig.rotShape.push(rot.x * radToDeg);
  93224. bodyConfig.rotShape.push(rot.y * radToDeg);
  93225. bodyConfig.rotShape.push(rot.z * radToDeg);
  93226. }
  93227. // register mesh
  93228. switch (i.type) {
  93229. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93230. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  93231. case BABYLON.PhysicsImpostor.SphereImpostor:
  93232. var radiusX = extendSize.x;
  93233. var radiusY = extendSize.y;
  93234. var radiusZ = extendSize.z;
  93235. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  93236. bodyConfig.type.push('sphere');
  93237. //due to the way oimo works with compounds, add 3 times
  93238. bodyConfig.size.push(size);
  93239. bodyConfig.size.push(size);
  93240. bodyConfig.size.push(size);
  93241. break;
  93242. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93243. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  93244. var sizeY = checkWithEpsilon_1(extendSize.y);
  93245. bodyConfig.type.push('cylinder');
  93246. bodyConfig.size.push(sizeX);
  93247. bodyConfig.size.push(sizeY);
  93248. //due to the way oimo works with compounds, add one more value.
  93249. bodyConfig.size.push(sizeY);
  93250. break;
  93251. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93252. case BABYLON.PhysicsImpostor.BoxImpostor:
  93253. default:
  93254. var sizeX = checkWithEpsilon_1(extendSize.x);
  93255. var sizeY = checkWithEpsilon_1(extendSize.y);
  93256. var sizeZ = checkWithEpsilon_1(extendSize.z);
  93257. bodyConfig.type.push('box');
  93258. //if (i === impostor) {
  93259. bodyConfig.size.push(sizeX);
  93260. bodyConfig.size.push(sizeY);
  93261. bodyConfig.size.push(sizeZ);
  93262. //} else {
  93263. // bodyConfig.size.push(0,0,0);
  93264. //}
  93265. break;
  93266. }
  93267. //actually not needed, but hey...
  93268. i.object.rotationQuaternion = oldQuaternion;
  93269. });
  93270. impostor.physicsBody = this.world.add(bodyConfig);
  93271. // set the quaternion, ignoring the previously defined (euler) rotation
  93272. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  93273. // update with delta 0, so the body will reveive the new rotation.
  93274. impostor.physicsBody.updatePosition(0);
  93275. }
  93276. else {
  93277. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  93278. }
  93279. impostor.setDeltaPosition(this._tmpPositionVector);
  93280. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  93281. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  93282. };
  93283. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93284. //impostor.physicsBody.dispose();
  93285. //Same as : (older oimo versions)
  93286. this.world.removeRigidBody(impostor.physicsBody);
  93287. };
  93288. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93289. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93290. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93291. if (!mainBody || !connectedBody) {
  93292. return;
  93293. }
  93294. var jointData = impostorJoint.joint.jointData;
  93295. var options = jointData.nativeParams || {};
  93296. var type;
  93297. var nativeJointData = {
  93298. body1: mainBody,
  93299. body2: connectedBody,
  93300. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  93301. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  93302. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  93303. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  93304. min: options.min,
  93305. max: options.max,
  93306. collision: options.collision || jointData.collision,
  93307. spring: options.spring,
  93308. //supporting older version of Oimo
  93309. world: this.world
  93310. };
  93311. switch (impostorJoint.joint.type) {
  93312. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93313. type = "jointBall";
  93314. break;
  93315. case BABYLON.PhysicsJoint.SpringJoint:
  93316. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  93317. var springData = jointData;
  93318. nativeJointData.min = springData.length || nativeJointData.min;
  93319. //Max should also be set, just make sure it is at least min
  93320. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  93321. case BABYLON.PhysicsJoint.DistanceJoint:
  93322. type = "jointDistance";
  93323. nativeJointData.max = jointData.maxDistance;
  93324. break;
  93325. case BABYLON.PhysicsJoint.PrismaticJoint:
  93326. type = "jointPrisme";
  93327. break;
  93328. case BABYLON.PhysicsJoint.SliderJoint:
  93329. type = "jointSlide";
  93330. break;
  93331. case BABYLON.PhysicsJoint.WheelJoint:
  93332. type = "jointWheel";
  93333. break;
  93334. case BABYLON.PhysicsJoint.HingeJoint:
  93335. default:
  93336. type = "jointHinge";
  93337. break;
  93338. }
  93339. nativeJointData.type = type;
  93340. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  93341. };
  93342. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93343. //Bug in Oimo prevents us from disposing a joint in the playground
  93344. //joint.joint.physicsJoint.dispose();
  93345. //So we will bruteforce it!
  93346. try {
  93347. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  93348. }
  93349. catch (e) {
  93350. BABYLON.Tools.Warn(e);
  93351. }
  93352. };
  93353. OimoJSPlugin.prototype.isSupported = function () {
  93354. return this.BJSOIMO !== undefined;
  93355. };
  93356. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93357. if (!impostor.physicsBody.sleeping) {
  93358. //TODO check that
  93359. /*if (impostor.physicsBody.shapes.next) {
  93360. var parentShape = this._getLastShape(impostor.physicsBody);
  93361. impostor.object.position.copyFrom(parentShape.position);
  93362. console.log(parentShape.position);
  93363. } else {*/
  93364. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  93365. //}
  93366. if (impostor.object.rotationQuaternion) {
  93367. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  93368. }
  93369. }
  93370. };
  93371. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93372. var body = impostor.physicsBody;
  93373. body.position.copy(newPosition);
  93374. body.orientation.copy(newRotation);
  93375. body.syncShapes();
  93376. body.awake();
  93377. };
  93378. /*private _getLastShape(body: any): any {
  93379. var lastShape = body.shapes;
  93380. while (lastShape.next) {
  93381. lastShape = lastShape.next;
  93382. }
  93383. return lastShape;
  93384. }*/
  93385. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93386. impostor.physicsBody.linearVelocity.copy(velocity);
  93387. };
  93388. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93389. impostor.physicsBody.angularVelocity.copy(velocity);
  93390. };
  93391. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93392. var v = impostor.physicsBody.linearVelocity;
  93393. if (!v) {
  93394. return null;
  93395. }
  93396. return new BABYLON.Vector3(v.x, v.y, v.z);
  93397. };
  93398. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93399. var v = impostor.physicsBody.angularVelocity;
  93400. if (!v) {
  93401. return null;
  93402. }
  93403. return new BABYLON.Vector3(v.x, v.y, v.z);
  93404. };
  93405. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93406. var staticBody = mass === 0;
  93407. //this will actually set the body's density and not its mass.
  93408. //But this is how oimo treats the mass variable.
  93409. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  93410. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  93411. };
  93412. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  93413. return impostor.physicsBody.shapes.density;
  93414. };
  93415. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  93416. return impostor.physicsBody.shapes.friction;
  93417. };
  93418. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93419. impostor.physicsBody.shapes.friction = friction;
  93420. };
  93421. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93422. return impostor.physicsBody.shapes.restitution;
  93423. };
  93424. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93425. impostor.physicsBody.shapes.restitution = restitution;
  93426. };
  93427. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  93428. impostor.physicsBody.sleep();
  93429. };
  93430. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  93431. impostor.physicsBody.awake();
  93432. };
  93433. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93434. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  93435. if (minDistance !== void 0) {
  93436. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  93437. }
  93438. };
  93439. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93440. //TODO separate rotational and transational motors.
  93441. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93442. if (motor) {
  93443. motor.setMotor(speed, maxForce);
  93444. }
  93445. };
  93446. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  93447. //TODO separate rotational and transational motors.
  93448. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93449. if (motor) {
  93450. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  93451. }
  93452. };
  93453. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93454. var body = impostor.physicsBody;
  93455. mesh.position.x = body.position.x;
  93456. mesh.position.y = body.position.y;
  93457. mesh.position.z = body.position.z;
  93458. if (mesh.rotationQuaternion) {
  93459. mesh.rotationQuaternion.x = body.orientation.x;
  93460. mesh.rotationQuaternion.y = body.orientation.y;
  93461. mesh.rotationQuaternion.z = body.orientation.z;
  93462. mesh.rotationQuaternion.w = body.orientation.s;
  93463. }
  93464. };
  93465. OimoJSPlugin.prototype.getRadius = function (impostor) {
  93466. return impostor.physicsBody.shapes.radius;
  93467. };
  93468. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93469. var shape = impostor.physicsBody.shapes;
  93470. result.x = shape.halfWidth * 2;
  93471. result.y = shape.halfHeight * 2;
  93472. result.z = shape.halfDepth * 2;
  93473. };
  93474. OimoJSPlugin.prototype.dispose = function () {
  93475. this.world.clear();
  93476. };
  93477. return OimoJSPlugin;
  93478. }());
  93479. BABYLON.OimoJSPlugin = OimoJSPlugin;
  93480. })(BABYLON || (BABYLON = {}));
  93481. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  93482. var BABYLON;
  93483. (function (BABYLON) {
  93484. /**
  93485. * Gets the current physics engine
  93486. * @returns a IPhysicsEngine or null if none attached
  93487. */
  93488. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  93489. return this._physicsEngine;
  93490. };
  93491. /**
  93492. * Enables physics to the current scene
  93493. * @param gravity defines the scene's gravity for the physics engine
  93494. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  93495. * @return a boolean indicating if the physics engine was initialized
  93496. */
  93497. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  93498. if (gravity === void 0) { gravity = null; }
  93499. if (this._physicsEngine) {
  93500. return true;
  93501. }
  93502. // Register the component to the scene
  93503. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  93504. if (!component) {
  93505. component = new PhysicsEngineSceneComponent(this);
  93506. this._addComponent(component);
  93507. }
  93508. try {
  93509. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  93510. return true;
  93511. }
  93512. catch (e) {
  93513. BABYLON.Tools.Error(e.message);
  93514. return false;
  93515. }
  93516. };
  93517. /**
  93518. * Disables and disposes the physics engine associated with the scene
  93519. */
  93520. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  93521. if (!this._physicsEngine) {
  93522. return;
  93523. }
  93524. this._physicsEngine.dispose();
  93525. this._physicsEngine = null;
  93526. };
  93527. /**
  93528. * Gets a boolean indicating if there is an active physics engine
  93529. * @returns a boolean indicating if there is an active physics engine
  93530. */
  93531. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  93532. return this._physicsEngine !== undefined;
  93533. };
  93534. /**
  93535. * Deletes a physics compound impostor
  93536. * @param compound defines the compound to delete
  93537. */
  93538. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  93539. var mesh = compound.parts[0].mesh;
  93540. if (mesh.physicsImpostor) {
  93541. mesh.physicsImpostor.dispose( /*true*/);
  93542. mesh.physicsImpostor = null;
  93543. }
  93544. };
  93545. /** @hidden */
  93546. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  93547. if (this._physicsEngine) {
  93548. this.onBeforePhysicsObservable.notifyObservers(this);
  93549. this._physicsEngine._step(step / 1000);
  93550. this.onAfterPhysicsObservable.notifyObservers(this);
  93551. }
  93552. };
  93553. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  93554. get: function () {
  93555. return this._physicsImpostor;
  93556. },
  93557. set: function (value) {
  93558. var _this = this;
  93559. if (this._physicsImpostor === value) {
  93560. return;
  93561. }
  93562. if (this._disposePhysicsObserver) {
  93563. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  93564. }
  93565. this._physicsImpostor = value;
  93566. if (value) {
  93567. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  93568. // Physics
  93569. if (_this.physicsImpostor) {
  93570. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  93571. _this.physicsImpostor = null;
  93572. }
  93573. });
  93574. }
  93575. },
  93576. enumerable: true,
  93577. configurable: true
  93578. });
  93579. /**
  93580. * Gets the current physics impostor
  93581. * @see http://doc.babylonjs.com/features/physics_engine
  93582. * @returns a physics impostor or null
  93583. */
  93584. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  93585. return this.physicsImpostor;
  93586. };
  93587. /**
  93588. * Apply a physic impulse to the mesh
  93589. * @param force defines the force to apply
  93590. * @param contactPoint defines where to apply the force
  93591. * @returns the current mesh
  93592. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93593. */
  93594. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  93595. if (!this.physicsImpostor) {
  93596. return this;
  93597. }
  93598. this.physicsImpostor.applyImpulse(force, contactPoint);
  93599. return this;
  93600. };
  93601. /**
  93602. * Creates a physic joint between two meshes
  93603. * @param otherMesh defines the other mesh to use
  93604. * @param pivot1 defines the pivot to use on this mesh
  93605. * @param pivot2 defines the pivot to use on the other mesh
  93606. * @param options defines additional options (can be plugin dependent)
  93607. * @returns the current mesh
  93608. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  93609. */
  93610. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  93611. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  93612. return this;
  93613. }
  93614. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  93615. mainPivot: pivot1,
  93616. connectedPivot: pivot2,
  93617. nativeParams: options
  93618. });
  93619. return this;
  93620. };
  93621. /**
  93622. * Defines the physics engine scene component responsible to manage a physics engine
  93623. */
  93624. var PhysicsEngineSceneComponent = /** @class */ (function () {
  93625. /**
  93626. * Creates a new instance of the component for the given scene
  93627. * @param scene Defines the scene to register the component in
  93628. */
  93629. function PhysicsEngineSceneComponent(scene) {
  93630. var _this = this;
  93631. /**
  93632. * The component name helpful to identify the component in the list of scene components.
  93633. */
  93634. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  93635. this.scene = scene;
  93636. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  93637. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  93638. // Replace the function used to get the deterministic frame time
  93639. this.scene.getDeterministicFrameTime = function () {
  93640. if (_this.scene._physicsEngine) {
  93641. return _this.scene._physicsEngine.getTimeStep() * 1000;
  93642. }
  93643. return 1000.0 / 60.0;
  93644. };
  93645. }
  93646. /**
  93647. * Registers the component in a given scene
  93648. */
  93649. PhysicsEngineSceneComponent.prototype.register = function () {
  93650. };
  93651. /**
  93652. * Rebuilds the elements related to this component in case of
  93653. * context lost for instance.
  93654. */
  93655. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  93656. // Nothing to do for this component
  93657. };
  93658. /**
  93659. * Disposes the component and the associated ressources
  93660. */
  93661. PhysicsEngineSceneComponent.prototype.dispose = function () {
  93662. this.scene.onBeforePhysicsObservable.clear();
  93663. this.scene.onAfterPhysicsObservable.clear();
  93664. if (this.scene._physicsEngine) {
  93665. this.scene.disablePhysicsEngine();
  93666. }
  93667. };
  93668. return PhysicsEngineSceneComponent;
  93669. }());
  93670. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  93671. })(BABYLON || (BABYLON = {}));
  93672. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  93673. var BABYLON;
  93674. (function (BABYLON) {
  93675. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  93676. // All values and structures referenced from:
  93677. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  93678. var DDS_MAGIC = 0x20534444;
  93679. var
  93680. //DDSD_CAPS = 0x1,
  93681. //DDSD_HEIGHT = 0x2,
  93682. //DDSD_WIDTH = 0x4,
  93683. //DDSD_PITCH = 0x8,
  93684. //DDSD_PIXELFORMAT = 0x1000,
  93685. DDSD_MIPMAPCOUNT = 0x20000;
  93686. //DDSD_LINEARSIZE = 0x80000,
  93687. //DDSD_DEPTH = 0x800000;
  93688. // var DDSCAPS_COMPLEX = 0x8,
  93689. // DDSCAPS_MIPMAP = 0x400000,
  93690. // DDSCAPS_TEXTURE = 0x1000;
  93691. var DDSCAPS2_CUBEMAP = 0x200;
  93692. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  93693. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  93694. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  93695. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  93696. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  93697. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  93698. // DDSCAPS2_VOLUME = 0x200000;
  93699. var
  93700. //DDPF_ALPHAPIXELS = 0x1,
  93701. //DDPF_ALPHA = 0x2,
  93702. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  93703. //DDPF_YUV = 0x200,
  93704. DDPF_LUMINANCE = 0x20000;
  93705. function FourCCToInt32(value) {
  93706. return value.charCodeAt(0) +
  93707. (value.charCodeAt(1) << 8) +
  93708. (value.charCodeAt(2) << 16) +
  93709. (value.charCodeAt(3) << 24);
  93710. }
  93711. function Int32ToFourCC(value) {
  93712. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  93713. }
  93714. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  93715. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  93716. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  93717. var FOURCC_DX10 = FourCCToInt32("DX10");
  93718. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  93719. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  93720. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  93721. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  93722. var headerLengthInt = 31; // The header length in 32 bit ints
  93723. // Offsets into the header array
  93724. var off_magic = 0;
  93725. var off_size = 1;
  93726. var off_flags = 2;
  93727. var off_height = 3;
  93728. var off_width = 4;
  93729. var off_mipmapCount = 7;
  93730. var off_pfFlags = 20;
  93731. var off_pfFourCC = 21;
  93732. var off_RGBbpp = 22;
  93733. var off_RMask = 23;
  93734. var off_GMask = 24;
  93735. var off_BMask = 25;
  93736. var off_AMask = 26;
  93737. // var off_caps1 = 27;
  93738. var off_caps2 = 28;
  93739. // var off_caps3 = 29;
  93740. // var off_caps4 = 30;
  93741. var off_dxgiFormat = 32;
  93742. ;
  93743. var DDSTools = /** @class */ (function () {
  93744. function DDSTools() {
  93745. }
  93746. DDSTools.GetDDSInfo = function (arrayBuffer) {
  93747. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93748. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  93749. var mipmapCount = 1;
  93750. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  93751. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93752. }
  93753. var fourCC = header[off_pfFourCC];
  93754. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  93755. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93756. switch (fourCC) {
  93757. case FOURCC_D3DFMT_R16G16B16A16F:
  93758. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93759. break;
  93760. case FOURCC_D3DFMT_R32G32B32A32F:
  93761. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93762. break;
  93763. case FOURCC_DX10:
  93764. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  93765. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93766. break;
  93767. }
  93768. }
  93769. return {
  93770. width: header[off_width],
  93771. height: header[off_height],
  93772. mipmapCount: mipmapCount,
  93773. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  93774. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  93775. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  93776. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  93777. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  93778. dxgiFormat: dxgiFormat,
  93779. textureType: textureType
  93780. };
  93781. };
  93782. DDSTools._ToHalfFloat = function (value) {
  93783. if (!DDSTools._FloatView) {
  93784. DDSTools._FloatView = new Float32Array(1);
  93785. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  93786. }
  93787. DDSTools._FloatView[0] = value;
  93788. var x = DDSTools._Int32View[0];
  93789. var bits = (x >> 16) & 0x8000; /* Get the sign */
  93790. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  93791. var e = (x >> 23) & 0xff; /* Using int is faster here */
  93792. /* If zero, or denormal, or exponent underflows too much for a denormal
  93793. * half, return signed zero. */
  93794. if (e < 103) {
  93795. return bits;
  93796. }
  93797. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  93798. if (e > 142) {
  93799. bits |= 0x7c00;
  93800. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  93801. * not Inf, so make sure we set one mantissa bit too. */
  93802. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  93803. return bits;
  93804. }
  93805. /* If exponent underflows but not too much, return a denormal */
  93806. if (e < 113) {
  93807. m |= 0x0800;
  93808. /* Extra rounding may overflow and set mantissa to 0 and exponent
  93809. * to 1, which is OK. */
  93810. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  93811. return bits;
  93812. }
  93813. bits |= ((e - 112) << 10) | (m >> 1);
  93814. bits += m & 1;
  93815. return bits;
  93816. };
  93817. DDSTools._FromHalfFloat = function (value) {
  93818. var s = (value & 0x8000) >> 15;
  93819. var e = (value & 0x7C00) >> 10;
  93820. var f = value & 0x03FF;
  93821. if (e === 0) {
  93822. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  93823. }
  93824. else if (e == 0x1F) {
  93825. return f ? NaN : ((s ? -1 : 1) * Infinity);
  93826. }
  93827. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  93828. };
  93829. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93830. var destArray = new Float32Array(dataLength);
  93831. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93832. var index = 0;
  93833. for (var y = 0; y < height; y++) {
  93834. for (var x = 0; x < width; x++) {
  93835. var srcPos = (x + y * width) * 4;
  93836. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  93837. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  93838. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  93839. if (DDSTools.StoreLODInAlphaChannel) {
  93840. destArray[index + 3] = lod;
  93841. }
  93842. else {
  93843. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  93844. }
  93845. index += 4;
  93846. }
  93847. }
  93848. return destArray;
  93849. };
  93850. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93851. if (DDSTools.StoreLODInAlphaChannel) {
  93852. var destArray = new Uint16Array(dataLength);
  93853. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93854. var index = 0;
  93855. for (var y = 0; y < height; y++) {
  93856. for (var x = 0; x < width; x++) {
  93857. var srcPos = (x + y * width) * 4;
  93858. destArray[index] = srcData[srcPos];
  93859. destArray[index + 1] = srcData[srcPos + 1];
  93860. destArray[index + 2] = srcData[srcPos + 2];
  93861. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  93862. index += 4;
  93863. }
  93864. }
  93865. return destArray;
  93866. }
  93867. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  93868. };
  93869. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93870. if (DDSTools.StoreLODInAlphaChannel) {
  93871. var destArray = new Float32Array(dataLength);
  93872. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93873. var index = 0;
  93874. for (var y = 0; y < height; y++) {
  93875. for (var x = 0; x < width; x++) {
  93876. var srcPos = (x + y * width) * 4;
  93877. destArray[index] = srcData[srcPos];
  93878. destArray[index + 1] = srcData[srcPos + 1];
  93879. destArray[index + 2] = srcData[srcPos + 2];
  93880. destArray[index + 3] = lod;
  93881. index += 4;
  93882. }
  93883. }
  93884. return destArray;
  93885. }
  93886. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  93887. };
  93888. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93889. var destArray = new Uint8Array(dataLength);
  93890. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93891. var index = 0;
  93892. for (var y = 0; y < height; y++) {
  93893. for (var x = 0; x < width; x++) {
  93894. var srcPos = (x + y * width) * 4;
  93895. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  93896. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  93897. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  93898. if (DDSTools.StoreLODInAlphaChannel) {
  93899. destArray[index + 3] = lod;
  93900. }
  93901. else {
  93902. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  93903. }
  93904. index += 4;
  93905. }
  93906. }
  93907. return destArray;
  93908. };
  93909. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93910. var destArray = new Uint8Array(dataLength);
  93911. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93912. var index = 0;
  93913. for (var y = 0; y < height; y++) {
  93914. for (var x = 0; x < width; x++) {
  93915. var srcPos = (x + y * width) * 4;
  93916. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  93917. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  93918. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  93919. if (DDSTools.StoreLODInAlphaChannel) {
  93920. destArray[index + 3] = lod;
  93921. }
  93922. else {
  93923. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  93924. }
  93925. index += 4;
  93926. }
  93927. }
  93928. return destArray;
  93929. };
  93930. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  93931. var byteArray = new Uint8Array(dataLength);
  93932. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93933. var index = 0;
  93934. for (var y = 0; y < height; y++) {
  93935. for (var x = 0; x < width; x++) {
  93936. var srcPos = (x + y * width) * 4;
  93937. byteArray[index] = srcData[srcPos + rOffset];
  93938. byteArray[index + 1] = srcData[srcPos + gOffset];
  93939. byteArray[index + 2] = srcData[srcPos + bOffset];
  93940. byteArray[index + 3] = srcData[srcPos + aOffset];
  93941. index += 4;
  93942. }
  93943. }
  93944. return byteArray;
  93945. };
  93946. DDSTools._ExtractLongWordOrder = function (value) {
  93947. if (value === 0 || value === 255 || value === -16777216) {
  93948. return 0;
  93949. }
  93950. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  93951. };
  93952. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  93953. var byteArray = new Uint8Array(dataLength);
  93954. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93955. var index = 0;
  93956. for (var y = 0; y < height; y++) {
  93957. for (var x = 0; x < width; x++) {
  93958. var srcPos = (x + y * width) * 3;
  93959. byteArray[index] = srcData[srcPos + rOffset];
  93960. byteArray[index + 1] = srcData[srcPos + gOffset];
  93961. byteArray[index + 2] = srcData[srcPos + bOffset];
  93962. index += 3;
  93963. }
  93964. }
  93965. return byteArray;
  93966. };
  93967. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  93968. var byteArray = new Uint8Array(dataLength);
  93969. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93970. var index = 0;
  93971. for (var y = 0; y < height; y++) {
  93972. for (var x = 0; x < width; x++) {
  93973. var srcPos = (x + y * width);
  93974. byteArray[index] = srcData[srcPos];
  93975. index++;
  93976. }
  93977. }
  93978. return byteArray;
  93979. };
  93980. /**
  93981. * Uploads DDS Levels to a Babylon Texture
  93982. * @hidden
  93983. */
  93984. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  93985. if (lodIndex === void 0) { lodIndex = -1; }
  93986. var sphericalPolynomialFaces = null;
  93987. if (info.sphericalPolynomial) {
  93988. sphericalPolynomialFaces = new Array();
  93989. }
  93990. var ext = engine.getCaps().s3tc;
  93991. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93992. var fourCC, width, height, dataLength = 0, dataOffset;
  93993. var byteArray, mipmapCount, mip;
  93994. var internalCompressedFormat = 0;
  93995. var blockBytes = 1;
  93996. if (header[off_magic] !== DDS_MAGIC) {
  93997. BABYLON.Tools.Error("Invalid magic number in DDS header");
  93998. return;
  93999. }
  94000. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  94001. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  94002. return;
  94003. }
  94004. if (info.isCompressed && !ext) {
  94005. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  94006. return;
  94007. }
  94008. var bpp = header[off_RGBbpp];
  94009. dataOffset = header[off_size] + 4;
  94010. var computeFormats = false;
  94011. if (info.isFourCC) {
  94012. fourCC = header[off_pfFourCC];
  94013. switch (fourCC) {
  94014. case FOURCC_DXT1:
  94015. blockBytes = 8;
  94016. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  94017. break;
  94018. case FOURCC_DXT3:
  94019. blockBytes = 16;
  94020. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  94021. break;
  94022. case FOURCC_DXT5:
  94023. blockBytes = 16;
  94024. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  94025. break;
  94026. case FOURCC_D3DFMT_R16G16B16A16F:
  94027. computeFormats = true;
  94028. break;
  94029. case FOURCC_D3DFMT_R32G32B32A32F:
  94030. computeFormats = true;
  94031. break;
  94032. case FOURCC_DX10:
  94033. // There is an additionnal header so dataOffset need to be changed
  94034. dataOffset += 5 * 4; // 5 uints
  94035. var supported = false;
  94036. switch (info.dxgiFormat) {
  94037. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  94038. computeFormats = true;
  94039. supported = true;
  94040. break;
  94041. case DXGI_FORMAT_B8G8R8X8_UNORM:
  94042. info.isRGB = true;
  94043. info.isFourCC = false;
  94044. bpp = 32;
  94045. supported = true;
  94046. break;
  94047. }
  94048. if (supported) {
  94049. break;
  94050. }
  94051. default:
  94052. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  94053. return;
  94054. }
  94055. }
  94056. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  94057. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  94058. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  94059. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  94060. if (computeFormats) {
  94061. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  94062. }
  94063. mipmapCount = 1;
  94064. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  94065. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94066. }
  94067. for (var face = 0; face < faces; face++) {
  94068. width = header[off_width];
  94069. height = header[off_height];
  94070. for (mip = 0; mip < mipmapCount; ++mip) {
  94071. if (lodIndex === -1 || lodIndex === mip) {
  94072. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  94073. var i = (lodIndex === -1) ? mip : 0;
  94074. if (!info.isCompressed && info.isFourCC) {
  94075. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94076. dataLength = width * height * 4;
  94077. var floatArray = null;
  94078. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  94079. if (bpp === 128) {
  94080. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94081. if (sphericalPolynomialFaces && i == 0) {
  94082. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94083. }
  94084. }
  94085. else if (bpp === 64) {
  94086. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94087. if (sphericalPolynomialFaces && i == 0) {
  94088. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94089. }
  94090. }
  94091. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94092. }
  94093. else {
  94094. if (bpp === 128) {
  94095. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94096. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94097. if (sphericalPolynomialFaces && i == 0) {
  94098. sphericalPolynomialFaces.push(floatArray);
  94099. }
  94100. }
  94101. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  94102. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94103. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94104. if (sphericalPolynomialFaces && i == 0) {
  94105. sphericalPolynomialFaces.push(floatArray);
  94106. }
  94107. }
  94108. else { // 64
  94109. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94110. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94111. if (sphericalPolynomialFaces && i == 0) {
  94112. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94113. }
  94114. }
  94115. }
  94116. if (floatArray) {
  94117. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  94118. }
  94119. }
  94120. else if (info.isRGB) {
  94121. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94122. if (bpp === 24) {
  94123. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  94124. dataLength = width * height * 3;
  94125. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  94126. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94127. }
  94128. else { // 32
  94129. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94130. dataLength = width * height * 4;
  94131. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  94132. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94133. }
  94134. }
  94135. else if (info.isLuminance) {
  94136. var unpackAlignment = engine._getUnpackAlignement();
  94137. var unpaddedRowSize = width;
  94138. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  94139. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  94140. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  94141. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  94142. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94143. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94144. }
  94145. else {
  94146. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  94147. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  94148. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94149. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  94150. }
  94151. }
  94152. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  94153. width *= 0.5;
  94154. height *= 0.5;
  94155. width = Math.max(1.0, width);
  94156. height = Math.max(1.0, height);
  94157. }
  94158. if (currentFace !== undefined) {
  94159. // Loading a single face
  94160. break;
  94161. }
  94162. }
  94163. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  94164. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  94165. size: header[off_width],
  94166. right: sphericalPolynomialFaces[0],
  94167. left: sphericalPolynomialFaces[1],
  94168. up: sphericalPolynomialFaces[2],
  94169. down: sphericalPolynomialFaces[3],
  94170. front: sphericalPolynomialFaces[4],
  94171. back: sphericalPolynomialFaces[5],
  94172. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  94173. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94174. gammaSpace: false,
  94175. });
  94176. }
  94177. else {
  94178. info.sphericalPolynomial = undefined;
  94179. }
  94180. };
  94181. DDSTools.StoreLODInAlphaChannel = false;
  94182. return DDSTools;
  94183. }());
  94184. BABYLON.DDSTools = DDSTools;
  94185. })(BABYLON || (BABYLON = {}));
  94186. //# sourceMappingURL=babylon.dds.js.map
  94187. var BABYLON;
  94188. (function (BABYLON) {
  94189. /**
  94190. * Implementation of the DDS Texture Loader.
  94191. */
  94192. var DDSTextureLoader = /** @class */ (function () {
  94193. function DDSTextureLoader() {
  94194. /**
  94195. * Defines wether the loader supports cascade loading the different faces.
  94196. */
  94197. this.supportCascades = true;
  94198. }
  94199. /**
  94200. * This returns if the loader support the current file information.
  94201. * @param extension defines the file extension of the file being loaded
  94202. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94203. * @param fallback defines the fallback internal texture if any
  94204. * @param isBase64 defines whether the texture is encoded as a base64
  94205. * @param isBuffer defines whether the texture data are stored as a buffer
  94206. * @returns true if the loader can load the specified file
  94207. */
  94208. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94209. return extension.indexOf(".dds") === 0;
  94210. };
  94211. /**
  94212. * Transform the url before loading if required.
  94213. * @param rootUrl the url of the texture
  94214. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94215. * @returns the transformed texture
  94216. */
  94217. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94218. return rootUrl;
  94219. };
  94220. /**
  94221. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94222. * @param rootUrl the url of the texture
  94223. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94224. * @returns the fallback texture
  94225. */
  94226. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94227. return null;
  94228. };
  94229. /**
  94230. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94231. * @param data contains the texture data
  94232. * @param texture defines the BabylonJS internal texture
  94233. * @param createPolynomials will be true if polynomials have been requested
  94234. * @param onLoad defines the callback to trigger once the texture is ready
  94235. * @param onError defines the callback to trigger in case of error
  94236. */
  94237. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  94238. var engine = texture.getEngine();
  94239. var info;
  94240. var loadMipmap = false;
  94241. if (Array.isArray(imgs)) {
  94242. for (var index = 0; index < imgs.length; index++) {
  94243. var data_1 = imgs[index];
  94244. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  94245. texture.width = info.width;
  94246. texture.height = info.height;
  94247. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94248. engine._unpackFlipY(info.isCompressed);
  94249. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  94250. if (!info.isFourCC && info.mipmapCount === 1) {
  94251. engine.generateMipMapsForCubemap(texture);
  94252. }
  94253. }
  94254. }
  94255. else {
  94256. var data = imgs;
  94257. info = BABYLON.DDSTools.GetDDSInfo(data);
  94258. texture.width = info.width;
  94259. texture.height = info.height;
  94260. if (createPolynomials) {
  94261. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  94262. }
  94263. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94264. engine._unpackFlipY(info.isCompressed);
  94265. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  94266. if (!info.isFourCC && info.mipmapCount === 1) {
  94267. engine.generateMipMapsForCubemap(texture);
  94268. }
  94269. }
  94270. engine._setCubeMapTextureParams(loadMipmap);
  94271. texture.isReady = true;
  94272. if (onLoad) {
  94273. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  94274. }
  94275. };
  94276. /**
  94277. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94278. * @param data contains the texture data
  94279. * @param texture defines the BabylonJS internal texture
  94280. * @param callback defines the method to call once ready to upload
  94281. */
  94282. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  94283. var info = BABYLON.DDSTools.GetDDSInfo(data);
  94284. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  94285. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  94286. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  94287. });
  94288. };
  94289. return DDSTextureLoader;
  94290. }());
  94291. // Register the loader.
  94292. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  94293. })(BABYLON || (BABYLON = {}));
  94294. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  94295. var BABYLON;
  94296. (function (BABYLON) {
  94297. /*
  94298. * Based on jsTGALoader - Javascript loader for TGA file
  94299. * By Vincent Thibault
  94300. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  94301. */
  94302. var TGATools = /** @class */ (function () {
  94303. function TGATools() {
  94304. }
  94305. TGATools.GetTGAHeader = function (data) {
  94306. var offset = 0;
  94307. var header = {
  94308. id_length: data[offset++],
  94309. colormap_type: data[offset++],
  94310. image_type: data[offset++],
  94311. colormap_index: data[offset++] | data[offset++] << 8,
  94312. colormap_length: data[offset++] | data[offset++] << 8,
  94313. colormap_size: data[offset++],
  94314. origin: [
  94315. data[offset++] | data[offset++] << 8,
  94316. data[offset++] | data[offset++] << 8
  94317. ],
  94318. width: data[offset++] | data[offset++] << 8,
  94319. height: data[offset++] | data[offset++] << 8,
  94320. pixel_size: data[offset++],
  94321. flags: data[offset++]
  94322. };
  94323. return header;
  94324. };
  94325. /**
  94326. * Uploads TGA content to a Babylon Texture
  94327. * @hidden
  94328. */
  94329. TGATools.UploadContent = function (texture, data) {
  94330. // Not enough data to contain header ?
  94331. if (data.length < 19) {
  94332. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  94333. return;
  94334. }
  94335. // Read Header
  94336. var offset = 18;
  94337. var header = TGATools.GetTGAHeader(data);
  94338. // Assume it's a valid Targa file.
  94339. if (header.id_length + offset > data.length) {
  94340. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  94341. return;
  94342. }
  94343. // Skip not needed data
  94344. offset += header.id_length;
  94345. var use_rle = false;
  94346. var use_pal = false;
  94347. var use_grey = false;
  94348. // Get some informations.
  94349. switch (header.image_type) {
  94350. case TGATools._TYPE_RLE_INDEXED:
  94351. use_rle = true;
  94352. case TGATools._TYPE_INDEXED:
  94353. use_pal = true;
  94354. break;
  94355. case TGATools._TYPE_RLE_RGB:
  94356. use_rle = true;
  94357. case TGATools._TYPE_RGB:
  94358. // use_rgb = true;
  94359. break;
  94360. case TGATools._TYPE_RLE_GREY:
  94361. use_rle = true;
  94362. case TGATools._TYPE_GREY:
  94363. use_grey = true;
  94364. break;
  94365. }
  94366. var pixel_data;
  94367. // var numAlphaBits = header.flags & 0xf;
  94368. var pixel_size = header.pixel_size >> 3;
  94369. var pixel_total = header.width * header.height * pixel_size;
  94370. // Read palettes
  94371. var palettes;
  94372. if (use_pal) {
  94373. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  94374. }
  94375. // Read LRE
  94376. if (use_rle) {
  94377. pixel_data = new Uint8Array(pixel_total);
  94378. var c, count, i;
  94379. var localOffset = 0;
  94380. var pixels = new Uint8Array(pixel_size);
  94381. while (offset < pixel_total && localOffset < pixel_total) {
  94382. c = data[offset++];
  94383. count = (c & 0x7f) + 1;
  94384. // RLE pixels
  94385. if (c & 0x80) {
  94386. // Bind pixel tmp array
  94387. for (i = 0; i < pixel_size; ++i) {
  94388. pixels[i] = data[offset++];
  94389. }
  94390. // Copy pixel array
  94391. for (i = 0; i < count; ++i) {
  94392. pixel_data.set(pixels, localOffset + i * pixel_size);
  94393. }
  94394. localOffset += pixel_size * count;
  94395. }
  94396. // Raw pixels
  94397. else {
  94398. count *= pixel_size;
  94399. for (i = 0; i < count; ++i) {
  94400. pixel_data[localOffset + i] = data[offset++];
  94401. }
  94402. localOffset += count;
  94403. }
  94404. }
  94405. }
  94406. // RAW Pixels
  94407. else {
  94408. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  94409. }
  94410. // Load to texture
  94411. var x_start, y_start, x_step, y_step, y_end, x_end;
  94412. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  94413. default:
  94414. case TGATools._ORIGIN_UL:
  94415. x_start = 0;
  94416. x_step = 1;
  94417. x_end = header.width;
  94418. y_start = 0;
  94419. y_step = 1;
  94420. y_end = header.height;
  94421. break;
  94422. case TGATools._ORIGIN_BL:
  94423. x_start = 0;
  94424. x_step = 1;
  94425. x_end = header.width;
  94426. y_start = header.height - 1;
  94427. y_step = -1;
  94428. y_end = -1;
  94429. break;
  94430. case TGATools._ORIGIN_UR:
  94431. x_start = header.width - 1;
  94432. x_step = -1;
  94433. x_end = -1;
  94434. y_start = 0;
  94435. y_step = 1;
  94436. y_end = header.height;
  94437. break;
  94438. case TGATools._ORIGIN_BR:
  94439. x_start = header.width - 1;
  94440. x_step = -1;
  94441. x_end = -1;
  94442. y_start = header.height - 1;
  94443. y_step = -1;
  94444. y_end = -1;
  94445. break;
  94446. }
  94447. // Load the specify method
  94448. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  94449. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  94450. var engine = texture.getEngine();
  94451. engine._uploadDataToTextureDirectly(texture, imageData);
  94452. };
  94453. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94454. var image = pixel_data, colormap = palettes;
  94455. var width = header.width, height = header.height;
  94456. var color, i = 0, x, y;
  94457. var imageData = new Uint8Array(width * height * 4);
  94458. for (y = y_start; y !== y_end; y += y_step) {
  94459. for (x = x_start; x !== x_end; x += x_step, i++) {
  94460. color = image[i];
  94461. imageData[(x + width * y) * 4 + 3] = 255;
  94462. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  94463. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  94464. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  94465. }
  94466. }
  94467. return imageData;
  94468. };
  94469. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94470. var image = pixel_data;
  94471. var width = header.width, height = header.height;
  94472. var color, i = 0, x, y;
  94473. var imageData = new Uint8Array(width * height * 4);
  94474. for (y = y_start; y !== y_end; y += y_step) {
  94475. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94476. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  94477. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  94478. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  94479. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  94480. imageData[(x + width * y) * 4 + 0] = r;
  94481. imageData[(x + width * y) * 4 + 1] = g;
  94482. imageData[(x + width * y) * 4 + 2] = b;
  94483. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  94484. }
  94485. }
  94486. return imageData;
  94487. };
  94488. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94489. var image = pixel_data;
  94490. var width = header.width, height = header.height;
  94491. var i = 0, x, y;
  94492. var imageData = new Uint8Array(width * height * 4);
  94493. for (y = y_start; y !== y_end; y += y_step) {
  94494. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  94495. imageData[(x + width * y) * 4 + 3] = 255;
  94496. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94497. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94498. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94499. }
  94500. }
  94501. return imageData;
  94502. };
  94503. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94504. var image = pixel_data;
  94505. var width = header.width, height = header.height;
  94506. var i = 0, x, y;
  94507. var imageData = new Uint8Array(width * height * 4);
  94508. for (y = y_start; y !== y_end; y += y_step) {
  94509. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  94510. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94511. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94512. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94513. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  94514. }
  94515. }
  94516. return imageData;
  94517. };
  94518. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94519. var image = pixel_data;
  94520. var width = header.width, height = header.height;
  94521. var color, i = 0, x, y;
  94522. var imageData = new Uint8Array(width * height * 4);
  94523. for (y = y_start; y !== y_end; y += y_step) {
  94524. for (x = x_start; x !== x_end; x += x_step, i++) {
  94525. color = image[i];
  94526. imageData[(x + width * y) * 4 + 0] = color;
  94527. imageData[(x + width * y) * 4 + 1] = color;
  94528. imageData[(x + width * y) * 4 + 2] = color;
  94529. imageData[(x + width * y) * 4 + 3] = 255;
  94530. }
  94531. }
  94532. return imageData;
  94533. };
  94534. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94535. var image = pixel_data;
  94536. var width = header.width, height = header.height;
  94537. var i = 0, x, y;
  94538. var imageData = new Uint8Array(width * height * 4);
  94539. for (y = y_start; y !== y_end; y += y_step) {
  94540. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94541. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  94542. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  94543. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94544. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  94545. }
  94546. }
  94547. return imageData;
  94548. };
  94549. //private static _TYPE_NO_DATA = 0;
  94550. TGATools._TYPE_INDEXED = 1;
  94551. TGATools._TYPE_RGB = 2;
  94552. TGATools._TYPE_GREY = 3;
  94553. TGATools._TYPE_RLE_INDEXED = 9;
  94554. TGATools._TYPE_RLE_RGB = 10;
  94555. TGATools._TYPE_RLE_GREY = 11;
  94556. TGATools._ORIGIN_MASK = 0x30;
  94557. TGATools._ORIGIN_SHIFT = 0x04;
  94558. TGATools._ORIGIN_BL = 0x00;
  94559. TGATools._ORIGIN_BR = 0x01;
  94560. TGATools._ORIGIN_UL = 0x02;
  94561. TGATools._ORIGIN_UR = 0x03;
  94562. return TGATools;
  94563. }());
  94564. BABYLON.TGATools = TGATools;
  94565. })(BABYLON || (BABYLON = {}));
  94566. //# sourceMappingURL=babylon.tga.js.map
  94567. var BABYLON;
  94568. (function (BABYLON) {
  94569. /**
  94570. * Implementation of the TGA Texture Loader.
  94571. */
  94572. var TGATextureLoader = /** @class */ (function () {
  94573. function TGATextureLoader() {
  94574. /**
  94575. * Defines wether the loader supports cascade loading the different faces.
  94576. */
  94577. this.supportCascades = false;
  94578. }
  94579. /**
  94580. * This returns if the loader support the current file information.
  94581. * @param extension defines the file extension of the file being loaded
  94582. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94583. * @param fallback defines the fallback internal texture if any
  94584. * @param isBase64 defines whether the texture is encoded as a base64
  94585. * @param isBuffer defines whether the texture data are stored as a buffer
  94586. * @returns true if the loader can load the specified file
  94587. */
  94588. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94589. return extension.indexOf(".tga") === 0;
  94590. };
  94591. /**
  94592. * Transform the url before loading if required.
  94593. * @param rootUrl the url of the texture
  94594. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94595. * @returns the transformed texture
  94596. */
  94597. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94598. return rootUrl;
  94599. };
  94600. /**
  94601. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94602. * @param rootUrl the url of the texture
  94603. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94604. * @returns the fallback texture
  94605. */
  94606. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94607. return null;
  94608. };
  94609. /**
  94610. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94611. * @param data contains the texture data
  94612. * @param texture defines the BabylonJS internal texture
  94613. * @param createPolynomials will be true if polynomials have been requested
  94614. * @param onLoad defines the callback to trigger once the texture is ready
  94615. * @param onError defines the callback to trigger in case of error
  94616. */
  94617. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94618. throw ".env not supported in Cube.";
  94619. };
  94620. /**
  94621. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94622. * @param data contains the texture data
  94623. * @param texture defines the BabylonJS internal texture
  94624. * @param callback defines the method to call once ready to upload
  94625. */
  94626. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  94627. var uintData = new Uint8Array(data);
  94628. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  94629. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  94630. BABYLON.TGATools.UploadContent(texture, uintData);
  94631. });
  94632. };
  94633. return TGATextureLoader;
  94634. }());
  94635. // Register the loader.
  94636. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  94637. })(BABYLON || (BABYLON = {}));
  94638. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  94639. var BABYLON;
  94640. (function (BABYLON) {
  94641. /**
  94642. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  94643. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  94644. */
  94645. var KhronosTextureContainer = /** @class */ (function () {
  94646. /**
  94647. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  94648. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  94649. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  94650. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  94651. */
  94652. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  94653. this.arrayBuffer = arrayBuffer;
  94654. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  94655. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  94656. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  94657. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  94658. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  94659. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  94660. BABYLON.Tools.Error("texture missing KTX identifier");
  94661. return;
  94662. }
  94663. // load the reset of the header in native 32 bit int
  94664. var header = new Int32Array(this.arrayBuffer, 12, 13);
  94665. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  94666. var oppositeEndianess = header[0] === 0x01020304;
  94667. // read all the header elements in order they exist in the file, without modification (sans endainness)
  94668. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  94669. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  94670. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  94671. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  94672. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  94673. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  94674. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  94675. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  94676. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  94677. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  94678. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  94679. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  94680. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  94681. if (this.glType !== 0) {
  94682. BABYLON.Tools.Error("only compressed formats currently supported");
  94683. return;
  94684. }
  94685. else {
  94686. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  94687. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  94688. }
  94689. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  94690. BABYLON.Tools.Error("only 2D textures currently supported");
  94691. return;
  94692. }
  94693. if (this.numberOfArrayElements !== 0) {
  94694. BABYLON.Tools.Error("texture arrays not currently supported");
  94695. return;
  94696. }
  94697. if (this.numberOfFaces !== facesExpected) {
  94698. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  94699. return;
  94700. }
  94701. // we now have a completely validated file, so could use existence of loadType as success
  94702. // would need to make this more elaborate & adjust checks above to support more than one load type
  94703. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  94704. }
  94705. // not as fast hardware based, but will probably never need to use
  94706. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  94707. return ((val & 0xFF) << 24)
  94708. | ((val & 0xFF00) << 8)
  94709. | ((val >> 8) & 0xFF00)
  94710. | ((val >> 24) & 0xFF);
  94711. };
  94712. /**
  94713. * Uploads KTX content to a Babylon Texture.
  94714. * It is assumed that the texture has already been created & is currently bound
  94715. * @hidden
  94716. */
  94717. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  94718. switch (this.loadType) {
  94719. case KhronosTextureContainer.COMPRESSED_2D:
  94720. this._upload2DCompressedLevels(texture, loadMipmaps);
  94721. break;
  94722. case KhronosTextureContainer.TEX_2D:
  94723. case KhronosTextureContainer.COMPRESSED_3D:
  94724. case KhronosTextureContainer.TEX_3D:
  94725. }
  94726. };
  94727. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  94728. // initialize width & height for level 1
  94729. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  94730. var width = this.pixelWidth;
  94731. var height = this.pixelHeight;
  94732. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  94733. for (var level = 0; level < mipmapCount; level++) {
  94734. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  94735. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  94736. for (var face = 0; face < this.numberOfFaces; face++) {
  94737. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  94738. var engine = texture.getEngine();
  94739. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  94740. dataOffset += imageSize; // add size of the image for the next face/mipmap
  94741. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  94742. }
  94743. width = Math.max(1.0, width * 0.5);
  94744. height = Math.max(1.0, height * 0.5);
  94745. }
  94746. };
  94747. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  94748. // load types
  94749. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  94750. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  94751. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  94752. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  94753. return KhronosTextureContainer;
  94754. }());
  94755. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  94756. })(BABYLON || (BABYLON = {}));
  94757. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  94758. var BABYLON;
  94759. (function (BABYLON) {
  94760. /**
  94761. * Implementation of the KTX Texture Loader.
  94762. */
  94763. var KTXTextureLoader = /** @class */ (function () {
  94764. function KTXTextureLoader() {
  94765. /**
  94766. * Defines wether the loader supports cascade loading the different faces.
  94767. */
  94768. this.supportCascades = false;
  94769. }
  94770. /**
  94771. * This returns if the loader support the current file information.
  94772. * @param extension defines the file extension of the file being loaded
  94773. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94774. * @param fallback defines the fallback internal texture if any
  94775. * @param isBase64 defines whether the texture is encoded as a base64
  94776. * @param isBuffer defines whether the texture data are stored as a buffer
  94777. * @returns true if the loader can load the specified file
  94778. */
  94779. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94780. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  94781. return true;
  94782. }
  94783. return false;
  94784. };
  94785. /**
  94786. * Transform the url before loading if required.
  94787. * @param rootUrl the url of the texture
  94788. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94789. * @returns the transformed texture
  94790. */
  94791. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94792. var lastDot = rootUrl.lastIndexOf('.');
  94793. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  94794. };
  94795. /**
  94796. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94797. * @param rootUrl the url of the texture
  94798. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94799. * @returns the fallback texture
  94800. */
  94801. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94802. // remove the format appended to the rootUrl in the original createCubeTexture call.
  94803. var exp = new RegExp("" + textureFormatInUse + "$");
  94804. return rootUrl.replace(exp, "");
  94805. };
  94806. /**
  94807. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94808. * @param data contains the texture data
  94809. * @param texture defines the BabylonJS internal texture
  94810. * @param createPolynomials will be true if polynomials have been requested
  94811. * @param onLoad defines the callback to trigger once the texture is ready
  94812. * @param onError defines the callback to trigger in case of error
  94813. */
  94814. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94815. if (Array.isArray(data)) {
  94816. return;
  94817. }
  94818. var engine = texture.getEngine();
  94819. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  94820. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  94821. engine._unpackFlipY(true);
  94822. ktx.uploadLevels(texture, texture.generateMipMaps);
  94823. texture.width = ktx.pixelWidth;
  94824. texture.height = ktx.pixelHeight;
  94825. engine._setCubeMapTextureParams(loadMipmap);
  94826. texture.isReady = true;
  94827. };
  94828. /**
  94829. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94830. * @param data contains the texture data
  94831. * @param texture defines the BabylonJS internal texture
  94832. * @param callback defines the method to call once ready to upload
  94833. */
  94834. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  94835. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  94836. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  94837. ktx.uploadLevels(texture, texture.generateMipMaps);
  94838. });
  94839. };
  94840. return KTXTextureLoader;
  94841. }());
  94842. // Register the loader.
  94843. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  94844. })(BABYLON || (BABYLON = {}));
  94845. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  94846. var BABYLON;
  94847. (function (BABYLON) {
  94848. /**
  94849. * Sets of helpers addressing the serialization and deserialization of environment texture
  94850. * stored in a BabylonJS env file.
  94851. * Those files are usually stored as .env files.
  94852. */
  94853. var EnvironmentTextureTools = /** @class */ (function () {
  94854. function EnvironmentTextureTools() {
  94855. }
  94856. /**
  94857. * Gets the environment info from an env file.
  94858. * @param data The array buffer containing the .env bytes.
  94859. * @returns the environment file info (the json header) if successfully parsed.
  94860. */
  94861. EnvironmentTextureTools.GetEnvInfo = function (data) {
  94862. var dataView = new DataView(data);
  94863. var pos = 0;
  94864. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94865. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  94866. BABYLON.Tools.Error('Not a babylon environment map');
  94867. return null;
  94868. }
  94869. }
  94870. // Read json manifest - collect characters up to null terminator
  94871. var manifestString = '';
  94872. var charCode = 0x00;
  94873. while ((charCode = dataView.getUint8(pos++))) {
  94874. manifestString += String.fromCharCode(charCode);
  94875. }
  94876. var manifest = JSON.parse(manifestString);
  94877. if (manifest.specular) {
  94878. // Extend the header with the position of the payload.
  94879. manifest.specular.specularDataPosition = pos;
  94880. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  94881. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  94882. }
  94883. return manifest;
  94884. };
  94885. /**
  94886. * Creates an environment texture from a loaded cube texture.
  94887. * @param texture defines the cube texture to convert in env file
  94888. * @return a promise containing the environment data if succesfull.
  94889. */
  94890. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  94891. var _this = this;
  94892. var internalTexture = texture.getInternalTexture();
  94893. if (!internalTexture) {
  94894. return Promise.reject("The cube texture is invalid.");
  94895. }
  94896. if (!texture._prefiltered) {
  94897. return Promise.reject("The cube texture is invalid (not prefiltered).");
  94898. }
  94899. var engine = internalTexture.getEngine();
  94900. if (engine && engine.premultipliedAlpha) {
  94901. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  94902. }
  94903. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  94904. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  94905. }
  94906. var canvas = engine.getRenderingCanvas();
  94907. if (!canvas) {
  94908. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  94909. }
  94910. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94911. if (!engine.getCaps().textureFloatRender) {
  94912. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94913. if (!engine.getCaps().textureHalfFloatRender) {
  94914. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  94915. }
  94916. }
  94917. var cubeWidth = internalTexture.width;
  94918. var hostingScene = new BABYLON.Scene(engine);
  94919. var specularTextures = {};
  94920. var promises = [];
  94921. // Read and collect all mipmaps data from the cube.
  94922. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  94923. mipmapsCount = Math.round(mipmapsCount);
  94924. var _loop_1 = function (i) {
  94925. var faceWidth = Math.pow(2, mipmapsCount - i);
  94926. var _loop_2 = function (face) {
  94927. var data = texture.readPixels(face, i);
  94928. // Creates a temp texture with the face data.
  94929. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  94930. // And rgbdEncode them.
  94931. var promise = new Promise(function (resolve, reject) {
  94932. 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);
  94933. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94934. rgbdPostProcess.onApply = function (effect) {
  94935. effect._bindTexture("textureSampler", tempTexture);
  94936. };
  94937. // As the process needs to happen on the main canvas, keep track of the current size
  94938. var currentW = engine.getRenderWidth();
  94939. var currentH = engine.getRenderHeight();
  94940. // Set the desired size for the texture
  94941. engine.setSize(faceWidth, faceWidth);
  94942. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  94943. // Reading datas from WebGL
  94944. BABYLON.Tools.ToBlob(canvas, function (blob) {
  94945. var fileReader = new FileReader();
  94946. fileReader.onload = function (event) {
  94947. var arrayBuffer = event.target.result;
  94948. specularTextures[i * 6 + face] = arrayBuffer;
  94949. resolve();
  94950. };
  94951. fileReader.readAsArrayBuffer(blob);
  94952. });
  94953. // Reapply the previous canvas size
  94954. engine.setSize(currentW, currentH);
  94955. });
  94956. });
  94957. promises.push(promise);
  94958. };
  94959. // All faces of the cube.
  94960. for (var face = 0; face < 6; face++) {
  94961. _loop_2(face);
  94962. }
  94963. };
  94964. for (var i = 0; i <= mipmapsCount; i++) {
  94965. _loop_1(i);
  94966. }
  94967. // Once all the textures haves been collected as RGBD stored in PNGs
  94968. return Promise.all(promises).then(function () {
  94969. // We can delete the hosting scene keeping track of all the creation objects
  94970. hostingScene.dispose();
  94971. // Creates the json header for the env texture
  94972. var info = {
  94973. version: 1,
  94974. width: cubeWidth,
  94975. irradiance: _this._CreateEnvTextureIrradiance(texture),
  94976. specular: {
  94977. mipmaps: [],
  94978. lodGenerationScale: texture.lodGenerationScale
  94979. }
  94980. };
  94981. // Sets the specular image data information
  94982. var position = 0;
  94983. for (var i = 0; i <= mipmapsCount; i++) {
  94984. for (var face = 0; face < 6; face++) {
  94985. var byteLength = specularTextures[i * 6 + face].byteLength;
  94986. info.specular.mipmaps.push({
  94987. length: byteLength,
  94988. position: position
  94989. });
  94990. position += byteLength;
  94991. }
  94992. }
  94993. // Encode the JSON as an array buffer
  94994. var infoString = JSON.stringify(info);
  94995. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  94996. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  94997. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  94998. infoView[i] = infoString.charCodeAt(i);
  94999. }
  95000. // Ends up with a null terminator for easier parsing
  95001. infoView[infoString.length] = 0x00;
  95002. // Computes the final required size and creates the storage
  95003. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  95004. var finalBuffer = new ArrayBuffer(totalSize);
  95005. var finalBufferView = new Uint8Array(finalBuffer);
  95006. var dataView = new DataView(finalBuffer);
  95007. // Copy the magic bytes identifying the file in
  95008. var pos = 0;
  95009. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  95010. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  95011. }
  95012. // Add the json info
  95013. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  95014. pos += infoBuffer.byteLength;
  95015. // Finally inserts the texture data
  95016. for (var i = 0; i <= mipmapsCount; i++) {
  95017. for (var face = 0; face < 6; face++) {
  95018. var dataBuffer = specularTextures[i * 6 + face];
  95019. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  95020. pos += dataBuffer.byteLength;
  95021. }
  95022. }
  95023. // Voila
  95024. return finalBuffer;
  95025. });
  95026. };
  95027. /**
  95028. * Creates a JSON representation of the spherical data.
  95029. * @param texture defines the texture containing the polynomials
  95030. * @return the JSON representation of the spherical info
  95031. */
  95032. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  95033. var polynmials = texture.sphericalPolynomial;
  95034. if (polynmials == null) {
  95035. return null;
  95036. }
  95037. return {
  95038. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  95039. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  95040. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  95041. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  95042. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  95043. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  95044. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  95045. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  95046. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  95047. };
  95048. };
  95049. /**
  95050. * Uploads the texture info contained in the env file to the GPU.
  95051. * @param texture defines the internal texture to upload to
  95052. * @param arrayBuffer defines the buffer cotaining the data to load
  95053. * @param info defines the texture info retrieved through the GetEnvInfo method
  95054. * @returns a promise
  95055. */
  95056. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  95057. if (info.version !== 1) {
  95058. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  95059. }
  95060. var specularInfo = info.specular;
  95061. if (!specularInfo) {
  95062. // Nothing else parsed so far
  95063. return Promise.resolve();
  95064. }
  95065. // Double checks the enclosed info
  95066. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  95067. mipmapsCount = Math.round(mipmapsCount) + 1;
  95068. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  95069. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  95070. }
  95071. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  95072. var imageData = new Array(mipmapsCount);
  95073. for (var i = 0; i < mipmapsCount; i++) {
  95074. imageData[i] = new Array(6);
  95075. for (var face = 0; face < 6; face++) {
  95076. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  95077. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  95078. }
  95079. }
  95080. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  95081. };
  95082. /**
  95083. * Uploads the levels of image data to the GPU.
  95084. * @param texture defines the internal texture to upload to
  95085. * @param imageData defines the array buffer views of image data [mipmap][face]
  95086. * @returns a promise
  95087. */
  95088. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  95089. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  95090. throw new Error("Texture size must be a power of two");
  95091. }
  95092. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  95093. // Gets everything ready.
  95094. var engine = texture.getEngine();
  95095. var expandTexture = false;
  95096. var generateNonLODTextures = false;
  95097. var rgbdPostProcess = null;
  95098. var cubeRtt = null;
  95099. var lodTextures = null;
  95100. var caps = engine.getCaps();
  95101. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95102. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95103. texture.generateMipMaps = true;
  95104. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  95105. // Add extra process if texture lod is not supported
  95106. if (!caps.textureLOD) {
  95107. expandTexture = false;
  95108. generateNonLODTextures = true;
  95109. lodTextures = {};
  95110. }
  95111. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  95112. else if (engine.webGLVersion < 2) {
  95113. expandTexture = false;
  95114. }
  95115. // If half float available we can uncompress the texture
  95116. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  95117. expandTexture = true;
  95118. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95119. }
  95120. // If full float available we can uncompress the texture
  95121. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  95122. expandTexture = true;
  95123. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95124. }
  95125. // Expand the texture if possible
  95126. if (expandTexture) {
  95127. // Simply run through the decode PP
  95128. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  95129. texture._isRGBD = false;
  95130. texture.invertY = false;
  95131. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  95132. generateDepthBuffer: false,
  95133. generateMipMaps: true,
  95134. generateStencilBuffer: false,
  95135. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  95136. type: texture.type,
  95137. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  95138. });
  95139. }
  95140. else {
  95141. texture._isRGBD = true;
  95142. texture.invertY = true;
  95143. // In case of missing support, applies the same patch than DDS files.
  95144. if (generateNonLODTextures) {
  95145. var mipSlices = 3;
  95146. var scale = texture._lodGenerationScale;
  95147. var offset = texture._lodGenerationOffset;
  95148. for (var i = 0; i < mipSlices; i++) {
  95149. //compute LOD from even spacing in smoothness (matching shader calculation)
  95150. var smoothness = i / (mipSlices - 1);
  95151. var roughness = 1 - smoothness;
  95152. var minLODIndex = offset; // roughness = 0
  95153. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  95154. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  95155. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  95156. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  95157. glTextureFromLod.isCube = true;
  95158. glTextureFromLod.invertY = true;
  95159. glTextureFromLod.generateMipMaps = false;
  95160. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  95161. // Wrap in a base texture for easy binding.
  95162. var lodTexture = new BABYLON.BaseTexture(null);
  95163. lodTexture.isCube = true;
  95164. lodTexture._texture = glTextureFromLod;
  95165. lodTextures[mipmapIndex] = lodTexture;
  95166. switch (i) {
  95167. case 0:
  95168. texture._lodTextureLow = lodTexture;
  95169. break;
  95170. case 1:
  95171. texture._lodTextureMid = lodTexture;
  95172. break;
  95173. case 2:
  95174. texture._lodTextureHigh = lodTexture;
  95175. break;
  95176. }
  95177. }
  95178. }
  95179. }
  95180. var promises = [];
  95181. var _loop_3 = function (i) {
  95182. var _loop_4 = function (face) {
  95183. // Constructs an image element from image data
  95184. var bytes = imageData[i][face];
  95185. var blob = new Blob([bytes], { type: 'image/png' });
  95186. var url = URL.createObjectURL(blob);
  95187. var image = new Image();
  95188. image.src = url;
  95189. // Enqueue promise to upload to the texture.
  95190. var promise = new Promise(function (resolve, reject) {
  95191. image.onload = function () {
  95192. if (expandTexture) {
  95193. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  95194. reject(message);
  95195. }, image);
  95196. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95197. // Uncompress the data to a RTT
  95198. rgbdPostProcess.onApply = function (effect) {
  95199. effect._bindTexture("textureSampler", tempTexture_1);
  95200. effect.setFloat2("scale", 1, 1);
  95201. };
  95202. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  95203. // Cleanup
  95204. engine.restoreDefaultFramebuffer();
  95205. tempTexture_1.dispose();
  95206. window.URL.revokeObjectURL(url);
  95207. resolve();
  95208. });
  95209. }
  95210. else {
  95211. engine._uploadImageToTexture(texture, image, face, i);
  95212. // Upload the face to the non lod texture support
  95213. if (generateNonLODTextures) {
  95214. var lodTexture = lodTextures[i];
  95215. if (lodTexture) {
  95216. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  95217. }
  95218. }
  95219. resolve();
  95220. }
  95221. };
  95222. image.onerror = function (error) {
  95223. reject(error);
  95224. };
  95225. });
  95226. promises.push(promise);
  95227. };
  95228. // All faces
  95229. for (var face = 0; face < 6; face++) {
  95230. _loop_4(face);
  95231. }
  95232. };
  95233. // All mipmaps up to provided number of images
  95234. for (var i = 0; i < imageData.length; i++) {
  95235. _loop_3(i);
  95236. }
  95237. // Fill remaining mipmaps with black textures.
  95238. if (imageData.length < mipmapsCount) {
  95239. var data = void 0;
  95240. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  95241. var dataLength = size * size * 4;
  95242. switch (texture.type) {
  95243. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  95244. data = new Uint8Array(dataLength);
  95245. break;
  95246. }
  95247. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  95248. data = new Uint16Array(dataLength);
  95249. break;
  95250. }
  95251. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  95252. data = new Float32Array(dataLength);
  95253. break;
  95254. }
  95255. }
  95256. for (var i = imageData.length; i < mipmapsCount; i++) {
  95257. for (var face = 0; face < 6; face++) {
  95258. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  95259. }
  95260. }
  95261. }
  95262. // Once all done, finishes the cleanup and return
  95263. return Promise.all(promises).then(function () {
  95264. // Release temp RTT.
  95265. if (cubeRtt) {
  95266. engine._releaseFramebufferObjects(cubeRtt);
  95267. cubeRtt._swapAndDie(texture);
  95268. }
  95269. // Release temp Post Process.
  95270. if (rgbdPostProcess) {
  95271. rgbdPostProcess.dispose();
  95272. }
  95273. // Flag internal texture as ready in case they are in use.
  95274. if (generateNonLODTextures) {
  95275. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  95276. texture._lodTextureHigh._texture.isReady = true;
  95277. }
  95278. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  95279. texture._lodTextureMid._texture.isReady = true;
  95280. }
  95281. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  95282. texture._lodTextureLow._texture.isReady = true;
  95283. }
  95284. }
  95285. });
  95286. };
  95287. /**
  95288. * Uploads spherical polynomials information to the texture.
  95289. * @param texture defines the texture we are trying to upload the information to
  95290. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  95291. */
  95292. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  95293. if (info.version !== 1) {
  95294. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  95295. }
  95296. var irradianceInfo = info.irradiance;
  95297. if (!irradianceInfo) {
  95298. return;
  95299. }
  95300. var sp = new BABYLON.SphericalPolynomial();
  95301. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  95302. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  95303. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  95304. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  95305. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  95306. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  95307. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  95308. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  95309. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  95310. texture._sphericalPolynomial = sp;
  95311. };
  95312. /**
  95313. * Magic number identifying the env file.
  95314. */
  95315. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  95316. return EnvironmentTextureTools;
  95317. }());
  95318. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  95319. })(BABYLON || (BABYLON = {}));
  95320. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  95321. var BABYLON;
  95322. (function (BABYLON) {
  95323. /**
  95324. * Implementation of the ENV Texture Loader.
  95325. */
  95326. var ENVTextureLoader = /** @class */ (function () {
  95327. function ENVTextureLoader() {
  95328. /**
  95329. * Defines wether the loader supports cascade loading the different faces.
  95330. */
  95331. this.supportCascades = false;
  95332. }
  95333. /**
  95334. * This returns if the loader support the current file information.
  95335. * @param extension defines the file extension of the file being loaded
  95336. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95337. * @param fallback defines the fallback internal texture if any
  95338. * @param isBase64 defines whether the texture is encoded as a base64
  95339. * @param isBuffer defines whether the texture data are stored as a buffer
  95340. * @returns true if the loader can load the specified file
  95341. */
  95342. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95343. return extension.indexOf(".env") === 0;
  95344. };
  95345. /**
  95346. * Transform the url before loading if required.
  95347. * @param rootUrl the url of the texture
  95348. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95349. * @returns the transformed texture
  95350. */
  95351. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95352. return rootUrl;
  95353. };
  95354. /**
  95355. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95356. * @param rootUrl the url of the texture
  95357. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95358. * @returns the fallback texture
  95359. */
  95360. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95361. return null;
  95362. };
  95363. /**
  95364. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95365. * @param data contains the texture data
  95366. * @param texture defines the BabylonJS internal texture
  95367. * @param createPolynomials will be true if polynomials have been requested
  95368. * @param onLoad defines the callback to trigger once the texture is ready
  95369. * @param onError defines the callback to trigger in case of error
  95370. */
  95371. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95372. if (Array.isArray(data)) {
  95373. return;
  95374. }
  95375. data = data;
  95376. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  95377. if (info) {
  95378. texture.width = info.width;
  95379. texture.height = info.width;
  95380. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  95381. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  95382. texture.isReady = true;
  95383. if (onLoad) {
  95384. onLoad();
  95385. }
  95386. });
  95387. }
  95388. else if (onError) {
  95389. onError("Can not parse the environment file", null);
  95390. }
  95391. };
  95392. /**
  95393. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95394. * @param data contains the texture data
  95395. * @param texture defines the BabylonJS internal texture
  95396. * @param callback defines the method to call once ready to upload
  95397. */
  95398. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  95399. throw ".env not supported in 2d.";
  95400. };
  95401. return ENVTextureLoader;
  95402. }());
  95403. // Register the loader.
  95404. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  95405. })(BABYLON || (BABYLON = {}));
  95406. //# sourceMappingURL=babylon.envTextureLoader.js.map
  95407. var BABYLON;
  95408. (function (BABYLON) {
  95409. /**
  95410. * Renders a layer on top of an existing scene
  95411. */
  95412. var UtilityLayerRenderer = /** @class */ (function () {
  95413. /**
  95414. * Instantiates a UtilityLayerRenderer
  95415. * @param originalScene the original scene that will be rendered on top of
  95416. */
  95417. function UtilityLayerRenderer(
  95418. /** the original scene that will be rendered on top of */
  95419. originalScene) {
  95420. var _this = this;
  95421. this.originalScene = originalScene;
  95422. this._pointerCaptures = {};
  95423. this._lastPointerEvents = {};
  95424. /**
  95425. * If the utility layer should automatically be rendered on top of existing scene
  95426. */
  95427. this.shouldRender = true;
  95428. /**
  95429. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  95430. */
  95431. this.onlyCheckPointerDownEvents = true;
  95432. /**
  95433. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  95434. */
  95435. this.processAllEvents = false;
  95436. /**
  95437. * Observable raised when the pointer move from the utility layer scene to the main scene
  95438. */
  95439. this.onPointerOutObservable = new BABYLON.Observable();
  95440. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  95441. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  95442. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  95443. this.utilityLayerScene._allowPostProcessClearColor = false;
  95444. originalScene.getEngine().scenes.pop();
  95445. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  95446. this.utilityLayerScene.detachControl();
  95447. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  95448. if (!_this.processAllEvents) {
  95449. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  95450. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  95451. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  95452. return;
  95453. }
  95454. }
  95455. var pointerEvent = (prePointerInfo.event);
  95456. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  95457. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95458. return;
  95459. }
  95460. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  95461. if (!prePointerInfo.ray && utilityScenePick) {
  95462. prePointerInfo.ray = utilityScenePick.ray;
  95463. }
  95464. // always fire the prepointer oversvable
  95465. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  95466. // allow every non pointer down event to flow to the utility layer
  95467. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  95468. if (!prePointerInfo.skipOnPointerObservable) {
  95469. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95470. }
  95471. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  95472. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95473. }
  95474. return;
  95475. }
  95476. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  95477. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  95478. if (utilityScenePick && utilityScenePick.hit) {
  95479. if (!prePointerInfo.skipOnPointerObservable) {
  95480. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95481. }
  95482. prePointerInfo.skipOnPointerObservable = true;
  95483. }
  95484. }
  95485. else {
  95486. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  95487. var pointerEvent_1 = (prePointerInfo.event);
  95488. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  95489. if (originalScenePick && utilityScenePick) {
  95490. // No pick in utility scene
  95491. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  95492. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95493. // We touched an utility mesh present in the main scene
  95494. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95495. prePointerInfo.skipOnPointerObservable = true;
  95496. }
  95497. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95498. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  95499. }
  95500. }
  95501. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  95502. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  95503. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  95504. // If a previous utility layer set this, do not unset this
  95505. if (!prePointerInfo.skipOnPointerObservable) {
  95506. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  95507. }
  95508. }
  95509. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  95510. // We have a pick in both scenes but main is closer than utility
  95511. // We touched an utility mesh present in the main scene
  95512. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95513. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95514. prePointerInfo.skipOnPointerObservable = true;
  95515. }
  95516. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  95517. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  95518. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  95519. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  95520. }
  95521. }
  95522. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  95523. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  95524. }
  95525. }
  95526. }
  95527. });
  95528. // Render directly on top of existing scene without clearing
  95529. this.utilityLayerScene.autoClear = false;
  95530. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  95531. if (_this.shouldRender) {
  95532. _this.render();
  95533. }
  95534. });
  95535. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  95536. _this.dispose();
  95537. });
  95538. this._updateCamera();
  95539. }
  95540. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  95541. /**
  95542. * 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)
  95543. */
  95544. get: function () {
  95545. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  95546. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95547. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95548. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95549. });
  95550. }
  95551. return UtilityLayerRenderer._DefaultUtilityLayer;
  95552. },
  95553. enumerable: true,
  95554. configurable: true
  95555. });
  95556. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  95557. /**
  95558. * 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)
  95559. */
  95560. get: function () {
  95561. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  95562. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95563. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  95564. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95565. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95566. });
  95567. }
  95568. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  95569. },
  95570. enumerable: true,
  95571. configurable: true
  95572. });
  95573. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  95574. if (!prePointerInfo.skipOnPointerObservable) {
  95575. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  95576. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  95577. }
  95578. };
  95579. /**
  95580. * Renders the utility layers scene on top of the original scene
  95581. */
  95582. UtilityLayerRenderer.prototype.render = function () {
  95583. this._updateCamera();
  95584. if (this.utilityLayerScene.activeCamera) {
  95585. // Set the camera's scene to utility layers scene
  95586. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  95587. var camera = this.utilityLayerScene.activeCamera;
  95588. camera._scene = this.utilityLayerScene;
  95589. if (camera.leftCamera) {
  95590. camera.leftCamera._scene = this.utilityLayerScene;
  95591. }
  95592. if (camera.rightCamera) {
  95593. camera.rightCamera._scene = this.utilityLayerScene;
  95594. }
  95595. this.utilityLayerScene.render(false);
  95596. // Reset camera's scene back to original
  95597. camera._scene = oldScene;
  95598. if (camera.leftCamera) {
  95599. camera.leftCamera._scene = oldScene;
  95600. }
  95601. if (camera.rightCamera) {
  95602. camera.rightCamera._scene = oldScene;
  95603. }
  95604. }
  95605. };
  95606. /**
  95607. * Disposes of the renderer
  95608. */
  95609. UtilityLayerRenderer.prototype.dispose = function () {
  95610. this.onPointerOutObservable.clear();
  95611. if (this._afterRenderObserver) {
  95612. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  95613. }
  95614. if (this._sceneDisposeObserver) {
  95615. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95616. }
  95617. if (this._originalPointerObserver) {
  95618. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  95619. }
  95620. this.utilityLayerScene.dispose();
  95621. };
  95622. UtilityLayerRenderer.prototype._updateCamera = function () {
  95623. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  95624. };
  95625. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95626. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95627. return UtilityLayerRenderer;
  95628. }());
  95629. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  95630. })(BABYLON || (BABYLON = {}));
  95631. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  95632. //# sourceMappingURL=babylon.behavior.js.map
  95633. var BABYLON;
  95634. (function (BABYLON) {
  95635. /**
  95636. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95637. */
  95638. var PointerDragBehavior = /** @class */ (function () {
  95639. /**
  95640. * Creates a pointer drag behavior that can be attached to a mesh
  95641. * @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)
  95642. */
  95643. function PointerDragBehavior(options) {
  95644. /**
  95645. * 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)
  95646. */
  95647. this.maxDragAngle = 0;
  95648. /**
  95649. * @hidden
  95650. */
  95651. this._useAlternatePickedPointAboveMaxDragAngle = false;
  95652. /**
  95653. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95654. */
  95655. this.currentDraggingPointerID = -1;
  95656. /**
  95657. * If the behavior is currently in a dragging state
  95658. */
  95659. this.dragging = false;
  95660. /**
  95661. * 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)
  95662. */
  95663. this.dragDeltaRatio = 0.2;
  95664. /**
  95665. * If the drag plane orientation should be updated during the dragging (Default: true)
  95666. */
  95667. this.updateDragPlane = true;
  95668. // Debug mode will display drag planes to help visualize behavior
  95669. this._debugMode = false;
  95670. this._moving = false;
  95671. /**
  95672. * Fires each time the attached mesh is dragged with the pointer
  95673. * * delta between last drag position and current drag position in world space
  95674. * * dragDistance along the drag axis
  95675. * * dragPlaneNormal normal of the current drag plane used during the drag
  95676. * * dragPlanePoint in world space where the drag intersects the drag plane
  95677. */
  95678. this.onDragObservable = new BABYLON.Observable();
  95679. /**
  95680. * Fires each time a drag begins (eg. mouse down on mesh)
  95681. */
  95682. this.onDragStartObservable = new BABYLON.Observable();
  95683. /**
  95684. * Fires each time a drag ends (eg. mouse release after drag)
  95685. */
  95686. this.onDragEndObservable = new BABYLON.Observable();
  95687. /**
  95688. * If the attached mesh should be moved when dragged
  95689. */
  95690. this.moveAttached = true;
  95691. /**
  95692. * If the drag behavior will react to drag events (Default: true)
  95693. */
  95694. this.enabled = true;
  95695. /**
  95696. * If camera controls should be detached during the drag
  95697. */
  95698. this.detachCameraControls = true;
  95699. /**
  95700. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  95701. */
  95702. this.useObjectOrienationForDragging = true;
  95703. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95704. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  95705. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  95706. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95707. this._attachedElement = null;
  95708. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95709. this._lastPointerRay = {};
  95710. this._dragDelta = new BABYLON.Vector3();
  95711. // Variables to avoid instantiation in the below method
  95712. this._pointA = new BABYLON.Vector3(0, 0, 0);
  95713. this._pointB = new BABYLON.Vector3(0, 0, 0);
  95714. this._pointC = new BABYLON.Vector3(0, 0, 0);
  95715. this._lineA = new BABYLON.Vector3(0, 0, 0);
  95716. this._lineB = new BABYLON.Vector3(0, 0, 0);
  95717. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  95718. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  95719. this._options = options ? options : {};
  95720. var optionCount = 0;
  95721. if (this._options.dragAxis) {
  95722. optionCount++;
  95723. }
  95724. if (this._options.dragPlaneNormal) {
  95725. optionCount++;
  95726. }
  95727. if (optionCount > 1) {
  95728. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95729. }
  95730. }
  95731. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95732. /**
  95733. * The name of the behavior
  95734. */
  95735. get: function () {
  95736. return "PointerDrag";
  95737. },
  95738. enumerable: true,
  95739. configurable: true
  95740. });
  95741. /**
  95742. * Initializes the behavior
  95743. */
  95744. PointerDragBehavior.prototype.init = function () { };
  95745. /**
  95746. * Attaches the drag behavior the passed in mesh
  95747. * @param ownerNode The mesh that will be dragged around once attached
  95748. */
  95749. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95750. var _this = this;
  95751. this._scene = ownerNode.getScene();
  95752. this._attachedNode = ownerNode;
  95753. // Initialize drag plane to not interfere with existing scene
  95754. if (!PointerDragBehavior._planeScene) {
  95755. if (this._debugMode) {
  95756. PointerDragBehavior._planeScene = this._scene;
  95757. }
  95758. else {
  95759. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95760. PointerDragBehavior._planeScene.detachControl();
  95761. this._scene.getEngine().scenes.pop();
  95762. this._scene.onDisposeObservable.addOnce(function () {
  95763. PointerDragBehavior._planeScene.dispose();
  95764. PointerDragBehavior._planeScene = null;
  95765. });
  95766. }
  95767. }
  95768. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95769. // State of the drag
  95770. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  95771. var pickPredicate = function (m) {
  95772. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95773. };
  95774. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95775. if (!_this.enabled) {
  95776. return;
  95777. }
  95778. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95779. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95780. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  95781. }
  95782. }
  95783. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95784. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95785. _this.releaseDrag();
  95786. }
  95787. }
  95788. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95789. var pointerId = pointerInfo.event.pointerId;
  95790. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  95791. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  95792. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  95793. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  95794. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  95795. }
  95796. _this.currentDraggingPointerID = pointerId;
  95797. }
  95798. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  95799. if (!_this._lastPointerRay[pointerId]) {
  95800. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95801. }
  95802. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  95803. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  95804. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  95805. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  95806. _this._moveDrag(pointerInfo.pickInfo.ray);
  95807. }
  95808. }
  95809. }
  95810. });
  95811. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95812. if (_this._moving && _this.moveAttached) {
  95813. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  95814. // Slowly move mesh to avoid jitter
  95815. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  95816. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  95817. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  95818. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  95819. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  95820. }
  95821. });
  95822. };
  95823. /**
  95824. * Force relase the drag action by code.
  95825. */
  95826. PointerDragBehavior.prototype.releaseDrag = function () {
  95827. this.dragging = false;
  95828. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  95829. this.currentDraggingPointerID = -1;
  95830. this._moving = false;
  95831. // Reattach camera controls
  95832. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95833. this._scene.activeCamera.attachControl(this._attachedElement, true);
  95834. }
  95835. };
  95836. /**
  95837. * Simulates the start of a pointer drag event on the behavior
  95838. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  95839. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  95840. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  95841. */
  95842. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  95843. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  95844. this._startDrag(pointerId, fromRay, startPickedPoint);
  95845. var lastRay = this._lastPointerRay[pointerId];
  95846. if (pointerId === PointerDragBehavior._AnyMouseID) {
  95847. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  95848. }
  95849. if (lastRay) {
  95850. // if there was a last pointer ray drag the object there
  95851. this._moveDrag(lastRay);
  95852. }
  95853. };
  95854. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  95855. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  95856. return;
  95857. }
  95858. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  95859. // Create start ray from the camera to the object
  95860. if (fromRay) {
  95861. this._startDragRay.direction.copyFrom(fromRay.direction);
  95862. this._startDragRay.origin.copyFrom(fromRay.origin);
  95863. }
  95864. else {
  95865. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  95866. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  95867. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  95868. }
  95869. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  95870. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  95871. if (pickedPoint) {
  95872. this.dragging = true;
  95873. this.currentDraggingPointerID = pointerId;
  95874. this.lastDragPosition.copyFrom(pickedPoint);
  95875. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  95876. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  95877. // Detatch camera controls
  95878. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95879. if (this._scene.activeCamera.inputs.attachedElement) {
  95880. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  95881. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  95882. }
  95883. else {
  95884. this._attachedElement = null;
  95885. }
  95886. }
  95887. }
  95888. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  95889. };
  95890. PointerDragBehavior.prototype._moveDrag = function (ray) {
  95891. this._moving = true;
  95892. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  95893. if (pickedPoint) {
  95894. if (this.updateDragPlane) {
  95895. this._updateDragPlanePosition(ray, pickedPoint);
  95896. }
  95897. var dragLength = 0;
  95898. // depending on the drag mode option drag accordingly
  95899. if (this._options.dragAxis) {
  95900. // Convert local drag axis to world
  95901. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  95902. // Project delta drag from the drag plane onto the drag axis
  95903. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  95904. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  95905. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  95906. }
  95907. else {
  95908. dragLength = this._dragDelta.length();
  95909. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  95910. }
  95911. this._targetPosition.addInPlace(this._dragDelta);
  95912. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  95913. this.lastDragPosition.copyFrom(pickedPoint);
  95914. }
  95915. };
  95916. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95917. var _this = this;
  95918. if (!ray) {
  95919. return null;
  95920. }
  95921. // Calculate angle between plane normal and ray
  95922. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  95923. // Correct if ray is casted from oposite side
  95924. if (angle > Math.PI / 2) {
  95925. angle = Math.PI - angle;
  95926. }
  95927. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  95928. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  95929. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  95930. // Invert ray direction along the towards object axis
  95931. this._tmpVector.copyFrom(ray.direction);
  95932. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  95933. this._alternatePickedPoint.normalize();
  95934. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  95935. this._tmpVector.addInPlace(this._alternatePickedPoint);
  95936. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  95937. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  95938. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  95939. this._alternatePickedPoint.addInPlace(this._tmpVector);
  95940. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  95941. return this._alternatePickedPoint;
  95942. }
  95943. else {
  95944. return null;
  95945. }
  95946. }
  95947. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95948. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95949. return pickResult.pickedPoint;
  95950. }
  95951. else {
  95952. return null;
  95953. }
  95954. };
  95955. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95956. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  95957. this._pointA.copyFrom(dragPlanePosition);
  95958. if (this._options.dragAxis) {
  95959. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  95960. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95961. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  95962. ray.origin.subtractToRef(this._pointA, this._pointC);
  95963. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  95964. // Get perpendicular line from direction to camera and drag axis
  95965. this._pointB.subtractToRef(this._pointA, this._lineA);
  95966. this._pointC.subtractToRef(this._pointA, this._lineB);
  95967. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  95968. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95969. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  95970. this._lookAt.normalize();
  95971. this._dragPlane.position.copyFrom(this._pointA);
  95972. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  95973. this._dragPlane.lookAt(this._lookAt);
  95974. }
  95975. else if (this._options.dragPlaneNormal) {
  95976. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  95977. this._dragPlane.position.copyFrom(this._pointA);
  95978. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  95979. this._dragPlane.lookAt(this._lookAt);
  95980. }
  95981. else {
  95982. this._dragPlane.position.copyFrom(this._pointA);
  95983. this._dragPlane.lookAt(ray.origin);
  95984. }
  95985. this._dragPlane.computeWorldMatrix(true);
  95986. };
  95987. /**
  95988. * Detaches the behavior from the mesh
  95989. */
  95990. PointerDragBehavior.prototype.detach = function () {
  95991. if (this._pointerObserver) {
  95992. this._scene.onPointerObservable.remove(this._pointerObserver);
  95993. }
  95994. if (this._beforeRenderObserver) {
  95995. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95996. }
  95997. };
  95998. PointerDragBehavior._AnyMouseID = -2;
  95999. return PointerDragBehavior;
  96000. }());
  96001. BABYLON.PointerDragBehavior = PointerDragBehavior;
  96002. })(BABYLON || (BABYLON = {}));
  96003. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  96004. var BABYLON;
  96005. (function (BABYLON) {
  96006. /**
  96007. * A behavior that when attached to a mesh will allow the mesh to be scaled
  96008. */
  96009. var MultiPointerScaleBehavior = /** @class */ (function () {
  96010. /**
  96011. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  96012. */
  96013. function MultiPointerScaleBehavior() {
  96014. this._startDistance = 0;
  96015. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  96016. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  96017. this._sceneRenderObserver = null;
  96018. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  96019. this._dragBehaviorA.moveAttached = false;
  96020. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  96021. this._dragBehaviorB.moveAttached = false;
  96022. }
  96023. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  96024. /**
  96025. * The name of the behavior
  96026. */
  96027. get: function () {
  96028. return "MultiPointerScale";
  96029. },
  96030. enumerable: true,
  96031. configurable: true
  96032. });
  96033. /**
  96034. * Initializes the behavior
  96035. */
  96036. MultiPointerScaleBehavior.prototype.init = function () { };
  96037. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  96038. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  96039. };
  96040. /**
  96041. * Attaches the scale behavior the passed in mesh
  96042. * @param ownerNode The mesh that will be scaled around once attached
  96043. */
  96044. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  96045. var _this = this;
  96046. this._ownerNode = ownerNode;
  96047. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  96048. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  96049. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96050. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96051. _this._dragBehaviorA.releaseDrag();
  96052. }
  96053. else {
  96054. _this._initialScale.copyFrom(ownerNode.scaling);
  96055. _this._startDistance = _this._getCurrentDistance();
  96056. }
  96057. }
  96058. });
  96059. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  96060. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96061. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96062. _this._dragBehaviorB.releaseDrag();
  96063. }
  96064. else {
  96065. _this._initialScale.copyFrom(ownerNode.scaling);
  96066. _this._startDistance = _this._getCurrentDistance();
  96067. }
  96068. }
  96069. });
  96070. // Once both drag behaviors are active scale based on the distance between the two pointers
  96071. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96072. behavior.onDragObservable.add(function () {
  96073. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96074. var ratio = _this._getCurrentDistance() / _this._startDistance;
  96075. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  96076. }
  96077. });
  96078. });
  96079. ownerNode.addBehavior(this._dragBehaviorA);
  96080. ownerNode.addBehavior(this._dragBehaviorB);
  96081. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96082. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96083. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96084. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  96085. if (change.length() > 0.01) {
  96086. ownerNode.scaling.addInPlace(change);
  96087. }
  96088. }
  96089. });
  96090. };
  96091. /**
  96092. * Detaches the behavior from the mesh
  96093. */
  96094. MultiPointerScaleBehavior.prototype.detach = function () {
  96095. var _this = this;
  96096. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96097. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96098. behavior.onDragStartObservable.clear();
  96099. behavior.onDragObservable.clear();
  96100. _this._ownerNode.removeBehavior(behavior);
  96101. });
  96102. };
  96103. return MultiPointerScaleBehavior;
  96104. }());
  96105. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  96106. })(BABYLON || (BABYLON = {}));
  96107. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  96108. var BABYLON;
  96109. (function (BABYLON) {
  96110. /**
  96111. * 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
  96112. */
  96113. var SixDofDragBehavior = /** @class */ (function () {
  96114. /**
  96115. * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  96116. */
  96117. function SixDofDragBehavior() {
  96118. this._sceneRenderObserver = null;
  96119. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96120. this._moving = false;
  96121. this._startingOrientation = new BABYLON.Quaternion();
  96122. /**
  96123. * 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)
  96124. */
  96125. this.zDragFactor = 3;
  96126. /**
  96127. * If the behavior is currently in a dragging state
  96128. */
  96129. this.dragging = false;
  96130. /**
  96131. * 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)
  96132. */
  96133. this.dragDeltaRatio = 0.2;
  96134. /**
  96135. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96136. */
  96137. this.currentDraggingPointerID = -1;
  96138. /**
  96139. * If camera controls should be detached during the drag
  96140. */
  96141. this.detachCameraControls = true;
  96142. /**
  96143. * Fires each time a drag starts
  96144. */
  96145. this.onDragStartObservable = new BABYLON.Observable();
  96146. /**
  96147. * Fires each time a drag ends (eg. mouse release after drag)
  96148. */
  96149. this.onDragEndObservable = new BABYLON.Observable();
  96150. }
  96151. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  96152. /**
  96153. * The name of the behavior
  96154. */
  96155. get: function () {
  96156. return "SixDofDrag";
  96157. },
  96158. enumerable: true,
  96159. configurable: true
  96160. });
  96161. /**
  96162. * Initializes the behavior
  96163. */
  96164. SixDofDragBehavior.prototype.init = function () { };
  96165. /**
  96166. * Attaches the scale behavior the passed in mesh
  96167. * @param ownerNode The mesh that will be scaled around once attached
  96168. */
  96169. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  96170. var _this = this;
  96171. this._ownerNode = ownerNode;
  96172. this._scene = this._ownerNode.getScene();
  96173. if (!SixDofDragBehavior._virtualScene) {
  96174. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  96175. this._scene.getEngine().scenes.pop();
  96176. }
  96177. var pickedMesh = null;
  96178. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  96179. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  96180. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96181. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  96182. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96183. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  96184. var pickPredicate = function (m) {
  96185. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  96186. };
  96187. var attachedElement = null;
  96188. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96189. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96190. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96191. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96192. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96193. }
  96194. pickedMesh = _this._ownerNode;
  96195. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96196. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96197. // Set position and orientation of the controller
  96198. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96199. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96200. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  96201. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96202. pickedMesh.computeWorldMatrix();
  96203. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  96204. if (!pickedMesh.rotationQuaternion) {
  96205. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  96206. }
  96207. var oldParent = pickedMesh.parent;
  96208. pickedMesh.setParent(null);
  96209. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  96210. pickedMesh.setParent(oldParent);
  96211. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96212. // Update state
  96213. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96214. _this.dragging = true;
  96215. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  96216. // Detatch camera controls
  96217. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96218. if (_this._scene.activeCamera.inputs.attachedElement) {
  96219. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  96220. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  96221. }
  96222. else {
  96223. attachedElement = null;
  96224. }
  96225. }
  96226. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96227. _this.onDragStartObservable.notifyObservers({});
  96228. }
  96229. }
  96230. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96231. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96232. _this.dragging = false;
  96233. _this._moving = false;
  96234. _this.currentDraggingPointerID = -1;
  96235. pickedMesh = null;
  96236. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96237. // Reattach camera controls
  96238. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96239. _this._scene.activeCamera.attachControl(attachedElement, true);
  96240. }
  96241. _this.onDragEndObservable.notifyObservers({});
  96242. }
  96243. }
  96244. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96245. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  96246. var zDragFactor = _this.zDragFactor;
  96247. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96248. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96249. zDragFactor = 0;
  96250. }
  96251. // Calculate controller drag distance in controller space
  96252. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  96253. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96254. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  96255. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96256. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  96257. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  96258. if (_this._virtualDragMesh.position.z < 0) {
  96259. _this._virtualDragMesh.position.z = 0;
  96260. }
  96261. // Update the controller position
  96262. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96263. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96264. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96265. // Move the virtualObjectsPosition into the picked mesh's space if needed
  96266. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96267. if (pickedMesh.parent) {
  96268. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  96269. }
  96270. if (!_this._moving) {
  96271. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  96272. }
  96273. _this._moving = true;
  96274. }
  96275. }
  96276. });
  96277. var tmpQuaternion = new BABYLON.Quaternion();
  96278. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96279. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96280. if (_this.dragging && _this._moving && pickedMesh) {
  96281. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96282. // Slowly move mesh to avoid jitter
  96283. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  96284. // Get change in rotation
  96285. tmpQuaternion.copyFrom(_this._startingOrientation);
  96286. tmpQuaternion.x = -tmpQuaternion.x;
  96287. tmpQuaternion.y = -tmpQuaternion.y;
  96288. tmpQuaternion.z = -tmpQuaternion.z;
  96289. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  96290. // Convert change in rotation to only y axis rotation
  96291. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  96292. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  96293. // Slowly move mesh to avoid jitter
  96294. var oldParent = pickedMesh.parent;
  96295. pickedMesh.setParent(null);
  96296. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  96297. pickedMesh.setParent(oldParent);
  96298. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96299. }
  96300. });
  96301. };
  96302. /**
  96303. * Detaches the behavior from the mesh
  96304. */
  96305. SixDofDragBehavior.prototype.detach = function () {
  96306. if (this._scene) {
  96307. this._scene.onPointerObservable.remove(this._pointerObserver);
  96308. }
  96309. if (this._ownerNode) {
  96310. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96311. }
  96312. if (this._virtualOriginMesh) {
  96313. this._virtualOriginMesh.dispose();
  96314. }
  96315. if (this._virtualDragMesh) {
  96316. this._virtualDragMesh.dispose();
  96317. }
  96318. this.onDragEndObservable.clear();
  96319. this.onDragStartObservable.clear();
  96320. };
  96321. return SixDofDragBehavior;
  96322. }());
  96323. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  96324. })(BABYLON || (BABYLON = {}));
  96325. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  96326. var BABYLON;
  96327. (function (BABYLON) {
  96328. /**
  96329. * @hidden
  96330. */
  96331. var FaceDirectionInfo = /** @class */ (function () {
  96332. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  96333. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  96334. if (diff === void 0) { diff = 0; }
  96335. if (ignore === void 0) { ignore = false; }
  96336. this.direction = direction;
  96337. this.rotatedDirection = rotatedDirection;
  96338. this.diff = diff;
  96339. this.ignore = ignore;
  96340. }
  96341. return FaceDirectionInfo;
  96342. }());
  96343. /**
  96344. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  96345. */
  96346. var AttachToBoxBehavior = /** @class */ (function () {
  96347. /**
  96348. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  96349. * @param ui The transform node that should be attched to the mesh
  96350. */
  96351. function AttachToBoxBehavior(ui) {
  96352. this.ui = ui;
  96353. /**
  96354. * The name of the behavior
  96355. */
  96356. this.name = "AttachToBoxBehavior";
  96357. /**
  96358. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  96359. */
  96360. this.distanceAwayFromFace = 0.15;
  96361. /**
  96362. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  96363. */
  96364. this.distanceAwayFromBottomOfFace = 0.15;
  96365. 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))];
  96366. this._tmpMatrix = new BABYLON.Matrix();
  96367. this._tmpVector = new BABYLON.Vector3();
  96368. this._zeroVector = BABYLON.Vector3.Zero();
  96369. this._lookAtTmpMatrix = new BABYLON.Matrix();
  96370. /* Does nothing */
  96371. }
  96372. /**
  96373. * Initializes the behavior
  96374. */
  96375. AttachToBoxBehavior.prototype.init = function () {
  96376. /* Does nothing */
  96377. };
  96378. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  96379. var _this = this;
  96380. // Go over each face and calculate the angle between the face's normal and targetDirection
  96381. this._faceVectors.forEach(function (v) {
  96382. if (!_this._target.rotationQuaternion) {
  96383. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  96384. }
  96385. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  96386. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  96387. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  96388. });
  96389. // Return the face information of the one with the normal closeset to target direction
  96390. return this._faceVectors.reduce(function (min, p) {
  96391. if (min.ignore) {
  96392. return p;
  96393. }
  96394. else if (p.ignore) {
  96395. return min;
  96396. }
  96397. else {
  96398. return min.diff < p.diff ? min : p;
  96399. }
  96400. }, this._faceVectors[0]);
  96401. };
  96402. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  96403. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  96404. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  96405. this._lookAtTmpMatrix.invert();
  96406. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  96407. };
  96408. /**
  96409. * Attaches the AttachToBoxBehavior to the passed in mesh
  96410. * @param target The mesh that the specified node will be attached to
  96411. */
  96412. AttachToBoxBehavior.prototype.attach = function (target) {
  96413. var _this = this;
  96414. this._target = target;
  96415. this._scene = this._target.getScene();
  96416. // Every frame, update the app bars position
  96417. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96418. if (!_this._scene.activeCamera) {
  96419. return;
  96420. }
  96421. // Find the face closest to the cameras position
  96422. var cameraPos = _this._scene.activeCamera.position;
  96423. if (_this._scene.activeCamera.devicePosition) {
  96424. cameraPos = _this._scene.activeCamera.devicePosition;
  96425. }
  96426. var facing = _this._closestFace(cameraPos.subtract(target.position));
  96427. if (_this._scene.activeCamera.leftCamera) {
  96428. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96429. }
  96430. else {
  96431. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96432. }
  96433. // Get camera up direction
  96434. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  96435. // Ignore faces to not select a parrelel face for the up vector of the UI
  96436. _this._faceVectors.forEach(function (v) {
  96437. if (facing.direction.x && v.direction.x) {
  96438. v.ignore = true;
  96439. }
  96440. if (facing.direction.y && v.direction.y) {
  96441. v.ignore = true;
  96442. }
  96443. if (facing.direction.z && v.direction.z) {
  96444. v.ignore = true;
  96445. }
  96446. });
  96447. var facingUp = _this._closestFace(_this._tmpVector);
  96448. // Unignore faces
  96449. _this._faceVectors.forEach(function (v) {
  96450. v.ignore = false;
  96451. });
  96452. // Position the app bar on that face
  96453. _this.ui.position.copyFrom(target.position);
  96454. if (facing.direction.x) {
  96455. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96456. _this.ui.position.addInPlace(_this._tmpVector);
  96457. }
  96458. if (facing.direction.y) {
  96459. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96460. _this.ui.position.addInPlace(_this._tmpVector);
  96461. }
  96462. if (facing.direction.z) {
  96463. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96464. _this.ui.position.addInPlace(_this._tmpVector);
  96465. }
  96466. // Rotate to be oriented properly to the camera
  96467. if (!_this.ui.rotationQuaternion) {
  96468. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  96469. }
  96470. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  96471. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  96472. // Place ui the correct distance from the bottom of the mesh
  96473. if (facingUp.direction.x) {
  96474. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  96475. }
  96476. if (facingUp.direction.y) {
  96477. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  96478. }
  96479. if (facingUp.direction.z) {
  96480. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  96481. }
  96482. _this.ui.position.addInPlace(_this._tmpVector);
  96483. });
  96484. };
  96485. /**
  96486. * Detaches the behavior from the mesh
  96487. */
  96488. AttachToBoxBehavior.prototype.detach = function () {
  96489. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  96490. };
  96491. return AttachToBoxBehavior;
  96492. }());
  96493. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  96494. })(BABYLON || (BABYLON = {}));
  96495. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  96496. var BABYLON;
  96497. (function (BABYLON) {
  96498. /**
  96499. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  96500. */
  96501. var FadeInOutBehavior = /** @class */ (function () {
  96502. /**
  96503. * Instatiates the FadeInOutBehavior
  96504. */
  96505. function FadeInOutBehavior() {
  96506. var _this = this;
  96507. /**
  96508. * Time in milliseconds to delay before fading in (Default: 0)
  96509. */
  96510. this.delay = 0;
  96511. /**
  96512. * Time in milliseconds for the mesh to fade in (Default: 300)
  96513. */
  96514. this.fadeInTime = 300;
  96515. this._millisecondsPerFrame = 1000 / 60;
  96516. this._hovered = false;
  96517. this._hoverValue = 0;
  96518. this._ownerNode = null;
  96519. this._update = function () {
  96520. if (_this._ownerNode) {
  96521. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  96522. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  96523. if (_this._ownerNode.visibility > 1) {
  96524. _this._setAllVisibility(_this._ownerNode, 1);
  96525. _this._hoverValue = _this.fadeInTime + _this.delay;
  96526. return;
  96527. }
  96528. else if (_this._ownerNode.visibility < 0) {
  96529. _this._setAllVisibility(_this._ownerNode, 0);
  96530. if (_this._hoverValue < 0) {
  96531. _this._hoverValue = 0;
  96532. return;
  96533. }
  96534. }
  96535. setTimeout(_this._update, _this._millisecondsPerFrame);
  96536. }
  96537. };
  96538. }
  96539. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  96540. /**
  96541. * The name of the behavior
  96542. */
  96543. get: function () {
  96544. return "FadeInOut";
  96545. },
  96546. enumerable: true,
  96547. configurable: true
  96548. });
  96549. /**
  96550. * Initializes the behavior
  96551. */
  96552. FadeInOutBehavior.prototype.init = function () {
  96553. };
  96554. /**
  96555. * Attaches the fade behavior on the passed in mesh
  96556. * @param ownerNode The mesh that will be faded in/out once attached
  96557. */
  96558. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  96559. this._ownerNode = ownerNode;
  96560. this._setAllVisibility(this._ownerNode, 0);
  96561. };
  96562. /**
  96563. * Detaches the behavior from the mesh
  96564. */
  96565. FadeInOutBehavior.prototype.detach = function () {
  96566. this._ownerNode = null;
  96567. };
  96568. /**
  96569. * Triggers the mesh to begin fading in or out
  96570. * @param value if the object should fade in or out (true to fade in)
  96571. */
  96572. FadeInOutBehavior.prototype.fadeIn = function (value) {
  96573. this._hovered = value;
  96574. this._update();
  96575. };
  96576. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  96577. var _this = this;
  96578. mesh.visibility = value;
  96579. mesh.getChildMeshes().forEach(function (c) {
  96580. _this._setAllVisibility(c, value);
  96581. });
  96582. };
  96583. return FadeInOutBehavior;
  96584. }());
  96585. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  96586. })(BABYLON || (BABYLON = {}));
  96587. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  96588. var BABYLON;
  96589. (function (BABYLON) {
  96590. /**
  96591. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  96592. */
  96593. var Gizmo = /** @class */ (function () {
  96594. /**
  96595. * Creates a gizmo
  96596. * @param gizmoLayer The utility layer the gizmo will be added to
  96597. */
  96598. function Gizmo(
  96599. /** The utility layer the gizmo will be added to */
  96600. gizmoLayer) {
  96601. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96602. var _this = this;
  96603. this.gizmoLayer = gizmoLayer;
  96604. /**
  96605. * Ratio for the scale of the gizmo (Default: 1)
  96606. */
  96607. this.scaleRatio = 1;
  96608. this._tmpMatrix = new BABYLON.Matrix();
  96609. /**
  96610. * If a custom mesh has been set (Default: false)
  96611. */
  96612. this._customMeshSet = false;
  96613. /**
  96614. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  96615. */
  96616. this.updateGizmoRotationToMatchAttachedMesh = true;
  96617. /**
  96618. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  96619. */
  96620. this.updateGizmoPositionToMatchAttachedMesh = true;
  96621. /**
  96622. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  96623. */
  96624. this._updateScale = true;
  96625. this._interactionsEnabled = true;
  96626. this._tempVector = new BABYLON.Vector3();
  96627. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  96628. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  96629. _this._update();
  96630. });
  96631. this.attachedMesh = null;
  96632. }
  96633. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  96634. /**
  96635. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  96636. * * When set, interactions will be enabled
  96637. */
  96638. get: function () {
  96639. return this._attachedMesh;
  96640. },
  96641. set: function (value) {
  96642. this._attachedMesh = value;
  96643. this._rootMesh.setEnabled(value ? true : false);
  96644. this._attachedMeshChanged(value);
  96645. },
  96646. enumerable: true,
  96647. configurable: true
  96648. });
  96649. /**
  96650. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96651. * @param mesh The mesh to replace the default mesh of the gizmo
  96652. */
  96653. Gizmo.prototype.setCustomMesh = function (mesh) {
  96654. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  96655. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  96656. }
  96657. this._rootMesh.getChildMeshes().forEach(function (c) {
  96658. c.dispose();
  96659. });
  96660. mesh.parent = this._rootMesh;
  96661. this._customMeshSet = true;
  96662. };
  96663. Gizmo.prototype._attachedMeshChanged = function (value) {
  96664. };
  96665. /**
  96666. * @hidden
  96667. * Updates the gizmo to match the attached mesh's position/rotation
  96668. */
  96669. Gizmo.prototype._update = function () {
  96670. if (this.attachedMesh) {
  96671. if (this.updateGizmoRotationToMatchAttachedMesh) {
  96672. if (!this._rootMesh.rotationQuaternion) {
  96673. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  96674. }
  96675. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  96676. this._tempVector.copyFrom(this.attachedMesh.scaling);
  96677. if (this.attachedMesh.scaling.x < 0) {
  96678. this.attachedMesh.scaling.x *= -1;
  96679. }
  96680. if (this.attachedMesh.scaling.y < 0) {
  96681. this.attachedMesh.scaling.y *= -1;
  96682. }
  96683. if (this.attachedMesh.scaling.z < 0) {
  96684. this.attachedMesh.scaling.z *= -1;
  96685. }
  96686. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  96687. this.attachedMesh.scaling.copyFrom(this._tempVector);
  96688. this.attachedMesh.computeWorldMatrix();
  96689. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  96690. }
  96691. else if (this._rootMesh.rotationQuaternion) {
  96692. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  96693. }
  96694. if (this.updateGizmoPositionToMatchAttachedMesh) {
  96695. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  96696. }
  96697. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  96698. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  96699. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  96700. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  96701. }
  96702. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  96703. var dist = this._tempVector.length() * this.scaleRatio;
  96704. this._rootMesh.scaling.set(dist, dist, dist);
  96705. }
  96706. }
  96707. };
  96708. /**
  96709. * Disposes of the gizmo
  96710. */
  96711. Gizmo.prototype.dispose = function () {
  96712. this._rootMesh.dispose();
  96713. if (this._beforeRenderObserver) {
  96714. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96715. }
  96716. };
  96717. return Gizmo;
  96718. }());
  96719. BABYLON.Gizmo = Gizmo;
  96720. })(BABYLON || (BABYLON = {}));
  96721. //# sourceMappingURL=babylon.gizmo.js.map
  96722. var BABYLON;
  96723. (function (BABYLON) {
  96724. /**
  96725. * Single axis drag gizmo
  96726. */
  96727. var AxisDragGizmo = /** @class */ (function (_super) {
  96728. __extends(AxisDragGizmo, _super);
  96729. /**
  96730. * Creates an AxisDragGizmo
  96731. * @param gizmoLayer The utility layer the gizmo will be added to
  96732. * @param dragAxis The axis which the gizmo will be able to drag on
  96733. * @param color The color of the gizmo
  96734. */
  96735. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  96736. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96737. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96738. var _this = _super.call(this, gizmoLayer) || this;
  96739. _this._pointerObserver = null;
  96740. /**
  96741. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96742. */
  96743. _this.snapDistance = 0;
  96744. /**
  96745. * Event that fires each time the gizmo snaps to a new location.
  96746. * * snapDistance is the the change in distance
  96747. */
  96748. _this.onSnapObservable = new BABYLON.Observable();
  96749. // Create Material
  96750. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96751. coloredMaterial.disableLighting = true;
  96752. coloredMaterial.emissiveColor = color;
  96753. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96754. hoverMaterial.disableLighting = true;
  96755. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96756. // Build mesh on root node
  96757. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96758. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  96759. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96760. arrowTail.color = coloredMaterial.emissiveColor;
  96761. arrow.addChild(arrowMesh);
  96762. arrow.addChild(arrowTail);
  96763. // Position arrow pointing in its drag axis
  96764. arrowMesh.scaling.scaleInPlace(0.05);
  96765. arrowMesh.material = coloredMaterial;
  96766. arrowMesh.rotation.x = Math.PI / 2;
  96767. arrowMesh.position.z += 0.3;
  96768. arrowTail.scaling.scaleInPlace(0.26);
  96769. arrowTail.rotation.x = Math.PI / 2;
  96770. arrowTail.material = coloredMaterial;
  96771. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96772. arrow.scaling.scaleInPlace(1 / 3);
  96773. _this._rootMesh.addChild(arrow);
  96774. var currentSnapDragDistance = 0;
  96775. var tmpVector = new BABYLON.Vector3();
  96776. var tmpSnapEvent = { snapDistance: 0 };
  96777. // Add drag behavior to handle events when the gizmo is dragged
  96778. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96779. _this.dragBehavior.moveAttached = false;
  96780. _this._rootMesh.addBehavior(_this.dragBehavior);
  96781. var localDelta = new BABYLON.Vector3();
  96782. var tmpMatrix = new BABYLON.Matrix();
  96783. _this.dragBehavior.onDragObservable.add(function (event) {
  96784. if (_this.attachedMesh) {
  96785. // Convert delta to local translation if it has a parent
  96786. if (_this.attachedMesh.parent) {
  96787. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96788. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  96789. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  96790. }
  96791. else {
  96792. localDelta.copyFrom(event.delta);
  96793. }
  96794. // Snapping logic
  96795. if (_this.snapDistance == 0) {
  96796. _this.attachedMesh.position.addInPlace(localDelta);
  96797. }
  96798. else {
  96799. currentSnapDragDistance += event.dragDistance;
  96800. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96801. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  96802. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96803. localDelta.normalizeToRef(tmpVector);
  96804. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  96805. _this.attachedMesh.position.addInPlace(tmpVector);
  96806. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96807. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96808. }
  96809. }
  96810. }
  96811. });
  96812. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96813. if (_this._customMeshSet) {
  96814. return;
  96815. }
  96816. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96817. var material = isHovered ? hoverMaterial : coloredMaterial;
  96818. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96819. m.material = material;
  96820. if (m.color) {
  96821. m.color = material.emissiveColor;
  96822. }
  96823. });
  96824. });
  96825. return _this;
  96826. }
  96827. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  96828. if (this.dragBehavior) {
  96829. this.dragBehavior.enabled = value ? true : false;
  96830. }
  96831. };
  96832. /**
  96833. * Disposes of the gizmo
  96834. */
  96835. AxisDragGizmo.prototype.dispose = function () {
  96836. this.onSnapObservable.clear();
  96837. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96838. this.dragBehavior.detach();
  96839. _super.prototype.dispose.call(this);
  96840. };
  96841. return AxisDragGizmo;
  96842. }(BABYLON.Gizmo));
  96843. BABYLON.AxisDragGizmo = AxisDragGizmo;
  96844. })(BABYLON || (BABYLON = {}));
  96845. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  96846. var BABYLON;
  96847. (function (BABYLON) {
  96848. /**
  96849. * Single axis scale gizmo
  96850. */
  96851. var AxisScaleGizmo = /** @class */ (function (_super) {
  96852. __extends(AxisScaleGizmo, _super);
  96853. /**
  96854. * Creates an AxisScaleGizmo
  96855. * @param gizmoLayer The utility layer the gizmo will be added to
  96856. * @param dragAxis The axis which the gizmo will be able to scale on
  96857. * @param color The color of the gizmo
  96858. */
  96859. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  96860. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96861. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96862. var _this = _super.call(this, gizmoLayer) || this;
  96863. _this._pointerObserver = null;
  96864. /**
  96865. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96866. */
  96867. _this.snapDistance = 0;
  96868. /**
  96869. * Event that fires each time the gizmo snaps to a new location.
  96870. * * snapDistance is the the change in distance
  96871. */
  96872. _this.onSnapObservable = new BABYLON.Observable();
  96873. /**
  96874. * If the scaling operation should be done on all axis (default: false)
  96875. */
  96876. _this.uniformScaling = false;
  96877. // Create Material
  96878. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96879. _this._coloredMaterial.disableLighting = true;
  96880. _this._coloredMaterial.emissiveColor = color;
  96881. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96882. hoverMaterial.disableLighting = true;
  96883. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96884. // Build mesh on root node
  96885. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96886. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  96887. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96888. arrowTail.color = _this._coloredMaterial.emissiveColor;
  96889. arrow.addChild(arrowMesh);
  96890. arrow.addChild(arrowTail);
  96891. // Position arrow pointing in its drag axis
  96892. arrowMesh.scaling.scaleInPlace(0.1);
  96893. arrowMesh.material = _this._coloredMaterial;
  96894. arrowMesh.rotation.x = Math.PI / 2;
  96895. arrowMesh.position.z += 0.3;
  96896. arrowTail.scaling.scaleInPlace(0.26);
  96897. arrowTail.rotation.x = Math.PI / 2;
  96898. arrowTail.material = _this._coloredMaterial;
  96899. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96900. _this._rootMesh.addChild(arrow);
  96901. arrow.scaling.scaleInPlace(1 / 3);
  96902. // Add drag behavior to handle events when the gizmo is dragged
  96903. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96904. _this.dragBehavior.moveAttached = false;
  96905. _this._rootMesh.addBehavior(_this.dragBehavior);
  96906. var currentSnapDragDistance = 0;
  96907. var tmpVector = new BABYLON.Vector3();
  96908. var tmpSnapEvent = { snapDistance: 0 };
  96909. _this.dragBehavior.onDragObservable.add(function (event) {
  96910. if (_this.attachedMesh) {
  96911. // Snapping logic
  96912. var snapped = false;
  96913. var dragSteps = 0;
  96914. if (_this.uniformScaling) {
  96915. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  96916. if (tmpVector.y < 0) {
  96917. tmpVector.scaleInPlace(-1);
  96918. }
  96919. }
  96920. else {
  96921. tmpVector.copyFrom(dragAxis);
  96922. }
  96923. if (_this.snapDistance == 0) {
  96924. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  96925. }
  96926. else {
  96927. currentSnapDragDistance += event.dragDistance;
  96928. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96929. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96930. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96931. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  96932. snapped = true;
  96933. }
  96934. else {
  96935. tmpVector.scaleInPlace(0);
  96936. }
  96937. }
  96938. _this.attachedMesh.scaling.addInPlace(tmpVector);
  96939. if (snapped) {
  96940. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96941. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96942. }
  96943. }
  96944. });
  96945. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96946. if (_this._customMeshSet) {
  96947. return;
  96948. }
  96949. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96950. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  96951. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96952. m.material = material;
  96953. if (m.color) {
  96954. m.color = material.emissiveColor;
  96955. }
  96956. });
  96957. });
  96958. return _this;
  96959. }
  96960. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  96961. if (this.dragBehavior) {
  96962. this.dragBehavior.enabled = value ? true : false;
  96963. }
  96964. };
  96965. /**
  96966. * Disposes of the gizmo
  96967. */
  96968. AxisScaleGizmo.prototype.dispose = function () {
  96969. this.onSnapObservable.clear();
  96970. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96971. this.dragBehavior.detach();
  96972. _super.prototype.dispose.call(this);
  96973. };
  96974. /**
  96975. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96976. * @param mesh The mesh to replace the default mesh of the gizmo
  96977. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  96978. */
  96979. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  96980. var _this = this;
  96981. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  96982. _super.prototype.setCustomMesh.call(this, mesh);
  96983. if (useGizmoMaterial) {
  96984. this._rootMesh.getChildMeshes().forEach(function (m) {
  96985. m.material = _this._coloredMaterial;
  96986. if (m.color) {
  96987. m.color = _this._coloredMaterial.emissiveColor;
  96988. }
  96989. });
  96990. this._customMeshSet = false;
  96991. }
  96992. };
  96993. return AxisScaleGizmo;
  96994. }(BABYLON.Gizmo));
  96995. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  96996. })(BABYLON || (BABYLON = {}));
  96997. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  96998. var BABYLON;
  96999. (function (BABYLON) {
  97000. /**
  97001. * Single plane rotation gizmo
  97002. */
  97003. var PlaneRotationGizmo = /** @class */ (function (_super) {
  97004. __extends(PlaneRotationGizmo, _super);
  97005. /**
  97006. * Creates a PlaneRotationGizmo
  97007. * @param gizmoLayer The utility layer the gizmo will be added to
  97008. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  97009. * @param color The color of the gizmo
  97010. */
  97011. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  97012. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97013. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97014. var _this = _super.call(this, gizmoLayer) || this;
  97015. _this._pointerObserver = null;
  97016. /**
  97017. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  97018. */
  97019. _this.snapDistance = 0;
  97020. /**
  97021. * Event that fires each time the gizmo snaps to a new location.
  97022. * * snapDistance is the the change in distance
  97023. */
  97024. _this.onSnapObservable = new BABYLON.Observable();
  97025. // Create Material
  97026. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97027. coloredMaterial.disableLighting = true;
  97028. coloredMaterial.emissiveColor = color;
  97029. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97030. hoverMaterial.disableLighting = true;
  97031. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97032. // Build mesh on root node
  97033. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97034. // Create circle out of lines
  97035. var tessellation = 20;
  97036. var radius = 0.8;
  97037. var points = new Array();
  97038. for (var i = 0; i < tessellation; i++) {
  97039. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  97040. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  97041. }
  97042. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  97043. rotationMesh.color = coloredMaterial.emissiveColor;
  97044. // Position arrow pointing in its drag axis
  97045. rotationMesh.scaling.scaleInPlace(0.26);
  97046. rotationMesh.material = coloredMaterial;
  97047. rotationMesh.rotation.x = Math.PI / 2;
  97048. parentMesh.addChild(rotationMesh);
  97049. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  97050. _this._rootMesh.addChild(parentMesh);
  97051. parentMesh.scaling.scaleInPlace(1 / 3);
  97052. // Add drag behavior to handle events when the gizmo is dragged
  97053. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  97054. _this.dragBehavior.moveAttached = false;
  97055. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  97056. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  97057. _this._rootMesh.addBehavior(_this.dragBehavior);
  97058. var lastDragPosition = new BABYLON.Vector3();
  97059. _this.dragBehavior.onDragStartObservable.add(function (e) {
  97060. if (_this.attachedMesh) {
  97061. lastDragPosition.copyFrom(e.dragPlanePoint);
  97062. }
  97063. });
  97064. var rotationMatrix = new BABYLON.Matrix();
  97065. var planeNormalTowardsCamera = new BABYLON.Vector3();
  97066. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  97067. var tmpSnapEvent = { snapDistance: 0 };
  97068. var currentSnapDragDistance = 0;
  97069. var tmpMatrix = new BABYLON.Matrix();
  97070. var tmpVector = new BABYLON.Vector3();
  97071. var amountToRotate = new BABYLON.Quaternion();
  97072. _this.dragBehavior.onDragObservable.add(function (event) {
  97073. if (_this.attachedMesh) {
  97074. if (!_this.attachedMesh.rotationQuaternion) {
  97075. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97076. }
  97077. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  97078. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  97079. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  97080. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  97081. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  97082. var angle = Math.atan2(cross.length(), dot);
  97083. planeNormalTowardsCamera.copyFrom(planeNormal);
  97084. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  97085. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97086. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  97087. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  97088. }
  97089. // Flip up vector depending on which side the camera is on
  97090. if (gizmoLayer.utilityLayerScene.activeCamera) {
  97091. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  97092. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  97093. planeNormalTowardsCamera.scaleInPlace(-1);
  97094. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  97095. }
  97096. }
  97097. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  97098. if (halfCircleSide)
  97099. angle = -angle;
  97100. // Snapping logic
  97101. var snapped = false;
  97102. if (_this.snapDistance != 0) {
  97103. currentSnapDragDistance += angle;
  97104. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97105. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97106. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97107. angle = _this.snapDistance * dragSteps;
  97108. snapped = true;
  97109. }
  97110. else {
  97111. angle = 0;
  97112. }
  97113. }
  97114. // If the mesh has a parent, convert needed world rotation to local rotation
  97115. tmpMatrix.reset();
  97116. if (_this.attachedMesh.parent) {
  97117. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97118. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  97119. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  97120. }
  97121. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  97122. var quaternionCoefficient = Math.sin(angle / 2);
  97123. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  97124. // 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
  97125. if (tmpMatrix.determinant() > 0) {
  97126. amountToRotate.toEulerAnglesToRef(tmpVector);
  97127. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  97128. }
  97129. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97130. // Rotate selected mesh quaternion over fixed axis
  97131. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  97132. }
  97133. else {
  97134. // Rotate selected mesh quaternion over rotated axis
  97135. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  97136. }
  97137. lastDragPosition.copyFrom(event.dragPlanePoint);
  97138. if (snapped) {
  97139. tmpSnapEvent.snapDistance = angle;
  97140. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97141. }
  97142. }
  97143. });
  97144. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97145. if (_this._customMeshSet) {
  97146. return;
  97147. }
  97148. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97149. var material = isHovered ? hoverMaterial : coloredMaterial;
  97150. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97151. m.material = material;
  97152. if (m.color) {
  97153. m.color = material.emissiveColor;
  97154. }
  97155. });
  97156. });
  97157. return _this;
  97158. }
  97159. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  97160. if (this.dragBehavior) {
  97161. this.dragBehavior.enabled = value ? true : false;
  97162. }
  97163. };
  97164. /**
  97165. * Disposes of the gizmo
  97166. */
  97167. PlaneRotationGizmo.prototype.dispose = function () {
  97168. this.onSnapObservable.clear();
  97169. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97170. this.dragBehavior.detach();
  97171. _super.prototype.dispose.call(this);
  97172. };
  97173. return PlaneRotationGizmo;
  97174. }(BABYLON.Gizmo));
  97175. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  97176. })(BABYLON || (BABYLON = {}));
  97177. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  97178. var BABYLON;
  97179. (function (BABYLON) {
  97180. /**
  97181. * Gizmo that enables dragging a mesh along 3 axis
  97182. */
  97183. var PositionGizmo = /** @class */ (function (_super) {
  97184. __extends(PositionGizmo, _super);
  97185. /**
  97186. * Creates a PositionGizmo
  97187. * @param gizmoLayer The utility layer the gizmo will be added to
  97188. */
  97189. function PositionGizmo(gizmoLayer) {
  97190. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97191. var _this = _super.call(this, gizmoLayer) || this;
  97192. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97193. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97194. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97195. _this.attachedMesh = null;
  97196. return _this;
  97197. }
  97198. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  97199. set: function (mesh) {
  97200. if (this.xGizmo) {
  97201. this.xGizmo.attachedMesh = mesh;
  97202. this.yGizmo.attachedMesh = mesh;
  97203. this.zGizmo.attachedMesh = mesh;
  97204. }
  97205. },
  97206. enumerable: true,
  97207. configurable: true
  97208. });
  97209. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97210. get: function () {
  97211. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97212. },
  97213. set: function (value) {
  97214. if (this.xGizmo) {
  97215. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97216. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97217. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97218. }
  97219. },
  97220. enumerable: true,
  97221. configurable: true
  97222. });
  97223. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  97224. get: function () {
  97225. return this.xGizmo.snapDistance;
  97226. },
  97227. /**
  97228. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97229. */
  97230. set: function (value) {
  97231. if (this.xGizmo) {
  97232. this.xGizmo.snapDistance = value;
  97233. this.yGizmo.snapDistance = value;
  97234. this.zGizmo.snapDistance = value;
  97235. }
  97236. },
  97237. enumerable: true,
  97238. configurable: true
  97239. });
  97240. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  97241. get: function () {
  97242. return this.xGizmo.scaleRatio;
  97243. },
  97244. /**
  97245. * Ratio for the scale of the gizmo (Default: 1)
  97246. */
  97247. set: function (value) {
  97248. if (this.xGizmo) {
  97249. this.xGizmo.scaleRatio = value;
  97250. this.yGizmo.scaleRatio = value;
  97251. this.zGizmo.scaleRatio = value;
  97252. }
  97253. },
  97254. enumerable: true,
  97255. configurable: true
  97256. });
  97257. /**
  97258. * Disposes of the gizmo
  97259. */
  97260. PositionGizmo.prototype.dispose = function () {
  97261. this.xGizmo.dispose();
  97262. this.yGizmo.dispose();
  97263. this.zGizmo.dispose();
  97264. };
  97265. /**
  97266. * CustomMeshes are not supported by this gizmo
  97267. * @param mesh The mesh to replace the default mesh of the gizmo
  97268. */
  97269. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  97270. 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)");
  97271. };
  97272. return PositionGizmo;
  97273. }(BABYLON.Gizmo));
  97274. BABYLON.PositionGizmo = PositionGizmo;
  97275. })(BABYLON || (BABYLON = {}));
  97276. //# sourceMappingURL=babylon.positionGizmo.js.map
  97277. var BABYLON;
  97278. (function (BABYLON) {
  97279. /**
  97280. * Gizmo that enables rotating a mesh along 3 axis
  97281. */
  97282. var RotationGizmo = /** @class */ (function (_super) {
  97283. __extends(RotationGizmo, _super);
  97284. /**
  97285. * Creates a RotationGizmo
  97286. * @param gizmoLayer The utility layer the gizmo will be added to
  97287. */
  97288. function RotationGizmo(gizmoLayer) {
  97289. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97290. var _this = _super.call(this, gizmoLayer) || this;
  97291. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97292. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97293. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97294. _this.attachedMesh = null;
  97295. return _this;
  97296. }
  97297. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  97298. set: function (mesh) {
  97299. if (this.xGizmo) {
  97300. this.xGizmo.attachedMesh = mesh;
  97301. this.yGizmo.attachedMesh = mesh;
  97302. this.zGizmo.attachedMesh = mesh;
  97303. }
  97304. },
  97305. enumerable: true,
  97306. configurable: true
  97307. });
  97308. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97309. get: function () {
  97310. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97311. },
  97312. set: function (value) {
  97313. if (this.xGizmo) {
  97314. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97315. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97316. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97317. }
  97318. },
  97319. enumerable: true,
  97320. configurable: true
  97321. });
  97322. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  97323. get: function () {
  97324. return this.xGizmo.snapDistance;
  97325. },
  97326. /**
  97327. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97328. */
  97329. set: function (value) {
  97330. if (this.xGizmo) {
  97331. this.xGizmo.snapDistance = value;
  97332. this.yGizmo.snapDistance = value;
  97333. this.zGizmo.snapDistance = value;
  97334. }
  97335. },
  97336. enumerable: true,
  97337. configurable: true
  97338. });
  97339. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  97340. get: function () {
  97341. return this.xGizmo.scaleRatio;
  97342. },
  97343. /**
  97344. * Ratio for the scale of the gizmo (Default: 1)
  97345. */
  97346. set: function (value) {
  97347. if (this.xGizmo) {
  97348. this.xGizmo.scaleRatio = value;
  97349. this.yGizmo.scaleRatio = value;
  97350. this.zGizmo.scaleRatio = value;
  97351. }
  97352. },
  97353. enumerable: true,
  97354. configurable: true
  97355. });
  97356. /**
  97357. * Disposes of the gizmo
  97358. */
  97359. RotationGizmo.prototype.dispose = function () {
  97360. this.xGizmo.dispose();
  97361. this.yGizmo.dispose();
  97362. this.zGizmo.dispose();
  97363. };
  97364. /**
  97365. * CustomMeshes are not supported by this gizmo
  97366. * @param mesh The mesh to replace the default mesh of the gizmo
  97367. */
  97368. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  97369. 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)");
  97370. };
  97371. return RotationGizmo;
  97372. }(BABYLON.Gizmo));
  97373. BABYLON.RotationGizmo = RotationGizmo;
  97374. })(BABYLON || (BABYLON = {}));
  97375. //# sourceMappingURL=babylon.rotationGizmo.js.map
  97376. var BABYLON;
  97377. (function (BABYLON) {
  97378. /**
  97379. * Gizmo that enables scaling a mesh along 3 axis
  97380. */
  97381. var ScaleGizmo = /** @class */ (function (_super) {
  97382. __extends(ScaleGizmo, _super);
  97383. /**
  97384. * Creates a ScaleGizmo
  97385. * @param gizmoLayer The utility layer the gizmo will be added to
  97386. */
  97387. function ScaleGizmo(gizmoLayer) {
  97388. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97389. var _this = _super.call(this, gizmoLayer) || this;
  97390. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97391. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97392. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97393. // Create uniform scale gizmo
  97394. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  97395. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97396. _this.uniformScaleGizmo.uniformScaling = true;
  97397. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  97398. octahedron.scaling.scaleInPlace(0.007);
  97399. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  97400. _this.attachedMesh = null;
  97401. return _this;
  97402. }
  97403. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  97404. set: function (mesh) {
  97405. if (this.xGizmo) {
  97406. this.xGizmo.attachedMesh = mesh;
  97407. this.yGizmo.attachedMesh = mesh;
  97408. this.zGizmo.attachedMesh = mesh;
  97409. this.uniformScaleGizmo.attachedMesh = mesh;
  97410. }
  97411. },
  97412. enumerable: true,
  97413. configurable: true
  97414. });
  97415. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97416. get: function () {
  97417. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97418. },
  97419. set: function (value) {
  97420. if (this.xGizmo) {
  97421. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97422. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97423. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97424. }
  97425. },
  97426. enumerable: true,
  97427. configurable: true
  97428. });
  97429. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  97430. get: function () {
  97431. return this.xGizmo.snapDistance;
  97432. },
  97433. /**
  97434. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97435. */
  97436. set: function (value) {
  97437. if (this.xGizmo) {
  97438. this.xGizmo.snapDistance = value;
  97439. this.yGizmo.snapDistance = value;
  97440. this.zGizmo.snapDistance = value;
  97441. this.uniformScaleGizmo.snapDistance = value;
  97442. }
  97443. },
  97444. enumerable: true,
  97445. configurable: true
  97446. });
  97447. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  97448. get: function () {
  97449. return this.xGizmo.scaleRatio;
  97450. },
  97451. /**
  97452. * Ratio for the scale of the gizmo (Default: 1)
  97453. */
  97454. set: function (value) {
  97455. if (this.xGizmo) {
  97456. this.xGizmo.scaleRatio = value;
  97457. this.yGizmo.scaleRatio = value;
  97458. this.zGizmo.scaleRatio = value;
  97459. this.uniformScaleGizmo.scaleRatio = value;
  97460. }
  97461. },
  97462. enumerable: true,
  97463. configurable: true
  97464. });
  97465. /**
  97466. * Disposes of the gizmo
  97467. */
  97468. ScaleGizmo.prototype.dispose = function () {
  97469. this.xGizmo.dispose();
  97470. this.yGizmo.dispose();
  97471. this.zGizmo.dispose();
  97472. this.uniformScaleGizmo.dispose();
  97473. };
  97474. return ScaleGizmo;
  97475. }(BABYLON.Gizmo));
  97476. BABYLON.ScaleGizmo = ScaleGizmo;
  97477. })(BABYLON || (BABYLON = {}));
  97478. //# sourceMappingURL=babylon.scaleGizmo.js.map
  97479. var BABYLON;
  97480. (function (BABYLON) {
  97481. /**
  97482. * Bounding box gizmo
  97483. */
  97484. var BoundingBoxGizmo = /** @class */ (function (_super) {
  97485. __extends(BoundingBoxGizmo, _super);
  97486. /**
  97487. * Creates an BoundingBoxGizmo
  97488. * @param gizmoLayer The utility layer the gizmo will be added to
  97489. * @param color The color of the gizmo
  97490. */
  97491. function BoundingBoxGizmo(color, gizmoLayer) {
  97492. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97493. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  97494. var _this = _super.call(this, gizmoLayer) || this;
  97495. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  97496. _this._renderObserver = null;
  97497. _this._pointerObserver = null;
  97498. _this._scaleDragSpeed = 0.2;
  97499. _this._tmpQuaternion = new BABYLON.Quaternion();
  97500. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97501. _this._tmpRotationMatrix = new BABYLON.Matrix();
  97502. /**
  97503. * 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)
  97504. */
  97505. _this.ignoreChildren = false;
  97506. /**
  97507. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  97508. */
  97509. _this.includeChildPredicate = null;
  97510. /**
  97511. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  97512. */
  97513. _this.rotationSphereSize = 0.1;
  97514. /**
  97515. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  97516. */
  97517. _this.scaleBoxSize = 0.1;
  97518. /**
  97519. * 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)
  97520. */
  97521. _this.fixedDragMeshScreenSize = false;
  97522. /**
  97523. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  97524. */
  97525. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  97526. /**
  97527. * Fired when a rotation sphere or scale box is dragged
  97528. */
  97529. _this.onDragStartObservable = new BABYLON.Observable();
  97530. /**
  97531. * Fired when a scale box is dragged
  97532. */
  97533. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  97534. /**
  97535. * Fired when a scale box drag is ended
  97536. */
  97537. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  97538. /**
  97539. * Fired when a rotation sphere is dragged
  97540. */
  97541. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  97542. /**
  97543. * Fired when a rotation sphere drag is ended
  97544. */
  97545. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  97546. /**
  97547. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  97548. */
  97549. _this.scalePivot = null;
  97550. _this._existingMeshScale = new BABYLON.Vector3();
  97551. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  97552. _this._updateScale = false;
  97553. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  97554. // Create Materials
  97555. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97556. coloredMaterial.disableLighting = true;
  97557. coloredMaterial.emissiveColor = color;
  97558. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97559. hoverColoredMaterial.disableLighting = true;
  97560. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97561. // Build bounding box out of lines
  97562. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97563. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  97564. var lines = [];
  97565. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  97566. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  97567. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  97568. 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));
  97569. 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));
  97570. 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));
  97571. 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));
  97572. 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));
  97573. 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));
  97574. 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));
  97575. 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));
  97576. 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));
  97577. lines.forEach(function (l) {
  97578. l.color = color;
  97579. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  97580. l.isPickable = false;
  97581. _this._lineBoundingBox.addChild(l);
  97582. });
  97583. _this._rootMesh.addChild(_this._lineBoundingBox);
  97584. // Create rotation spheres
  97585. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97586. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  97587. var _loop_1 = function (i_1) {
  97588. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  97589. sphere.rotationQuaternion = new BABYLON.Quaternion();
  97590. sphere.material = coloredMaterial;
  97591. // Drag behavior
  97592. _dragBehavior = new BABYLON.PointerDragBehavior({});
  97593. _dragBehavior.moveAttached = false;
  97594. _dragBehavior.updateDragPlane = false;
  97595. sphere.addBehavior(_dragBehavior);
  97596. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  97597. var totalTurnAmountOfDrag = 0;
  97598. _dragBehavior.onDragStartObservable.add(function (event) {
  97599. startingTurnDirection.copyFrom(sphere.forward);
  97600. totalTurnAmountOfDrag = 0;
  97601. });
  97602. _dragBehavior.onDragObservable.add(function (event) {
  97603. _this.onRotationSphereDragObservable.notifyObservers({});
  97604. if (_this.attachedMesh) {
  97605. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97606. var worldDragDirection = startingTurnDirection;
  97607. // Project the world right on to the drag plane
  97608. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  97609. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  97610. // project drag delta on to the resulting drag axis and rotate based on that
  97611. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  97612. // Make rotation relative to size of mesh.
  97613. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97614. // Rotate based on axis
  97615. if (!_this.attachedMesh.rotationQuaternion) {
  97616. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97617. }
  97618. if (!_this._anchorMesh.rotationQuaternion) {
  97619. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  97620. }
  97621. // Do not allow the object to turn more than a full circle
  97622. totalTurnAmountOfDrag += projectDist;
  97623. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  97624. if (i_1 >= 8) {
  97625. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  97626. }
  97627. else if (i_1 >= 4) {
  97628. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  97629. }
  97630. else {
  97631. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  97632. }
  97633. // Rotate around center of bounding box
  97634. _this._anchorMesh.addChild(_this.attachedMesh);
  97635. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  97636. _this._anchorMesh.removeChild(_this.attachedMesh);
  97637. }
  97638. _this.updateBoundingBox();
  97639. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97640. }
  97641. });
  97642. // Selection/deselection
  97643. _dragBehavior.onDragStartObservable.add(function () {
  97644. _this.onDragStartObservable.notifyObservers({});
  97645. _this._selectNode(sphere);
  97646. });
  97647. _dragBehavior.onDragEndObservable.add(function () {
  97648. _this.onRotationSphereDragEndObservable.notifyObservers({});
  97649. _this._selectNode(null);
  97650. });
  97651. this_1._rotateSpheresParent.addChild(sphere);
  97652. };
  97653. var this_1 = this, _dragBehavior;
  97654. for (var i_1 = 0; i_1 < 12; i_1++) {
  97655. _loop_1(i_1);
  97656. }
  97657. _this._rootMesh.addChild(_this._rotateSpheresParent);
  97658. // Create scale cubes
  97659. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97660. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  97661. for (var i = 0; i < 2; i++) {
  97662. for (var j = 0; j < 2; j++) {
  97663. var _loop_2 = function () {
  97664. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  97665. box.material = coloredMaterial;
  97666. // Dragging logic
  97667. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  97668. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97669. _dragBehavior.moveAttached = false;
  97670. box.addBehavior(_dragBehavior);
  97671. _dragBehavior.onDragObservable.add(function (event) {
  97672. _this.onScaleBoxDragObservable.notifyObservers({});
  97673. if (_this.attachedMesh) {
  97674. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97675. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97676. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  97677. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  97678. _this.updateBoundingBox();
  97679. if (_this.scalePivot) {
  97680. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  97681. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  97682. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  97683. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97684. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97685. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  97686. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97687. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  97688. }
  97689. else {
  97690. // Scale from the position of the opposite corner
  97691. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  97692. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97693. }
  97694. _this._anchorMesh.addChild(_this.attachedMesh);
  97695. _this._anchorMesh.scaling.addInPlace(deltaScale);
  97696. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  97697. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  97698. }
  97699. _this._anchorMesh.removeChild(_this.attachedMesh);
  97700. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97701. }
  97702. });
  97703. // Selection/deselection
  97704. _dragBehavior.onDragStartObservable.add(function () {
  97705. _this.onDragStartObservable.notifyObservers({});
  97706. _this._selectNode(box);
  97707. });
  97708. _dragBehavior.onDragEndObservable.add(function () {
  97709. _this.onScaleBoxDragEndObservable.notifyObservers({});
  97710. _this._selectNode(null);
  97711. });
  97712. this_2._scaleBoxesParent.addChild(box);
  97713. };
  97714. var this_2 = this, _dragBehavior;
  97715. for (var k = 0; k < 2; k++) {
  97716. _loop_2();
  97717. }
  97718. }
  97719. }
  97720. _this._rootMesh.addChild(_this._scaleBoxesParent);
  97721. // Hover color change
  97722. var pointerIds = new Array();
  97723. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97724. if (!pointerIds[pointerInfo.event.pointerId]) {
  97725. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  97726. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  97727. pointerIds[pointerInfo.event.pointerId] = mesh;
  97728. mesh.material = hoverColoredMaterial;
  97729. }
  97730. });
  97731. }
  97732. else {
  97733. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  97734. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  97735. delete pointerIds[pointerInfo.event.pointerId];
  97736. }
  97737. }
  97738. });
  97739. // Update bounding box positions
  97740. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  97741. // Only update the bouding box if scaling has changed
  97742. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  97743. _this.updateBoundingBox();
  97744. }
  97745. });
  97746. _this.updateBoundingBox();
  97747. return _this;
  97748. }
  97749. /** @hidden */
  97750. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  97751. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  97752. // Save old pivot and set pivot to 0,0,0
  97753. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  97754. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  97755. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  97756. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  97757. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97758. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97759. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97760. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  97761. }
  97762. }
  97763. BoundingBoxGizmo._PivotCached++;
  97764. };
  97765. /** @hidden */
  97766. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  97767. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  97768. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  97769. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97770. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97771. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97772. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  97773. }
  97774. this._PivotCached--;
  97775. };
  97776. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  97777. if (value) {
  97778. // Reset anchor mesh to match attached mesh's scale
  97779. // This is needed to avoid invalid box/sphere position on first drag
  97780. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  97781. this._anchorMesh.addChild(value);
  97782. this._anchorMesh.removeChild(value);
  97783. BoundingBoxGizmo._RestorePivotPoint(value);
  97784. this.updateBoundingBox();
  97785. }
  97786. };
  97787. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  97788. this._rotateSpheresParent.getChildMeshes()
  97789. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  97790. m.isVisible = (!selectedMesh || m == selectedMesh);
  97791. });
  97792. };
  97793. /**
  97794. * Updates the bounding box information for the Gizmo
  97795. */
  97796. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  97797. if (this.attachedMesh) {
  97798. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  97799. this._update();
  97800. // Rotate based on axis
  97801. if (!this.attachedMesh.rotationQuaternion) {
  97802. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  97803. }
  97804. if (!this._anchorMesh.rotationQuaternion) {
  97805. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  97806. }
  97807. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97808. // Store original position and reset mesh to origin before computing the bounding box
  97809. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97810. this._tmpVector.copyFrom(this.attachedMesh.position);
  97811. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  97812. this.attachedMesh.position.set(0, 0, 0);
  97813. // Update bounding dimensions/positions
  97814. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  97815. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  97816. // Update gizmo to match bounding box scaling and rotation
  97817. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  97818. 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);
  97819. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  97820. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  97821. this._lineBoundingBox.computeWorldMatrix();
  97822. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  97823. // restore position/rotation values
  97824. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  97825. this.attachedMesh.position.copyFrom(this._tmpVector);
  97826. }
  97827. // Update rotation sphere locations
  97828. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  97829. for (var i = 0; i < 3; i++) {
  97830. for (var j = 0; j < 2; j++) {
  97831. for (var k = 0; k < 2; k++) {
  97832. var index = ((i * 4) + (j * 2)) + k;
  97833. if (i == 0) {
  97834. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97835. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97836. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97837. }
  97838. if (i == 1) {
  97839. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  97840. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97841. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97842. }
  97843. if (i == 2) {
  97844. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  97845. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97846. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97847. }
  97848. if (this.fixedDragMeshScreenSize) {
  97849. this._rootMesh.computeWorldMatrix();
  97850. this._rotateSpheresParent.computeWorldMatrix();
  97851. rotateSpheres[index].computeWorldMatrix();
  97852. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97853. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97854. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97855. }
  97856. else {
  97857. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  97858. }
  97859. }
  97860. }
  97861. }
  97862. // Update scale box locations
  97863. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  97864. for (var i = 0; i < 2; i++) {
  97865. for (var j = 0; j < 2; j++) {
  97866. for (var k = 0; k < 2; k++) {
  97867. var index = ((i * 4) + (j * 2)) + k;
  97868. if (scaleBoxes[index]) {
  97869. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97870. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97871. if (this.fixedDragMeshScreenSize) {
  97872. this._rootMesh.computeWorldMatrix();
  97873. this._scaleBoxesParent.computeWorldMatrix();
  97874. scaleBoxes[index].computeWorldMatrix();
  97875. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97876. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97877. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97878. }
  97879. else {
  97880. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  97881. }
  97882. }
  97883. }
  97884. }
  97885. }
  97886. if (this.attachedMesh) {
  97887. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  97888. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  97889. }
  97890. };
  97891. /**
  97892. * Enables rotation on the specified axis and disables rotation on the others
  97893. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  97894. */
  97895. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  97896. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  97897. if (i < 4) {
  97898. m.setEnabled(axis.indexOf("x") != -1);
  97899. }
  97900. else if (i < 8) {
  97901. m.setEnabled(axis.indexOf("y") != -1);
  97902. }
  97903. else {
  97904. m.setEnabled(axis.indexOf("z") != -1);
  97905. }
  97906. });
  97907. };
  97908. /**
  97909. * Disposes of the gizmo
  97910. */
  97911. BoundingBoxGizmo.prototype.dispose = function () {
  97912. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97913. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  97914. this._lineBoundingBox.dispose();
  97915. this._rotateSpheresParent.dispose();
  97916. this._scaleBoxesParent.dispose();
  97917. _super.prototype.dispose.call(this);
  97918. };
  97919. /**
  97920. * 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)
  97921. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  97922. * @returns the bounding box mesh with the passed in mesh as a child
  97923. */
  97924. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  97925. var makeNotPickable = function (root) {
  97926. root.isPickable = false;
  97927. root.getChildMeshes().forEach(function (c) {
  97928. makeNotPickable(c);
  97929. });
  97930. };
  97931. makeNotPickable(mesh);
  97932. // Reset position to get boudning box from origin with no rotation
  97933. if (!mesh.rotationQuaternion) {
  97934. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  97935. }
  97936. var oldPos = mesh.position.clone();
  97937. var oldRot = mesh.rotationQuaternion.clone();
  97938. mesh.rotationQuaternion.set(0, 0, 0, 1);
  97939. mesh.position.set(0, 0, 0);
  97940. // Update bounding dimensions/positions
  97941. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  97942. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  97943. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  97944. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97945. // Restore original positions
  97946. mesh.addChild(box);
  97947. mesh.rotationQuaternion.copyFrom(oldRot);
  97948. mesh.position.copyFrom(oldPos);
  97949. // Reverse parenting
  97950. mesh.removeChild(box);
  97951. box.addChild(mesh);
  97952. box.visibility = 0;
  97953. return box;
  97954. };
  97955. /**
  97956. * CustomMeshes are not supported by this gizmo
  97957. * @param mesh The mesh to replace the default mesh of the gizmo
  97958. */
  97959. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  97960. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  97961. };
  97962. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  97963. // store/remove pivot point should only be applied during their outermost calls
  97964. BoundingBoxGizmo._PivotCached = 0;
  97965. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  97966. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  97967. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  97968. return BoundingBoxGizmo;
  97969. }(BABYLON.Gizmo));
  97970. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  97971. })(BABYLON || (BABYLON = {}));
  97972. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  97973. var BABYLON;
  97974. (function (BABYLON) {
  97975. /**
  97976. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  97977. */
  97978. var GizmoManager = /** @class */ (function () {
  97979. /**
  97980. * Instatiates a gizmo manager
  97981. * @param scene the scene to overlay the gizmos on top of
  97982. */
  97983. function GizmoManager(scene) {
  97984. var _this = this;
  97985. this.scene = scene;
  97986. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  97987. this._pointerObserver = null;
  97988. this._attachedMesh = null;
  97989. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  97990. /**
  97991. * When bounding box gizmo is enabled, this can be used to track drag/end events
  97992. */
  97993. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  97994. /**
  97995. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  97996. */
  97997. this.attachableMeshes = null;
  97998. /**
  97999. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  98000. */
  98001. this.usePointerToAttachGizmos = true;
  98002. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  98003. // Instatiate/dispose gizmos based on pointer actions
  98004. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  98005. if (!_this.usePointerToAttachGizmos) {
  98006. return;
  98007. }
  98008. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98009. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  98010. var node = pointerInfo.pickInfo.pickedMesh;
  98011. if (_this.attachableMeshes == null) {
  98012. // Attach to the most parent node
  98013. while (node && node.parent != null) {
  98014. node = node.parent;
  98015. }
  98016. }
  98017. else {
  98018. // Attach to the parent node that is an attachableMesh
  98019. var found = false;
  98020. _this.attachableMeshes.forEach(function (mesh) {
  98021. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  98022. node = mesh;
  98023. found = true;
  98024. }
  98025. });
  98026. if (!found) {
  98027. node = null;
  98028. }
  98029. }
  98030. if (node instanceof BABYLON.AbstractMesh) {
  98031. _this.attachToMesh(node);
  98032. }
  98033. else {
  98034. _this.attachToMesh(null);
  98035. }
  98036. }
  98037. else {
  98038. _this.attachToMesh(null);
  98039. }
  98040. }
  98041. });
  98042. }
  98043. /**
  98044. * Attaches a set of gizmos to the specified mesh
  98045. * @param mesh The mesh the gizmo's should be attached to
  98046. */
  98047. GizmoManager.prototype.attachToMesh = function (mesh) {
  98048. if (this._attachedMesh) {
  98049. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98050. }
  98051. this._attachedMesh = mesh;
  98052. for (var key in this.gizmos) {
  98053. var gizmo = (this.gizmos[key]);
  98054. if (gizmo && this._gizmosEnabled[key]) {
  98055. gizmo.attachedMesh = mesh;
  98056. }
  98057. }
  98058. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  98059. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98060. }
  98061. };
  98062. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  98063. get: function () {
  98064. return this._gizmosEnabled.positionGizmo;
  98065. },
  98066. /**
  98067. * If the position gizmo is enabled
  98068. */
  98069. set: function (value) {
  98070. if (value) {
  98071. if (!this.gizmos.positionGizmo) {
  98072. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  98073. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98074. }
  98075. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  98076. }
  98077. else if (this.gizmos.positionGizmo) {
  98078. this.gizmos.positionGizmo.attachedMesh = null;
  98079. }
  98080. this._gizmosEnabled.positionGizmo = value;
  98081. },
  98082. enumerable: true,
  98083. configurable: true
  98084. });
  98085. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  98086. get: function () {
  98087. return this._gizmosEnabled.rotationGizmo;
  98088. },
  98089. /**
  98090. * If the rotation gizmo is enabled
  98091. */
  98092. set: function (value) {
  98093. if (value) {
  98094. if (!this.gizmos.rotationGizmo) {
  98095. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  98096. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98097. }
  98098. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  98099. }
  98100. else if (this.gizmos.rotationGizmo) {
  98101. this.gizmos.rotationGizmo.attachedMesh = null;
  98102. }
  98103. this._gizmosEnabled.rotationGizmo = value;
  98104. },
  98105. enumerable: true,
  98106. configurable: true
  98107. });
  98108. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  98109. get: function () {
  98110. return this._gizmosEnabled.scaleGizmo;
  98111. },
  98112. /**
  98113. * If the scale gizmo is enabled
  98114. */
  98115. set: function (value) {
  98116. if (value) {
  98117. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  98118. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  98119. }
  98120. else if (this.gizmos.scaleGizmo) {
  98121. this.gizmos.scaleGizmo.attachedMesh = null;
  98122. }
  98123. this._gizmosEnabled.scaleGizmo = value;
  98124. },
  98125. enumerable: true,
  98126. configurable: true
  98127. });
  98128. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  98129. get: function () {
  98130. return this._gizmosEnabled.boundingBoxGizmo;
  98131. },
  98132. /**
  98133. * If the boundingBox gizmo is enabled
  98134. */
  98135. set: function (value) {
  98136. if (value) {
  98137. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  98138. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  98139. if (this._attachedMesh) {
  98140. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98141. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98142. }
  98143. }
  98144. else if (this.gizmos.boundingBoxGizmo) {
  98145. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  98146. }
  98147. this._gizmosEnabled.boundingBoxGizmo = value;
  98148. },
  98149. enumerable: true,
  98150. configurable: true
  98151. });
  98152. /**
  98153. * Disposes of the gizmo manager
  98154. */
  98155. GizmoManager.prototype.dispose = function () {
  98156. this.scene.onPointerObservable.remove(this._pointerObserver);
  98157. for (var key in this.gizmos) {
  98158. var gizmo = (this.gizmos[key]);
  98159. if (gizmo) {
  98160. gizmo.dispose();
  98161. }
  98162. }
  98163. this.boundingBoxDragBehavior.detach();
  98164. };
  98165. return GizmoManager;
  98166. }());
  98167. BABYLON.GizmoManager = GizmoManager;
  98168. })(BABYLON || (BABYLON = {}));
  98169. //# sourceMappingURL=babylon.gizmoManager.js.map
  98170. var BABYLON;
  98171. (function (BABYLON) {
  98172. /**
  98173. * Defines a target to use with MorphTargetManager
  98174. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98175. */
  98176. var MorphTarget = /** @class */ (function () {
  98177. /**
  98178. * Creates a new MorphTarget
  98179. * @param name defines the name of the target
  98180. * @param influence defines the influence to use
  98181. */
  98182. function MorphTarget(
  98183. /** defines the name of the target */
  98184. name, influence, scene) {
  98185. if (influence === void 0) { influence = 0; }
  98186. if (scene === void 0) { scene = null; }
  98187. this.name = name;
  98188. /**
  98189. * Gets or sets the list of animations
  98190. */
  98191. this.animations = new Array();
  98192. this._positions = null;
  98193. this._normals = null;
  98194. this._tangents = null;
  98195. /**
  98196. * Observable raised when the influence changes
  98197. */
  98198. this.onInfluenceChanged = new BABYLON.Observable();
  98199. this._animationPropertiesOverride = null;
  98200. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98201. this.influence = influence;
  98202. }
  98203. Object.defineProperty(MorphTarget.prototype, "influence", {
  98204. /**
  98205. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  98206. */
  98207. get: function () {
  98208. return this._influence;
  98209. },
  98210. set: function (influence) {
  98211. if (this._influence === influence) {
  98212. return;
  98213. }
  98214. var previous = this._influence;
  98215. this._influence = influence;
  98216. if (this.onInfluenceChanged.hasObservers) {
  98217. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  98218. }
  98219. },
  98220. enumerable: true,
  98221. configurable: true
  98222. });
  98223. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  98224. /**
  98225. * Gets or sets the animation properties override
  98226. */
  98227. get: function () {
  98228. if (!this._animationPropertiesOverride && this._scene) {
  98229. return this._scene.animationPropertiesOverride;
  98230. }
  98231. return this._animationPropertiesOverride;
  98232. },
  98233. set: function (value) {
  98234. this._animationPropertiesOverride = value;
  98235. },
  98236. enumerable: true,
  98237. configurable: true
  98238. });
  98239. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  98240. /**
  98241. * Gets a boolean defining if the target contains position data
  98242. */
  98243. get: function () {
  98244. return !!this._positions;
  98245. },
  98246. enumerable: true,
  98247. configurable: true
  98248. });
  98249. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  98250. /**
  98251. * Gets a boolean defining if the target contains normal data
  98252. */
  98253. get: function () {
  98254. return !!this._normals;
  98255. },
  98256. enumerable: true,
  98257. configurable: true
  98258. });
  98259. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  98260. /**
  98261. * Gets a boolean defining if the target contains tangent data
  98262. */
  98263. get: function () {
  98264. return !!this._tangents;
  98265. },
  98266. enumerable: true,
  98267. configurable: true
  98268. });
  98269. /**
  98270. * Affects position data to this target
  98271. * @param data defines the position data to use
  98272. */
  98273. MorphTarget.prototype.setPositions = function (data) {
  98274. this._positions = data;
  98275. };
  98276. /**
  98277. * Gets the position data stored in this target
  98278. * @returns a FloatArray containing the position data (or null if not present)
  98279. */
  98280. MorphTarget.prototype.getPositions = function () {
  98281. return this._positions;
  98282. };
  98283. /**
  98284. * Affects normal data to this target
  98285. * @param data defines the normal data to use
  98286. */
  98287. MorphTarget.prototype.setNormals = function (data) {
  98288. this._normals = data;
  98289. };
  98290. /**
  98291. * Gets the normal data stored in this target
  98292. * @returns a FloatArray containing the normal data (or null if not present)
  98293. */
  98294. MorphTarget.prototype.getNormals = function () {
  98295. return this._normals;
  98296. };
  98297. /**
  98298. * Affects tangent data to this target
  98299. * @param data defines the tangent data to use
  98300. */
  98301. MorphTarget.prototype.setTangents = function (data) {
  98302. this._tangents = data;
  98303. };
  98304. /**
  98305. * Gets the tangent data stored in this target
  98306. * @returns a FloatArray containing the tangent data (or null if not present)
  98307. */
  98308. MorphTarget.prototype.getTangents = function () {
  98309. return this._tangents;
  98310. };
  98311. /**
  98312. * Serializes the current target into a Serialization object
  98313. * @returns the serialized object
  98314. */
  98315. MorphTarget.prototype.serialize = function () {
  98316. var serializationObject = {};
  98317. serializationObject.name = this.name;
  98318. serializationObject.influence = this.influence;
  98319. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  98320. if (this.hasNormals) {
  98321. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  98322. }
  98323. if (this.hasTangents) {
  98324. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  98325. }
  98326. // Animations
  98327. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  98328. return serializationObject;
  98329. };
  98330. // Statics
  98331. /**
  98332. * Creates a new target from serialized data
  98333. * @param serializationObject defines the serialized data to use
  98334. * @returns a new MorphTarget
  98335. */
  98336. MorphTarget.Parse = function (serializationObject) {
  98337. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  98338. result.setPositions(serializationObject.positions);
  98339. if (serializationObject.normals) {
  98340. result.setNormals(serializationObject.normals);
  98341. }
  98342. if (serializationObject.tangents) {
  98343. result.setTangents(serializationObject.tangents);
  98344. }
  98345. // Animations
  98346. if (serializationObject.animations) {
  98347. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  98348. var parsedAnimation = serializationObject.animations[animationIndex];
  98349. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  98350. }
  98351. }
  98352. return result;
  98353. };
  98354. /**
  98355. * Creates a MorphTarget from mesh data
  98356. * @param mesh defines the source mesh
  98357. * @param name defines the name to use for the new target
  98358. * @param influence defines the influence to attach to the target
  98359. * @returns a new MorphTarget
  98360. */
  98361. MorphTarget.FromMesh = function (mesh, name, influence) {
  98362. if (!name) {
  98363. name = mesh.name;
  98364. }
  98365. var result = new MorphTarget(name, influence, mesh.getScene());
  98366. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98367. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98368. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  98369. }
  98370. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  98371. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  98372. }
  98373. return result;
  98374. };
  98375. return MorphTarget;
  98376. }());
  98377. BABYLON.MorphTarget = MorphTarget;
  98378. })(BABYLON || (BABYLON = {}));
  98379. //# sourceMappingURL=babylon.morphTarget.js.map
  98380. var BABYLON;
  98381. (function (BABYLON) {
  98382. /**
  98383. * This class is used to deform meshes using morphing between different targets
  98384. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98385. */
  98386. var MorphTargetManager = /** @class */ (function () {
  98387. /**
  98388. * Creates a new MorphTargetManager
  98389. * @param scene defines the current scene
  98390. */
  98391. function MorphTargetManager(scene) {
  98392. if (scene === void 0) { scene = null; }
  98393. this._targets = new Array();
  98394. this._targetObservable = new Array();
  98395. this._activeTargets = new BABYLON.SmartArray(16);
  98396. this._supportsNormals = false;
  98397. this._supportsTangents = false;
  98398. this._vertexCount = 0;
  98399. this._uniqueId = 0;
  98400. this._tempInfluences = new Array();
  98401. if (!scene) {
  98402. scene = BABYLON.Engine.LastCreatedScene;
  98403. }
  98404. this._scene = scene;
  98405. if (this._scene) {
  98406. this._scene.morphTargetManagers.push(this);
  98407. this._uniqueId = this._scene.getUniqueId();
  98408. }
  98409. }
  98410. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  98411. /**
  98412. * Gets the unique ID of this manager
  98413. */
  98414. get: function () {
  98415. return this._uniqueId;
  98416. },
  98417. enumerable: true,
  98418. configurable: true
  98419. });
  98420. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  98421. /**
  98422. * Gets the number of vertices handled by this manager
  98423. */
  98424. get: function () {
  98425. return this._vertexCount;
  98426. },
  98427. enumerable: true,
  98428. configurable: true
  98429. });
  98430. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  98431. /**
  98432. * Gets a boolean indicating if this manager supports morphing of normals
  98433. */
  98434. get: function () {
  98435. return this._supportsNormals;
  98436. },
  98437. enumerable: true,
  98438. configurable: true
  98439. });
  98440. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  98441. /**
  98442. * Gets a boolean indicating if this manager supports morphing of tangents
  98443. */
  98444. get: function () {
  98445. return this._supportsTangents;
  98446. },
  98447. enumerable: true,
  98448. configurable: true
  98449. });
  98450. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  98451. /**
  98452. * Gets the number of targets stored in this manager
  98453. */
  98454. get: function () {
  98455. return this._targets.length;
  98456. },
  98457. enumerable: true,
  98458. configurable: true
  98459. });
  98460. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  98461. /**
  98462. * Gets the number of influencers (ie. the number of targets with influences > 0)
  98463. */
  98464. get: function () {
  98465. return this._activeTargets.length;
  98466. },
  98467. enumerable: true,
  98468. configurable: true
  98469. });
  98470. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  98471. /**
  98472. * Gets the list of influences (one per target)
  98473. */
  98474. get: function () {
  98475. return this._influences;
  98476. },
  98477. enumerable: true,
  98478. configurable: true
  98479. });
  98480. /**
  98481. * Gets the active target at specified index. An active target is a target with an influence > 0
  98482. * @param index defines the index to check
  98483. * @returns the requested target
  98484. */
  98485. MorphTargetManager.prototype.getActiveTarget = function (index) {
  98486. return this._activeTargets.data[index];
  98487. };
  98488. /**
  98489. * Gets the target at specified index
  98490. * @param index defines the index to check
  98491. * @returns the requested target
  98492. */
  98493. MorphTargetManager.prototype.getTarget = function (index) {
  98494. return this._targets[index];
  98495. };
  98496. /**
  98497. * Add a new target to this manager
  98498. * @param target defines the target to add
  98499. */
  98500. MorphTargetManager.prototype.addTarget = function (target) {
  98501. var _this = this;
  98502. this._targets.push(target);
  98503. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  98504. _this._syncActiveTargets(needUpdate);
  98505. }));
  98506. this._syncActiveTargets(true);
  98507. };
  98508. /**
  98509. * Removes a target from the manager
  98510. * @param target defines the target to remove
  98511. */
  98512. MorphTargetManager.prototype.removeTarget = function (target) {
  98513. var index = this._targets.indexOf(target);
  98514. if (index >= 0) {
  98515. this._targets.splice(index, 1);
  98516. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  98517. this._syncActiveTargets(true);
  98518. }
  98519. };
  98520. /**
  98521. * Serializes the current manager into a Serialization object
  98522. * @returns the serialized object
  98523. */
  98524. MorphTargetManager.prototype.serialize = function () {
  98525. var serializationObject = {};
  98526. serializationObject.id = this.uniqueId;
  98527. serializationObject.targets = [];
  98528. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98529. var target = _a[_i];
  98530. serializationObject.targets.push(target.serialize());
  98531. }
  98532. return serializationObject;
  98533. };
  98534. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  98535. var influenceCount = 0;
  98536. this._activeTargets.reset();
  98537. this._supportsNormals = true;
  98538. this._supportsTangents = true;
  98539. this._vertexCount = 0;
  98540. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98541. var target = _a[_i];
  98542. this._activeTargets.push(target);
  98543. this._tempInfluences[influenceCount++] = target.influence;
  98544. var positions = target.getPositions();
  98545. if (positions) {
  98546. this._supportsNormals = this._supportsNormals && target.hasNormals;
  98547. this._supportsTangents = this._supportsTangents && target.hasTangents;
  98548. var vertexCount = positions.length / 3;
  98549. if (this._vertexCount === 0) {
  98550. this._vertexCount = vertexCount;
  98551. }
  98552. else if (this._vertexCount !== vertexCount) {
  98553. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  98554. return;
  98555. }
  98556. }
  98557. }
  98558. if (!this._influences || this._influences.length !== influenceCount) {
  98559. this._influences = new Float32Array(influenceCount);
  98560. }
  98561. for (var index = 0; index < influenceCount; index++) {
  98562. this._influences[index] = this._tempInfluences[index];
  98563. }
  98564. if (needUpdate) {
  98565. this.synchronize();
  98566. }
  98567. };
  98568. /**
  98569. * Syncrhonize the targets with all the meshes using this morph target manager
  98570. */
  98571. MorphTargetManager.prototype.synchronize = function () {
  98572. if (!this._scene) {
  98573. return;
  98574. }
  98575. // Flag meshes as dirty to resync with the active targets
  98576. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  98577. var mesh = _a[_i];
  98578. if (mesh.morphTargetManager === this) {
  98579. mesh._syncGeometryWithMorphTargetManager();
  98580. }
  98581. }
  98582. };
  98583. // Statics
  98584. /**
  98585. * Creates a new MorphTargetManager from serialized data
  98586. * @param serializationObject defines the serialized data
  98587. * @param scene defines the hosting scene
  98588. * @returns the new MorphTargetManager
  98589. */
  98590. MorphTargetManager.Parse = function (serializationObject, scene) {
  98591. var result = new MorphTargetManager(scene);
  98592. result._uniqueId = serializationObject.id;
  98593. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  98594. var targetData = _a[_i];
  98595. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  98596. }
  98597. return result;
  98598. };
  98599. return MorphTargetManager;
  98600. }());
  98601. BABYLON.MorphTargetManager = MorphTargetManager;
  98602. })(BABYLON || (BABYLON = {}));
  98603. //# sourceMappingURL=babylon.morphTargetManager.js.map
  98604. var BABYLON;
  98605. (function (BABYLON) {
  98606. var Octree = /** @class */ (function () {
  98607. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  98608. if (maxDepth === void 0) { maxDepth = 2; }
  98609. this.maxDepth = maxDepth;
  98610. this.dynamicContent = new Array();
  98611. this._maxBlockCapacity = maxBlockCapacity || 64;
  98612. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  98613. this._creationFunc = creationFunc;
  98614. }
  98615. // Methods
  98616. Octree.prototype.update = function (worldMin, worldMax, entries) {
  98617. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  98618. };
  98619. Octree.prototype.addMesh = function (entry) {
  98620. for (var index = 0; index < this.blocks.length; index++) {
  98621. var block = this.blocks[index];
  98622. block.addEntry(entry);
  98623. }
  98624. };
  98625. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  98626. this._selectionContent.reset();
  98627. for (var index = 0; index < this.blocks.length; index++) {
  98628. var block = this.blocks[index];
  98629. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  98630. }
  98631. if (allowDuplicate) {
  98632. this._selectionContent.concat(this.dynamicContent);
  98633. }
  98634. else {
  98635. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98636. }
  98637. return this._selectionContent;
  98638. };
  98639. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  98640. this._selectionContent.reset();
  98641. for (var index = 0; index < this.blocks.length; index++) {
  98642. var block = this.blocks[index];
  98643. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  98644. }
  98645. if (allowDuplicate) {
  98646. this._selectionContent.concat(this.dynamicContent);
  98647. }
  98648. else {
  98649. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98650. }
  98651. return this._selectionContent;
  98652. };
  98653. Octree.prototype.intersectsRay = function (ray) {
  98654. this._selectionContent.reset();
  98655. for (var index = 0; index < this.blocks.length; index++) {
  98656. var block = this.blocks[index];
  98657. block.intersectsRay(ray, this._selectionContent);
  98658. }
  98659. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98660. return this._selectionContent;
  98661. };
  98662. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  98663. target.blocks = new Array();
  98664. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  98665. // Segmenting space
  98666. for (var x = 0; x < 2; x++) {
  98667. for (var y = 0; y < 2; y++) {
  98668. for (var z = 0; z < 2; z++) {
  98669. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  98670. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  98671. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  98672. block.addEntries(entries);
  98673. target.blocks.push(block);
  98674. }
  98675. }
  98676. }
  98677. };
  98678. Octree.CreationFuncForMeshes = function (entry, block) {
  98679. var boundingInfo = entry.getBoundingInfo();
  98680. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98681. block.entries.push(entry);
  98682. }
  98683. };
  98684. Octree.CreationFuncForSubMeshes = function (entry, block) {
  98685. var boundingInfo = entry.getBoundingInfo();
  98686. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98687. block.entries.push(entry);
  98688. }
  98689. };
  98690. return Octree;
  98691. }());
  98692. BABYLON.Octree = Octree;
  98693. })(BABYLON || (BABYLON = {}));
  98694. //# sourceMappingURL=babylon.octree.js.map
  98695. var BABYLON;
  98696. (function (BABYLON) {
  98697. /**
  98698. * Class used to store a cell in an octree
  98699. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98700. */
  98701. var OctreeBlock = /** @class */ (function () {
  98702. /**
  98703. * Creates a new block
  98704. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  98705. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  98706. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98707. * @param depth defines the current depth of this block in the octree
  98708. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  98709. * @param creationFunc defines a callback to call when an element is added to the block
  98710. */
  98711. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  98712. /**
  98713. * Gets the content of the current block
  98714. */
  98715. this.entries = new Array();
  98716. this._boundingVectors = new Array();
  98717. this._capacity = capacity;
  98718. this._depth = depth;
  98719. this._maxDepth = maxDepth;
  98720. this._creationFunc = creationFunc;
  98721. this._minPoint = minPoint;
  98722. this._maxPoint = maxPoint;
  98723. this._boundingVectors.push(minPoint.clone());
  98724. this._boundingVectors.push(maxPoint.clone());
  98725. this._boundingVectors.push(minPoint.clone());
  98726. this._boundingVectors[2].x = maxPoint.x;
  98727. this._boundingVectors.push(minPoint.clone());
  98728. this._boundingVectors[3].y = maxPoint.y;
  98729. this._boundingVectors.push(minPoint.clone());
  98730. this._boundingVectors[4].z = maxPoint.z;
  98731. this._boundingVectors.push(maxPoint.clone());
  98732. this._boundingVectors[5].z = minPoint.z;
  98733. this._boundingVectors.push(maxPoint.clone());
  98734. this._boundingVectors[6].x = minPoint.x;
  98735. this._boundingVectors.push(maxPoint.clone());
  98736. this._boundingVectors[7].y = minPoint.y;
  98737. }
  98738. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  98739. // Property
  98740. /**
  98741. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98742. */
  98743. get: function () {
  98744. return this._capacity;
  98745. },
  98746. enumerable: true,
  98747. configurable: true
  98748. });
  98749. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  98750. /**
  98751. * Gets the minimum vector (in world space) of the block's bounding box
  98752. */
  98753. get: function () {
  98754. return this._minPoint;
  98755. },
  98756. enumerable: true,
  98757. configurable: true
  98758. });
  98759. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  98760. /**
  98761. * Gets the maximum vector (in world space) of the block's bounding box
  98762. */
  98763. get: function () {
  98764. return this._maxPoint;
  98765. },
  98766. enumerable: true,
  98767. configurable: true
  98768. });
  98769. // Methods
  98770. /**
  98771. * Add a new element to this block
  98772. * @param entry defines the element to add
  98773. */
  98774. OctreeBlock.prototype.addEntry = function (entry) {
  98775. if (this.blocks) {
  98776. for (var index = 0; index < this.blocks.length; index++) {
  98777. var block = this.blocks[index];
  98778. block.addEntry(entry);
  98779. }
  98780. return;
  98781. }
  98782. this._creationFunc(entry, this);
  98783. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  98784. this.createInnerBlocks();
  98785. }
  98786. };
  98787. /**
  98788. * Add an array of elements to this block
  98789. * @param entries defines the array of elements to add
  98790. */
  98791. OctreeBlock.prototype.addEntries = function (entries) {
  98792. for (var index = 0; index < entries.length; index++) {
  98793. var mesh = entries[index];
  98794. this.addEntry(mesh);
  98795. }
  98796. };
  98797. /**
  98798. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  98799. * @param frustumPlanes defines the frustum planes to test
  98800. * @param selection defines the array to store current content if selection is positive
  98801. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98802. */
  98803. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  98804. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  98805. if (this.blocks) {
  98806. for (var index = 0; index < this.blocks.length; index++) {
  98807. var block = this.blocks[index];
  98808. block.select(frustumPlanes, selection, allowDuplicate);
  98809. }
  98810. return;
  98811. }
  98812. if (allowDuplicate) {
  98813. selection.concat(this.entries);
  98814. }
  98815. else {
  98816. selection.concatWithNoDuplicate(this.entries);
  98817. }
  98818. }
  98819. };
  98820. /**
  98821. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  98822. * @param sphereCenter defines the bounding sphere center
  98823. * @param sphereRadius defines the bounding sphere radius
  98824. * @param selection defines the array to store current content if selection is positive
  98825. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98826. */
  98827. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  98828. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  98829. if (this.blocks) {
  98830. for (var index = 0; index < this.blocks.length; index++) {
  98831. var block = this.blocks[index];
  98832. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  98833. }
  98834. return;
  98835. }
  98836. if (allowDuplicate) {
  98837. selection.concat(this.entries);
  98838. }
  98839. else {
  98840. selection.concatWithNoDuplicate(this.entries);
  98841. }
  98842. }
  98843. };
  98844. /**
  98845. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  98846. * @param ray defines the ray to test with
  98847. * @param selection defines the array to store current content if selection is positive
  98848. */
  98849. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  98850. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  98851. if (this.blocks) {
  98852. for (var index = 0; index < this.blocks.length; index++) {
  98853. var block = this.blocks[index];
  98854. block.intersectsRay(ray, selection);
  98855. }
  98856. return;
  98857. }
  98858. selection.concatWithNoDuplicate(this.entries);
  98859. }
  98860. };
  98861. /**
  98862. * Subdivide the content into child blocks (this block will then be empty)
  98863. */
  98864. OctreeBlock.prototype.createInnerBlocks = function () {
  98865. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  98866. };
  98867. return OctreeBlock;
  98868. }());
  98869. BABYLON.OctreeBlock = OctreeBlock;
  98870. })(BABYLON || (BABYLON = {}));
  98871. //# sourceMappingURL=babylon.octreeBlock.js.map
  98872. var BABYLON;
  98873. (function (BABYLON) {
  98874. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  98875. if (maxCapacity === void 0) { maxCapacity = 64; }
  98876. if (maxDepth === void 0) { maxDepth = 2; }
  98877. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98878. if (!component) {
  98879. component = new OctreeSceneComponent(this);
  98880. this._addComponent(component);
  98881. }
  98882. if (!this._selectionOctree) {
  98883. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  98884. }
  98885. var worldExtends = this.getWorldExtends();
  98886. // Update octree
  98887. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  98888. return this._selectionOctree;
  98889. };
  98890. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  98891. get: function () {
  98892. return this._selectionOctree;
  98893. },
  98894. enumerable: true,
  98895. configurable: true
  98896. });
  98897. /**
  98898. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  98899. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  98900. * @param maxCapacity defines the maximum size of each block (64 by default)
  98901. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  98902. * @returns the new octree
  98903. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  98904. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98905. */
  98906. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  98907. if (maxCapacity === void 0) { maxCapacity = 64; }
  98908. if (maxDepth === void 0) { maxDepth = 2; }
  98909. var scene = this.getScene();
  98910. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98911. if (!component) {
  98912. component = new OctreeSceneComponent(scene);
  98913. scene._addComponent(component);
  98914. }
  98915. if (!this._submeshesOctree) {
  98916. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  98917. }
  98918. this.computeWorldMatrix(true);
  98919. var boundingInfo = this.getBoundingInfo();
  98920. // Update octree
  98921. var bbox = boundingInfo.boundingBox;
  98922. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  98923. return this._submeshesOctree;
  98924. };
  98925. /**
  98926. * Defines the octree scene component responsible to manage any octrees
  98927. * in a given scene.
  98928. */
  98929. var OctreeSceneComponent = /** @class */ (function () {
  98930. /**
  98931. * Creates a new instance of the component for the given scene
  98932. * @param scene Defines the scene to register the component in
  98933. */
  98934. function OctreeSceneComponent(scene) {
  98935. /**
  98936. * The component name helpfull to identify the component in the list of scene components.
  98937. */
  98938. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  98939. /**
  98940. * Indicates if the meshes have been checked to make sure they are isEnabled()
  98941. */
  98942. this.checksIsEnabled = true;
  98943. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  98944. this.scene = scene;
  98945. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  98946. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  98947. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  98948. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  98949. }
  98950. /**
  98951. * Registers the component in a given scene
  98952. */
  98953. OctreeSceneComponent.prototype.register = function () {
  98954. var _this = this;
  98955. this.scene.onMeshRemovedObservable.add(function (mesh) {
  98956. var sceneOctree = _this.scene.selectionOctree;
  98957. if (sceneOctree !== undefined && sceneOctree !== null) {
  98958. var index = sceneOctree.dynamicContent.indexOf(mesh);
  98959. if (index !== -1) {
  98960. sceneOctree.dynamicContent.splice(index, 1);
  98961. }
  98962. }
  98963. });
  98964. this.scene.onMeshImportedObservable.add(function (mesh) {
  98965. var sceneOctree = _this.scene.selectionOctree;
  98966. if (sceneOctree !== undefined && sceneOctree !== null) {
  98967. sceneOctree.addMesh(mesh);
  98968. }
  98969. });
  98970. };
  98971. /**
  98972. * Return the list of active meshes
  98973. * @returns the list of active meshes
  98974. */
  98975. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  98976. if (this.scene._selectionOctree) {
  98977. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  98978. return selection;
  98979. }
  98980. return this.scene._getDefaultMeshCandidates();
  98981. };
  98982. /**
  98983. * Return the list of active sub meshes
  98984. * @param mesh The mesh to get the candidates sub meshes from
  98985. * @returns the list of active sub meshes
  98986. */
  98987. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  98988. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  98989. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  98990. return intersections;
  98991. }
  98992. return this.scene._getDefaultSubMeshCandidates(mesh);
  98993. };
  98994. /**
  98995. * Return the list of sub meshes intersecting with a given local ray
  98996. * @param mesh defines the mesh to find the submesh for
  98997. * @param localRay defines the ray in local space
  98998. * @returns the list of intersecting sub meshes
  98999. */
  99000. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  99001. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  99002. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  99003. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  99004. return intersections;
  99005. }
  99006. return this.scene._getDefaultSubMeshCandidates(mesh);
  99007. };
  99008. /**
  99009. * Return the list of sub meshes colliding with a collider
  99010. * @param mesh defines the mesh to find the submesh for
  99011. * @param collider defines the collider to evaluate the collision against
  99012. * @returns the list of colliding sub meshes
  99013. */
  99014. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  99015. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  99016. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  99017. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  99018. return intersections;
  99019. }
  99020. return this.scene._getDefaultSubMeshCandidates(mesh);
  99021. };
  99022. /**
  99023. * Rebuilds the elements related to this component in case of
  99024. * context lost for instance.
  99025. */
  99026. OctreeSceneComponent.prototype.rebuild = function () {
  99027. // Nothing to do here.
  99028. };
  99029. /**
  99030. * Disposes the component and the associated ressources.
  99031. */
  99032. OctreeSceneComponent.prototype.dispose = function () {
  99033. // Nothing to do here.
  99034. };
  99035. return OctreeSceneComponent;
  99036. }());
  99037. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  99038. })(BABYLON || (BABYLON = {}));
  99039. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  99040. var BABYLON;
  99041. (function (BABYLON) {
  99042. /**
  99043. * Postprocess used to generate anaglyphic rendering
  99044. */
  99045. var AnaglyphPostProcess = /** @class */ (function (_super) {
  99046. __extends(AnaglyphPostProcess, _super);
  99047. /**
  99048. * Creates a new AnaglyphPostProcess
  99049. * @param name defines postprocess name
  99050. * @param options defines creation options or target ratio scale
  99051. * @param rigCameras defines cameras using this postprocess
  99052. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  99053. * @param engine defines hosting engine
  99054. * @param reusable defines if the postprocess will be reused multiple times per frame
  99055. */
  99056. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  99057. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  99058. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99059. _this.onApplyObservable.add(function (effect) {
  99060. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  99061. });
  99062. return _this;
  99063. }
  99064. return AnaglyphPostProcess;
  99065. }(BABYLON.PostProcess));
  99066. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  99067. })(BABYLON || (BABYLON = {}));
  99068. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  99069. var BABYLON;
  99070. (function (BABYLON) {
  99071. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  99072. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99073. });
  99074. /**
  99075. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  99076. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99077. */
  99078. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  99079. __extends(AnaglyphArcRotateCamera, _super);
  99080. /**
  99081. * Creates a new AnaglyphArcRotateCamera
  99082. * @param name defines camera name
  99083. * @param alpha defines alpha angle (in radians)
  99084. * @param beta defines beta angle (in radians)
  99085. * @param radius defines radius
  99086. * @param target defines camera target
  99087. * @param interaxialDistance defines distance between each color axis
  99088. * @param scene defines the hosting scene
  99089. */
  99090. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  99091. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99092. _this.interaxialDistance = interaxialDistance;
  99093. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99094. return _this;
  99095. }
  99096. /**
  99097. * Gets camera class name
  99098. * @returns AnaglyphArcRotateCamera
  99099. */
  99100. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  99101. return "AnaglyphArcRotateCamera";
  99102. };
  99103. return AnaglyphArcRotateCamera;
  99104. }(BABYLON.ArcRotateCamera));
  99105. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  99106. })(BABYLON || (BABYLON = {}));
  99107. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  99108. var BABYLON;
  99109. (function (BABYLON) {
  99110. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  99111. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99112. });
  99113. /**
  99114. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  99115. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99116. */
  99117. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  99118. __extends(AnaglyphFreeCamera, _super);
  99119. /**
  99120. * Creates a new AnaglyphFreeCamera
  99121. * @param name defines camera name
  99122. * @param position defines initial position
  99123. * @param interaxialDistance defines distance between each color axis
  99124. * @param scene defines the hosting scene
  99125. */
  99126. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  99127. var _this = _super.call(this, name, position, scene) || this;
  99128. _this.interaxialDistance = interaxialDistance;
  99129. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99130. return _this;
  99131. }
  99132. /**
  99133. * Gets camera class name
  99134. * @returns AnaglyphFreeCamera
  99135. */
  99136. AnaglyphFreeCamera.prototype.getClassName = function () {
  99137. return "AnaglyphFreeCamera";
  99138. };
  99139. return AnaglyphFreeCamera;
  99140. }(BABYLON.FreeCamera));
  99141. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  99142. })(BABYLON || (BABYLON = {}));
  99143. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  99144. var BABYLON;
  99145. (function (BABYLON) {
  99146. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  99147. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99148. });
  99149. /**
  99150. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  99151. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99152. */
  99153. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  99154. __extends(AnaglyphGamepadCamera, _super);
  99155. /**
  99156. * Creates a new AnaglyphGamepadCamera
  99157. * @param name defines camera name
  99158. * @param position defines initial position
  99159. * @param interaxialDistance defines distance between each color axis
  99160. * @param scene defines the hosting scene
  99161. */
  99162. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  99163. var _this = _super.call(this, name, position, scene) || this;
  99164. _this.interaxialDistance = interaxialDistance;
  99165. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99166. return _this;
  99167. }
  99168. /**
  99169. * Gets camera class name
  99170. * @returns AnaglyphGamepadCamera
  99171. */
  99172. AnaglyphGamepadCamera.prototype.getClassName = function () {
  99173. return "AnaglyphGamepadCamera";
  99174. };
  99175. return AnaglyphGamepadCamera;
  99176. }(BABYLON.GamepadCamera));
  99177. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  99178. })(BABYLON || (BABYLON = {}));
  99179. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  99180. var BABYLON;
  99181. (function (BABYLON) {
  99182. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  99183. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99184. });
  99185. /**
  99186. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  99187. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99188. */
  99189. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  99190. __extends(AnaglyphUniversalCamera, _super);
  99191. /**
  99192. * Creates a new AnaglyphUniversalCamera
  99193. * @param name defines camera name
  99194. * @param position defines initial position
  99195. * @param interaxialDistance defines distance between each color axis
  99196. * @param scene defines the hosting scene
  99197. */
  99198. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  99199. var _this = _super.call(this, name, position, scene) || this;
  99200. _this.interaxialDistance = interaxialDistance;
  99201. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99202. return _this;
  99203. }
  99204. /**
  99205. * Gets camera class name
  99206. * @returns AnaglyphUniversalCamera
  99207. */
  99208. AnaglyphUniversalCamera.prototype.getClassName = function () {
  99209. return "AnaglyphUniversalCamera";
  99210. };
  99211. return AnaglyphUniversalCamera;
  99212. }(BABYLON.UniversalCamera));
  99213. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  99214. })(BABYLON || (BABYLON = {}));
  99215. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  99216. var BABYLON;
  99217. (function (BABYLON) {
  99218. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  99219. __extends(StereoscopicInterlacePostProcess, _super);
  99220. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  99221. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  99222. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99223. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99224. _this.onSizeChangedObservable.add(function () {
  99225. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99226. });
  99227. _this.onApplyObservable.add(function (effect) {
  99228. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  99229. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  99230. });
  99231. return _this;
  99232. }
  99233. return StereoscopicInterlacePostProcess;
  99234. }(BABYLON.PostProcess));
  99235. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  99236. })(BABYLON || (BABYLON = {}));
  99237. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  99238. var BABYLON;
  99239. (function (BABYLON) {
  99240. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  99241. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99242. });
  99243. /**
  99244. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  99245. * @see http://doc.babylonjs.com/features/cameras
  99246. */
  99247. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  99248. __extends(StereoscopicArcRotateCamera, _super);
  99249. /**
  99250. * Creates a new StereoscopicArcRotateCamera
  99251. * @param name defines camera name
  99252. * @param alpha defines alpha angle (in radians)
  99253. * @param beta defines beta angle (in radians)
  99254. * @param radius defines radius
  99255. * @param target defines camera target
  99256. * @param interaxialDistance defines distance between each color axis
  99257. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99258. * @param scene defines the hosting scene
  99259. */
  99260. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  99261. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99262. _this.interaxialDistance = interaxialDistance;
  99263. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99264. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99265. return _this;
  99266. }
  99267. /**
  99268. * Gets camera class name
  99269. * @returns StereoscopicArcRotateCamera
  99270. */
  99271. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  99272. return "StereoscopicArcRotateCamera";
  99273. };
  99274. return StereoscopicArcRotateCamera;
  99275. }(BABYLON.ArcRotateCamera));
  99276. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  99277. })(BABYLON || (BABYLON = {}));
  99278. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  99279. var BABYLON;
  99280. (function (BABYLON) {
  99281. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99282. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99283. });
  99284. /**
  99285. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  99286. * @see http://doc.babylonjs.com/features/cameras
  99287. */
  99288. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  99289. __extends(StereoscopicFreeCamera, _super);
  99290. /**
  99291. * Creates a new StereoscopicFreeCamera
  99292. * @param name defines camera name
  99293. * @param position defines initial position
  99294. * @param interaxialDistance defines distance between each color axis
  99295. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99296. * @param scene defines the hosting scene
  99297. */
  99298. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99299. var _this = _super.call(this, name, position, scene) || this;
  99300. _this.interaxialDistance = interaxialDistance;
  99301. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99302. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99303. return _this;
  99304. }
  99305. /**
  99306. * Gets camera class name
  99307. * @returns StereoscopicFreeCamera
  99308. */
  99309. StereoscopicFreeCamera.prototype.getClassName = function () {
  99310. return "StereoscopicFreeCamera";
  99311. };
  99312. return StereoscopicFreeCamera;
  99313. }(BABYLON.FreeCamera));
  99314. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  99315. })(BABYLON || (BABYLON = {}));
  99316. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  99317. var BABYLON;
  99318. (function (BABYLON) {
  99319. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  99320. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99321. });
  99322. /**
  99323. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  99324. * @see http://doc.babylonjs.com/features/cameras
  99325. */
  99326. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  99327. __extends(StereoscopicGamepadCamera, _super);
  99328. /**
  99329. * Creates a new StereoscopicGamepadCamera
  99330. * @param name defines camera name
  99331. * @param position defines initial position
  99332. * @param interaxialDistance defines distance between each color axis
  99333. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99334. * @param scene defines the hosting scene
  99335. */
  99336. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99337. var _this = _super.call(this, name, position, scene) || this;
  99338. _this.interaxialDistance = interaxialDistance;
  99339. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99340. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99341. return _this;
  99342. }
  99343. /**
  99344. * Gets camera class name
  99345. * @returns StereoscopicGamepadCamera
  99346. */
  99347. StereoscopicGamepadCamera.prototype.getClassName = function () {
  99348. return "StereoscopicGamepadCamera";
  99349. };
  99350. return StereoscopicGamepadCamera;
  99351. }(BABYLON.GamepadCamera));
  99352. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  99353. })(BABYLON || (BABYLON = {}));
  99354. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  99355. var BABYLON;
  99356. (function (BABYLON) {
  99357. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99358. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99359. });
  99360. /**
  99361. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  99362. * @see http://doc.babylonjs.com/features/cameras
  99363. */
  99364. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  99365. __extends(StereoscopicUniversalCamera, _super);
  99366. /**
  99367. * Creates a new StereoscopicUniversalCamera
  99368. * @param name defines camera name
  99369. * @param position defines initial position
  99370. * @param interaxialDistance defines distance between each color axis
  99371. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99372. * @param scene defines the hosting scene
  99373. */
  99374. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99375. var _this = _super.call(this, name, position, scene) || this;
  99376. _this.interaxialDistance = interaxialDistance;
  99377. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99378. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99379. return _this;
  99380. }
  99381. /**
  99382. * Gets camera class name
  99383. * @returns StereoscopicUniversalCamera
  99384. */
  99385. StereoscopicUniversalCamera.prototype.getClassName = function () {
  99386. return "StereoscopicUniversalCamera";
  99387. };
  99388. return StereoscopicUniversalCamera;
  99389. }(BABYLON.UniversalCamera));
  99390. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  99391. })(BABYLON || (BABYLON = {}));
  99392. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  99393. var BABYLON;
  99394. (function (BABYLON) {
  99395. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  99396. __extends(VRDistortionCorrectionPostProcess, _super);
  99397. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  99398. var _this = _super.call(this, name, "vrDistortionCorrection", [
  99399. 'LensCenter',
  99400. 'Scale',
  99401. 'ScaleIn',
  99402. 'HmdWarpParam'
  99403. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  99404. _this._isRightEye = isRightEye;
  99405. _this._distortionFactors = vrMetrics.distortionK;
  99406. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  99407. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  99408. _this.adaptScaleToCurrentViewport = true;
  99409. _this.onSizeChangedObservable.add(function () {
  99410. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  99411. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  99412. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  99413. });
  99414. _this.onApplyObservable.add(function (effect) {
  99415. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  99416. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  99417. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  99418. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  99419. });
  99420. return _this;
  99421. }
  99422. return VRDistortionCorrectionPostProcess;
  99423. }(BABYLON.PostProcess));
  99424. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  99425. })(BABYLON || (BABYLON = {}));
  99426. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  99427. var BABYLON;
  99428. (function (BABYLON) {
  99429. /**
  99430. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  99431. * Screen rotation is taken into account.
  99432. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99433. */
  99434. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  99435. /**
  99436. * Instantiates a new input
  99437. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99438. */
  99439. function FreeCameraDeviceOrientationInput() {
  99440. var _this = this;
  99441. this._screenOrientationAngle = 0;
  99442. this._screenQuaternion = new BABYLON.Quaternion();
  99443. this._alpha = 0;
  99444. this._beta = 0;
  99445. this._gamma = 0;
  99446. this._orientationChanged = function () {
  99447. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  99448. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  99449. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  99450. };
  99451. this._deviceOrientation = function (evt) {
  99452. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  99453. _this._beta = evt.beta !== null ? evt.beta : 0;
  99454. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  99455. };
  99456. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  99457. this._orientationChanged();
  99458. }
  99459. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  99460. /**
  99461. * Define the camera controlled by the input.
  99462. */
  99463. get: function () {
  99464. return this._camera;
  99465. },
  99466. set: function (camera) {
  99467. this._camera = camera;
  99468. if (this._camera != null && !this._camera.rotationQuaternion) {
  99469. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  99470. }
  99471. },
  99472. enumerable: true,
  99473. configurable: true
  99474. });
  99475. /**
  99476. * Attach the input controls to a specific dom element to get the input from.
  99477. * @param element Defines the element the controls should be listened from
  99478. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99479. */
  99480. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99481. window.addEventListener("orientationchange", this._orientationChanged);
  99482. window.addEventListener("deviceorientation", this._deviceOrientation);
  99483. //In certain cases, the attach control is called AFTER orientation was changed,
  99484. //So this is needed.
  99485. this._orientationChanged();
  99486. };
  99487. /**
  99488. * Detach the current controls from the specified dom element.
  99489. * @param element Defines the element to stop listening the inputs from
  99490. */
  99491. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  99492. window.removeEventListener("orientationchange", this._orientationChanged);
  99493. window.removeEventListener("deviceorientation", this._deviceOrientation);
  99494. };
  99495. /**
  99496. * Update the current camera state depending on the inputs that have been used this frame.
  99497. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99498. */
  99499. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  99500. //if no device orientation provided, don't update the rotation.
  99501. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  99502. if (!this._alpha)
  99503. return;
  99504. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  99505. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  99506. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  99507. //Mirror on XY Plane
  99508. this._camera.rotationQuaternion.z *= -1;
  99509. this._camera.rotationQuaternion.w *= -1;
  99510. };
  99511. /**
  99512. * Gets the class name of the current intput.
  99513. * @returns the class name
  99514. */
  99515. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  99516. return "FreeCameraDeviceOrientationInput";
  99517. };
  99518. /**
  99519. * Get the friendly name associated with the input class.
  99520. * @returns the input friendly name
  99521. */
  99522. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  99523. return "deviceOrientation";
  99524. };
  99525. return FreeCameraDeviceOrientationInput;
  99526. }());
  99527. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  99528. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  99529. })(BABYLON || (BABYLON = {}));
  99530. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  99531. var BABYLON;
  99532. (function (BABYLON) {
  99533. /**
  99534. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  99535. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99536. */
  99537. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  99538. /**
  99539. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  99540. */
  99541. function ArcRotateCameraVRDeviceOrientationInput() {
  99542. /**
  99543. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  99544. */
  99545. this.alphaCorrection = 1;
  99546. /**
  99547. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  99548. */
  99549. this.betaCorrection = 1;
  99550. /**
  99551. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  99552. */
  99553. this.gammaCorrection = 1;
  99554. this._alpha = 0;
  99555. this._gamma = 0;
  99556. this._dirty = false;
  99557. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  99558. }
  99559. /**
  99560. * Attach the input controls to a specific dom element to get the input from.
  99561. * @param element Defines the element the controls should be listened from
  99562. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99563. */
  99564. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99565. this.camera.attachControl(element, noPreventDefault);
  99566. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  99567. };
  99568. /** @hidden */
  99569. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  99570. if (evt.alpha !== null) {
  99571. this._alpha = +evt.alpha | 0;
  99572. }
  99573. if (evt.gamma !== null) {
  99574. this._gamma = +evt.gamma | 0;
  99575. }
  99576. this._dirty = true;
  99577. };
  99578. /**
  99579. * Update the current camera state depending on the inputs that have been used this frame.
  99580. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99581. */
  99582. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  99583. if (this._dirty) {
  99584. this._dirty = false;
  99585. if (this._gamma < 0) {
  99586. this._gamma = 180 + this._gamma;
  99587. }
  99588. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  99589. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  99590. }
  99591. };
  99592. /**
  99593. * Detach the current controls from the specified dom element.
  99594. * @param element Defines the element to stop listening the inputs from
  99595. */
  99596. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  99597. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  99598. };
  99599. /**
  99600. * Gets the class name of the current intput.
  99601. * @returns the class name
  99602. */
  99603. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  99604. return "ArcRotateCameraVRDeviceOrientationInput";
  99605. };
  99606. /**
  99607. * Get the friendly name associated with the input class.
  99608. * @returns the input friendly name
  99609. */
  99610. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  99611. return "VRDeviceOrientation";
  99612. };
  99613. return ArcRotateCameraVRDeviceOrientationInput;
  99614. }());
  99615. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  99616. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  99617. })(BABYLON || (BABYLON = {}));
  99618. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  99619. var BABYLON;
  99620. (function (BABYLON) {
  99621. /**
  99622. * This represents all the required metrics to create a VR camera.
  99623. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  99624. */
  99625. var VRCameraMetrics = /** @class */ (function () {
  99626. function VRCameraMetrics() {
  99627. /**
  99628. * Define if the current vr camera should compensate the distortion of the lense or not.
  99629. */
  99630. this.compensateDistortion = true;
  99631. }
  99632. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  99633. /**
  99634. * Gets the rendering aspect ratio based on the provided resolutions.
  99635. */
  99636. get: function () {
  99637. return this.hResolution / (2 * this.vResolution);
  99638. },
  99639. enumerable: true,
  99640. configurable: true
  99641. });
  99642. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  99643. /**
  99644. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  99645. */
  99646. get: function () {
  99647. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  99648. },
  99649. enumerable: true,
  99650. configurable: true
  99651. });
  99652. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  99653. /**
  99654. * @hidden
  99655. */
  99656. get: function () {
  99657. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99658. var h = (4 * meters) / this.hScreenSize;
  99659. return BABYLON.Matrix.Translation(h, 0, 0);
  99660. },
  99661. enumerable: true,
  99662. configurable: true
  99663. });
  99664. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  99665. /**
  99666. * @hidden
  99667. */
  99668. get: function () {
  99669. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99670. var h = (4 * meters) / this.hScreenSize;
  99671. return BABYLON.Matrix.Translation(-h, 0, 0);
  99672. },
  99673. enumerable: true,
  99674. configurable: true
  99675. });
  99676. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  99677. /**
  99678. * @hidden
  99679. */
  99680. get: function () {
  99681. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  99682. },
  99683. enumerable: true,
  99684. configurable: true
  99685. });
  99686. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  99687. /**
  99688. * @hidden
  99689. */
  99690. get: function () {
  99691. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  99692. },
  99693. enumerable: true,
  99694. configurable: true
  99695. });
  99696. /**
  99697. * Get the default VRMetrics based on the most generic setup.
  99698. * @returns the default vr metrics
  99699. */
  99700. VRCameraMetrics.GetDefault = function () {
  99701. var result = new VRCameraMetrics();
  99702. result.hResolution = 1280;
  99703. result.vResolution = 800;
  99704. result.hScreenSize = 0.149759993;
  99705. result.vScreenSize = 0.0935999975;
  99706. result.vScreenCenter = 0.0467999987;
  99707. result.eyeToScreenDistance = 0.0410000011;
  99708. result.lensSeparationDistance = 0.0635000020;
  99709. result.interpupillaryDistance = 0.0640000030;
  99710. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  99711. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  99712. result.postProcessScaleFactor = 1.714605507808412;
  99713. result.lensCenterOffset = 0.151976421;
  99714. return result;
  99715. };
  99716. return VRCameraMetrics;
  99717. }());
  99718. BABYLON.VRCameraMetrics = VRCameraMetrics;
  99719. })(BABYLON || (BABYLON = {}));
  99720. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  99721. var BABYLON;
  99722. (function (BABYLON) {
  99723. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  99724. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99725. });
  99726. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  99727. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99728. });
  99729. /**
  99730. * This represents a WebVR camera.
  99731. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  99732. * @example http://doc.babylonjs.com/how_to/webvr_camera
  99733. */
  99734. var WebVRFreeCamera = /** @class */ (function (_super) {
  99735. __extends(WebVRFreeCamera, _super);
  99736. /**
  99737. * Instantiates a WebVRFreeCamera.
  99738. * @param name The name of the WebVRFreeCamera
  99739. * @param position The starting anchor position for the camera
  99740. * @param scene The scene the camera belongs to
  99741. * @param webVROptions a set of customizable options for the webVRCamera
  99742. */
  99743. function WebVRFreeCamera(name, position, scene, webVROptions) {
  99744. if (webVROptions === void 0) { webVROptions = {}; }
  99745. var _this = _super.call(this, name, position, scene) || this;
  99746. _this.webVROptions = webVROptions;
  99747. /**
  99748. * @hidden
  99749. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  99750. */
  99751. _this._vrDevice = null;
  99752. /**
  99753. * The rawPose of the vrDevice.
  99754. */
  99755. _this.rawPose = null;
  99756. _this._specsVersion = "1.1";
  99757. _this._attached = false;
  99758. _this._descendants = [];
  99759. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  99760. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  99761. /** @hidden */
  99762. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  99763. _this._standingMatrix = null;
  99764. /**
  99765. * Represents device position in babylon space.
  99766. */
  99767. _this.devicePosition = BABYLON.Vector3.Zero();
  99768. /**
  99769. * Represents device rotation in babylon space.
  99770. */
  99771. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  99772. /**
  99773. * The scale of the device to be used when translating from device space to babylon space.
  99774. */
  99775. _this.deviceScaleFactor = 1;
  99776. _this._deviceToWorld = BABYLON.Matrix.Identity();
  99777. _this._worldToDevice = BABYLON.Matrix.Identity();
  99778. /**
  99779. * References to the webVR controllers for the vrDevice.
  99780. */
  99781. _this.controllers = [];
  99782. /**
  99783. * Emits an event when a controller is attached.
  99784. */
  99785. _this.onControllersAttachedObservable = new BABYLON.Observable();
  99786. /**
  99787. * Emits an event when a controller's mesh has been loaded;
  99788. */
  99789. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99790. /**
  99791. * Emits an event when the HMD's pose has been updated.
  99792. */
  99793. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  99794. _this._poseSet = false;
  99795. /**
  99796. * If the rig cameras be used as parent instead of this camera.
  99797. */
  99798. _this.rigParenting = true;
  99799. _this._defaultHeight = undefined;
  99800. _this._htmlElementAttached = null;
  99801. _this._detachIfAttached = function () {
  99802. var vrDisplay = _this.getEngine().getVRDevice();
  99803. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  99804. _this.detachControl(_this._htmlElementAttached);
  99805. }
  99806. };
  99807. _this._workingVector = BABYLON.Vector3.Zero();
  99808. _this._oneVector = BABYLON.Vector3.One();
  99809. _this._workingMatrix = BABYLON.Matrix.Identity();
  99810. _this._tmpMatrix = new BABYLON.Matrix();
  99811. _this._cache.position = BABYLON.Vector3.Zero();
  99812. if (webVROptions.defaultHeight) {
  99813. _this._defaultHeight = webVROptions.defaultHeight;
  99814. _this.position.y = _this._defaultHeight;
  99815. }
  99816. _this.minZ = 0.1;
  99817. //legacy support - the compensation boolean was removed.
  99818. if (arguments.length === 5) {
  99819. _this.webVROptions = arguments[4];
  99820. }
  99821. // default webVR options
  99822. if (_this.webVROptions.trackPosition == undefined) {
  99823. _this.webVROptions.trackPosition = true;
  99824. }
  99825. if (_this.webVROptions.controllerMeshes == undefined) {
  99826. _this.webVROptions.controllerMeshes = true;
  99827. }
  99828. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  99829. _this.webVROptions.defaultLightingOnControllers = true;
  99830. }
  99831. _this.rotationQuaternion = new BABYLON.Quaternion();
  99832. if (_this.webVROptions && _this.webVROptions.positionScale) {
  99833. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  99834. }
  99835. //enable VR
  99836. var engine = _this.getEngine();
  99837. _this._onVREnabled = function (success) { if (success) {
  99838. _this.initControllers();
  99839. } };
  99840. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  99841. engine.initWebVR().add(function (event) {
  99842. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  99843. return;
  99844. }
  99845. _this._vrDevice = event.vrDisplay;
  99846. //reset the rig parameters.
  99847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  99848. if (_this._attached) {
  99849. _this.getEngine().enableVR();
  99850. }
  99851. });
  99852. if (typeof (VRFrameData) !== "undefined")
  99853. _this._frameData = new VRFrameData();
  99854. /**
  99855. * The idea behind the following lines:
  99856. * objects that have the camera as parent should actually have the rig cameras as a parent.
  99857. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  99858. * the second will not show it correctly.
  99859. *
  99860. * To solve this - each object that has the camera as parent will be added to a protected array.
  99861. * When the rig camera renders, it will take this array and set all of those to be its children.
  99862. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  99863. * Amazing!
  99864. */
  99865. scene.onBeforeCameraRenderObservable.add(function (camera) {
  99866. if (camera.parent === _this && _this.rigParenting) {
  99867. _this._descendants = _this.getDescendants(true, function (n) {
  99868. // don't take the cameras or the controllers!
  99869. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  99870. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  99871. return !isController && !isRigCamera;
  99872. });
  99873. _this._descendants.forEach(function (node) {
  99874. node.parent = camera;
  99875. });
  99876. }
  99877. });
  99878. scene.onAfterCameraRenderObservable.add(function (camera) {
  99879. if (camera.parent === _this && _this.rigParenting) {
  99880. _this._descendants.forEach(function (node) {
  99881. node.parent = _this;
  99882. });
  99883. }
  99884. });
  99885. return _this;
  99886. }
  99887. /**
  99888. * Gets the device distance from the ground in meters.
  99889. * @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.
  99890. */
  99891. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  99892. if (this._standingMatrix) {
  99893. // Add standing matrix offset to get real offset from ground in room
  99894. this._standingMatrix.getTranslationToRef(this._workingVector);
  99895. return this._deviceRoomPosition.y + this._workingVector.y;
  99896. }
  99897. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  99898. return this._defaultHeight || 0;
  99899. };
  99900. /**
  99901. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99902. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  99903. */
  99904. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  99905. var _this = this;
  99906. if (callback === void 0) { callback = function (bool) { }; }
  99907. // Use standing matrix if available
  99908. this.getEngine().initWebVRAsync().then(function (result) {
  99909. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  99910. callback(false);
  99911. }
  99912. else {
  99913. _this._standingMatrix = new BABYLON.Matrix();
  99914. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  99915. if (!_this.getScene().useRightHandedSystem) {
  99916. [2, 6, 8, 9, 14].forEach(function (num) {
  99917. if (_this._standingMatrix) {
  99918. _this._standingMatrix.m[num] *= -1;
  99919. }
  99920. });
  99921. }
  99922. callback(true);
  99923. }
  99924. });
  99925. };
  99926. /**
  99927. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99928. * @returns A promise with a boolean set to if the standing matrix is supported.
  99929. */
  99930. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  99931. var _this = this;
  99932. return new Promise(function (res, rej) {
  99933. _this.useStandingMatrix(function (supported) {
  99934. res(supported);
  99935. });
  99936. });
  99937. };
  99938. /**
  99939. * Disposes the camera
  99940. */
  99941. WebVRFreeCamera.prototype.dispose = function () {
  99942. this._detachIfAttached();
  99943. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  99944. if (this._updateCacheWhenTrackingDisabledObserver) {
  99945. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  99946. }
  99947. _super.prototype.dispose.call(this);
  99948. };
  99949. /**
  99950. * Gets a vrController by name.
  99951. * @param name The name of the controller to retreive
  99952. * @returns the controller matching the name specified or null if not found
  99953. */
  99954. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  99955. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  99956. var gp = _a[_i];
  99957. if (gp.hand === name) {
  99958. return gp;
  99959. }
  99960. }
  99961. return null;
  99962. };
  99963. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  99964. /**
  99965. * The controller corrisponding to the users left hand.
  99966. */
  99967. get: function () {
  99968. if (!this._leftController) {
  99969. this._leftController = this.getControllerByName("left");
  99970. }
  99971. return this._leftController;
  99972. },
  99973. enumerable: true,
  99974. configurable: true
  99975. });
  99976. ;
  99977. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  99978. /**
  99979. * The controller corrisponding to the users right hand.
  99980. */
  99981. get: function () {
  99982. if (!this._rightController) {
  99983. this._rightController = this.getControllerByName("right");
  99984. }
  99985. return this._rightController;
  99986. },
  99987. enumerable: true,
  99988. configurable: true
  99989. });
  99990. ;
  99991. /**
  99992. * Casts a ray forward from the vrCamera's gaze.
  99993. * @param length Length of the ray (default: 100)
  99994. * @returns the ray corrisponding to the gaze
  99995. */
  99996. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  99997. if (length === void 0) { length = 100; }
  99998. if (this.leftCamera) {
  99999. // Use left eye to avoid computation to compute center on every call
  100000. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  100001. }
  100002. else {
  100003. return _super.prototype.getForwardRay.call(this, length);
  100004. }
  100005. };
  100006. /**
  100007. * @hidden
  100008. * Updates the camera based on device's frame data
  100009. */
  100010. WebVRFreeCamera.prototype._checkInputs = function () {
  100011. if (this._vrDevice && this._vrDevice.isPresenting) {
  100012. this._vrDevice.getFrameData(this._frameData);
  100013. this.updateFromDevice(this._frameData.pose);
  100014. }
  100015. _super.prototype._checkInputs.call(this);
  100016. };
  100017. /**
  100018. * Updates the poseControlled values based on the input device pose.
  100019. * @param poseData Pose coming from the device
  100020. */
  100021. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  100022. if (poseData && poseData.orientation) {
  100023. this.rawPose = poseData;
  100024. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  100025. if (this.getScene().useRightHandedSystem) {
  100026. this._deviceRoomRotationQuaternion.z *= -1;
  100027. this._deviceRoomRotationQuaternion.w *= -1;
  100028. }
  100029. if (this.webVROptions.trackPosition && this.rawPose.position) {
  100030. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  100031. if (this.getScene().useRightHandedSystem) {
  100032. this._deviceRoomPosition.z *= -1;
  100033. }
  100034. }
  100035. this._poseSet = true;
  100036. }
  100037. };
  100038. /**
  100039. * WebVR's attach control will start broadcasting frames to the device.
  100040. * Note that in certain browsers (chrome for example) this function must be called
  100041. * within a user-interaction callback. Example:
  100042. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  100043. *
  100044. * @param element html element to attach the vrDevice to
  100045. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  100046. */
  100047. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  100048. _super.prototype.attachControl.call(this, element, noPreventDefault);
  100049. this._attached = true;
  100050. this._htmlElementAttached = element;
  100051. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  100052. if (this._vrDevice) {
  100053. this.getEngine().enableVR();
  100054. }
  100055. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100056. };
  100057. /**
  100058. * Detaches the camera from the html element and disables VR
  100059. *
  100060. * @param element html element to detach from
  100061. */
  100062. WebVRFreeCamera.prototype.detachControl = function (element) {
  100063. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  100064. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  100065. _super.prototype.detachControl.call(this, element);
  100066. this._attached = false;
  100067. this.getEngine().disableVR();
  100068. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100069. };
  100070. /**
  100071. * @returns the name of this class
  100072. */
  100073. WebVRFreeCamera.prototype.getClassName = function () {
  100074. return "WebVRFreeCamera";
  100075. };
  100076. /**
  100077. * Calls resetPose on the vrDisplay
  100078. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  100079. */
  100080. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  100081. //uses the vrDisplay's "resetPose()".
  100082. //pitch and roll won't be affected.
  100083. this._vrDevice.resetPose();
  100084. };
  100085. /**
  100086. * @hidden
  100087. * Updates the rig cameras (left and right eye)
  100088. */
  100089. WebVRFreeCamera.prototype._updateRigCameras = function () {
  100090. var camLeft = this._rigCameras[0];
  100091. var camRight = this._rigCameras[1];
  100092. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100093. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100094. camLeft.position.copyFrom(this._deviceRoomPosition);
  100095. camRight.position.copyFrom(this._deviceRoomPosition);
  100096. };
  100097. // Remove translation from 6dof headset if trackposition is set to false
  100098. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  100099. if (isViewMatrix === void 0) { isViewMatrix = false; }
  100100. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  100101. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  100102. if (!isViewMatrix) {
  100103. this._tmpMatrix.invert();
  100104. }
  100105. this._tmpMatrix.multiplyToRef(matrix, matrix);
  100106. }
  100107. };
  100108. /**
  100109. * @hidden
  100110. * Updates the cached values of the camera
  100111. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  100112. */
  100113. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  100114. var _this = this;
  100115. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  100116. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  100117. if (!this.updateCacheCalled) {
  100118. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  100119. this.updateCacheCalled = true;
  100120. this.update();
  100121. }
  100122. // Set working vector to the device position in room space rotated by the new rotation
  100123. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  100124. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  100125. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  100126. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  100127. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  100128. // Add translation from anchor position
  100129. this._deviceToWorld.getTranslationToRef(this._workingVector);
  100130. this._workingVector.addInPlace(this.position);
  100131. this._workingVector.subtractInPlace(this._cache.position);
  100132. this._deviceToWorld.setTranslation(this._workingVector);
  100133. // Set an inverted matrix to be used when updating the camera
  100134. this._deviceToWorld.invertToRef(this._worldToDevice);
  100135. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  100136. this.controllers.forEach(function (controller) {
  100137. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  100138. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  100139. controller.update();
  100140. });
  100141. }
  100142. if (!ignoreParentClass) {
  100143. _super.prototype._updateCache.call(this);
  100144. }
  100145. this.updateCacheCalled = false;
  100146. };
  100147. /**
  100148. * @hidden
  100149. * Get current device position in babylon world
  100150. */
  100151. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  100152. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  100153. };
  100154. /**
  100155. * Updates the current device position and rotation in the babylon world
  100156. */
  100157. WebVRFreeCamera.prototype.update = function () {
  100158. this._computeDevicePosition();
  100159. // Get current device rotation in babylon world
  100160. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  100161. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  100162. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  100163. if (this._poseSet) {
  100164. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  100165. }
  100166. _super.prototype.update.call(this);
  100167. };
  100168. /**
  100169. * @hidden
  100170. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  100171. * @returns an identity matrix
  100172. */
  100173. WebVRFreeCamera.prototype._getViewMatrix = function () {
  100174. return BABYLON.Matrix.Identity();
  100175. };
  100176. /**
  100177. * This function is called by the two RIG cameras.
  100178. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  100179. */
  100180. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  100181. var _this = this;
  100182. // Update the parent camera prior to using a child camera to avoid desynchronization
  100183. var parentCamera = this._cameraRigParams["parentCamera"];
  100184. parentCamera._updateCache();
  100185. //WebVR 1.1
  100186. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  100187. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  100188. if (!this.getScene().useRightHandedSystem) {
  100189. [2, 6, 8, 9, 14].forEach(function (num) {
  100190. _this._webvrViewMatrix.m[num] *= -1;
  100191. });
  100192. }
  100193. // update the camera rotation matrix
  100194. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  100195. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  100196. // Computing target and final matrix
  100197. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  100198. // should the view matrix be updated with scale and position offset?
  100199. if (parentCamera.deviceScaleFactor !== 1) {
  100200. this._webvrViewMatrix.invert();
  100201. // scale the position, if set
  100202. if (parentCamera.deviceScaleFactor) {
  100203. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  100204. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  100205. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  100206. }
  100207. this._webvrViewMatrix.invert();
  100208. }
  100209. // Remove translation from 6dof headset if trackposition is set to false
  100210. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  100211. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  100212. // Compute global position
  100213. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  100214. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  100215. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  100216. this._workingMatrix.getTranslationToRef(this._globalPosition);
  100217. this._markSyncedWithParent();
  100218. return this._webvrViewMatrix;
  100219. };
  100220. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  100221. var _this = this;
  100222. var parentCamera = this.parent;
  100223. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  100224. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  100225. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  100226. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  100227. //babylon compatible matrix
  100228. if (!this.getScene().useRightHandedSystem) {
  100229. [8, 9, 10, 11].forEach(function (num) {
  100230. _this._projectionMatrix.m[num] *= -1;
  100231. });
  100232. }
  100233. return this._projectionMatrix;
  100234. };
  100235. /**
  100236. * Initializes the controllers and their meshes
  100237. */
  100238. WebVRFreeCamera.prototype.initControllers = function () {
  100239. var _this = this;
  100240. this.controllers = [];
  100241. var manager = this.getScene().gamepadManager;
  100242. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  100243. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100244. var webVrController = gamepad;
  100245. if (webVrController.defaultModel) {
  100246. webVrController.defaultModel.setEnabled(false);
  100247. }
  100248. if (webVrController.hand === "right") {
  100249. _this._rightController = null;
  100250. }
  100251. if (webVrController.hand === "left") {
  100252. _this._leftController = null;
  100253. }
  100254. var controllerIndex = _this.controllers.indexOf(webVrController);
  100255. if (controllerIndex !== -1) {
  100256. _this.controllers.splice(controllerIndex, 1);
  100257. }
  100258. }
  100259. });
  100260. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  100261. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100262. var webVrController_1 = gamepad;
  100263. if (!_this.webVROptions.trackPosition) {
  100264. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  100265. // Cache must be updated before rendering controllers to avoid them being one frame behind
  100266. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  100267. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  100268. _this._updateCache();
  100269. });
  100270. }
  100271. }
  100272. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  100273. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  100274. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  100275. if (_this.webVROptions.controllerMeshes) {
  100276. if (webVrController_1.defaultModel) {
  100277. webVrController_1.defaultModel.setEnabled(true);
  100278. }
  100279. else {
  100280. // Load the meshes
  100281. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  100282. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  100283. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  100284. if (_this.webVROptions.defaultLightingOnControllers) {
  100285. if (!_this._lightOnControllers) {
  100286. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  100287. }
  100288. var activateLightOnSubMeshes_1 = function (mesh, light) {
  100289. var children = mesh.getChildren();
  100290. if (children && children.length !== 0) {
  100291. children.forEach(function (mesh) {
  100292. light.includedOnlyMeshes.push(mesh);
  100293. activateLightOnSubMeshes_1(mesh, light);
  100294. });
  100295. }
  100296. };
  100297. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  100298. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  100299. }
  100300. });
  100301. }
  100302. }
  100303. webVrController_1.attachToPoseControlledCamera(_this);
  100304. // since this is async - sanity check. Is the controller already stored?
  100305. if (_this.controllers.indexOf(webVrController_1) === -1) {
  100306. //add to the controllers array
  100307. _this.controllers.push(webVrController_1);
  100308. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  100309. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  100310. // So we're overriding setting left & right manually to be sure
  100311. var firstViveWandDetected = false;
  100312. for (var i = 0; i < _this.controllers.length; i++) {
  100313. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100314. if (!firstViveWandDetected) {
  100315. firstViveWandDetected = true;
  100316. _this.controllers[i].hand = "left";
  100317. }
  100318. else {
  100319. _this.controllers[i].hand = "right";
  100320. }
  100321. }
  100322. }
  100323. //did we find enough controllers? Great! let the developer know.
  100324. if (_this.controllers.length >= 2) {
  100325. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  100326. }
  100327. }
  100328. }
  100329. });
  100330. };
  100331. return WebVRFreeCamera;
  100332. }(BABYLON.FreeCamera));
  100333. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  100334. })(BABYLON || (BABYLON = {}));
  100335. //# sourceMappingURL=babylon.webVRCamera.js.map
  100336. var BABYLON;
  100337. (function (BABYLON) {
  100338. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  100339. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  100340. });
  100341. // We're mainly based on the logic defined into the FreeCamera code
  100342. /**
  100343. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  100344. * being tilted forward or back and left or right.
  100345. */
  100346. var DeviceOrientationCamera = /** @class */ (function (_super) {
  100347. __extends(DeviceOrientationCamera, _super);
  100348. /**
  100349. * Creates a new device orientation camera
  100350. * @param name The name of the camera
  100351. * @param position The start position camera
  100352. * @param scene The scene the camera belongs to
  100353. */
  100354. function DeviceOrientationCamera(name, position, scene) {
  100355. var _this = _super.call(this, name, position, scene) || this;
  100356. _this._quaternionCache = new BABYLON.Quaternion();
  100357. _this.inputs.addDeviceOrientation();
  100358. return _this;
  100359. }
  100360. /**
  100361. * Gets the current instance class name ("DeviceOrientationCamera").
  100362. * This helps avoiding instanceof at run time.
  100363. * @returns the class name
  100364. */
  100365. DeviceOrientationCamera.prototype.getClassName = function () {
  100366. return "DeviceOrientationCamera";
  100367. };
  100368. /**
  100369. * @hidden
  100370. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  100371. */
  100372. DeviceOrientationCamera.prototype._checkInputs = function () {
  100373. _super.prototype._checkInputs.call(this);
  100374. this._quaternionCache.copyFrom(this.rotationQuaternion);
  100375. if (this._initialQuaternion) {
  100376. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100377. }
  100378. };
  100379. /**
  100380. * Reset the camera to its default orientation on the specified axis only.
  100381. * @param axis The axis to reset
  100382. */
  100383. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  100384. var _this = this;
  100385. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  100386. //can only work if this camera has a rotation quaternion already.
  100387. if (!this.rotationQuaternion)
  100388. return;
  100389. if (!this._initialQuaternion) {
  100390. this._initialQuaternion = new BABYLON.Quaternion();
  100391. }
  100392. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  100393. ['x', 'y', 'z'].forEach(function (axisName) {
  100394. if (!axis[axisName]) {
  100395. _this._initialQuaternion[axisName] = 0;
  100396. }
  100397. else {
  100398. _this._initialQuaternion[axisName] *= -1;
  100399. }
  100400. });
  100401. this._initialQuaternion.normalize();
  100402. //force rotation update
  100403. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100404. };
  100405. return DeviceOrientationCamera;
  100406. }(BABYLON.FreeCamera));
  100407. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  100408. })(BABYLON || (BABYLON = {}));
  100409. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  100410. var BABYLON;
  100411. (function (BABYLON) {
  100412. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100413. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100414. });
  100415. /**
  100416. * Camera used to simulate VR rendering (based on FreeCamera)
  100417. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100418. */
  100419. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  100420. __extends(VRDeviceOrientationFreeCamera, _super);
  100421. /**
  100422. * Creates a new VRDeviceOrientationFreeCamera
  100423. * @param name defines camera name
  100424. * @param position defines the start position of the camera
  100425. * @param scene defines the scene the camera belongs to
  100426. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100427. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100428. */
  100429. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100430. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100431. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100432. var _this = _super.call(this, name, position, scene) || this;
  100433. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100434. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100435. return _this;
  100436. }
  100437. /**
  100438. * Gets camera class name
  100439. * @returns VRDeviceOrientationFreeCamera
  100440. */
  100441. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  100442. return "VRDeviceOrientationFreeCamera";
  100443. };
  100444. return VRDeviceOrientationFreeCamera;
  100445. }(BABYLON.DeviceOrientationCamera));
  100446. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  100447. })(BABYLON || (BABYLON = {}));
  100448. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  100449. var BABYLON;
  100450. (function (BABYLON) {
  100451. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100452. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  100453. });
  100454. /**
  100455. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  100456. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100457. */
  100458. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  100459. __extends(VRDeviceOrientationArcRotateCamera, _super);
  100460. /**
  100461. * Creates a new VRDeviceOrientationArcRotateCamera
  100462. * @param name defines camera name
  100463. * @param alpha defines the camera rotation along the logitudinal axis
  100464. * @param beta defines the camera rotation along the latitudinal axis
  100465. * @param radius defines the camera distance from its target
  100466. * @param target defines the camera target
  100467. * @param scene defines the scene the camera belongs to
  100468. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100469. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100470. */
  100471. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  100472. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100473. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100474. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100475. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100476. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100477. _this.inputs.addVRDeviceOrientation();
  100478. return _this;
  100479. }
  100480. /**
  100481. * Gets camera class name
  100482. * @returns VRDeviceOrientationArcRotateCamera
  100483. */
  100484. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  100485. return "VRDeviceOrientationArcRotateCamera";
  100486. };
  100487. return VRDeviceOrientationArcRotateCamera;
  100488. }(BABYLON.ArcRotateCamera));
  100489. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  100490. })(BABYLON || (BABYLON = {}));
  100491. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  100492. var BABYLON;
  100493. (function (BABYLON) {
  100494. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  100495. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  100496. });
  100497. /**
  100498. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  100499. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100500. */
  100501. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  100502. __extends(VRDeviceOrientationGamepadCamera, _super);
  100503. /**
  100504. * Creates a new VRDeviceOrientationGamepadCamera
  100505. * @param name defines camera name
  100506. * @param position defines the start position of the camera
  100507. * @param scene defines the scene the camera belongs to
  100508. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100509. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100510. */
  100511. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100512. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100513. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100514. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  100515. _this.inputs.addGamepad();
  100516. return _this;
  100517. }
  100518. /**
  100519. * Gets camera class name
  100520. * @returns VRDeviceOrientationGamepadCamera
  100521. */
  100522. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  100523. return "VRDeviceOrientationGamepadCamera";
  100524. };
  100525. return VRDeviceOrientationGamepadCamera;
  100526. }(BABYLON.VRDeviceOrientationFreeCamera));
  100527. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  100528. })(BABYLON || (BABYLON = {}));
  100529. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  100530. var BABYLON;
  100531. (function (BABYLON) {
  100532. var VRExperienceHelperGazer = /** @class */ (function () {
  100533. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  100534. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  100535. this.scene = scene;
  100536. /** @hidden */
  100537. this._pointerDownOnMeshAsked = false;
  100538. /** @hidden */
  100539. this._isActionableMesh = false;
  100540. /** @hidden */
  100541. this._teleportationRequestInitiated = false;
  100542. /** @hidden */
  100543. this._teleportationBackRequestInitiated = false;
  100544. /** @hidden */
  100545. this._rotationRightAsked = false;
  100546. /** @hidden */
  100547. this._rotationLeftAsked = false;
  100548. /** @hidden */
  100549. this._dpadPressed = true;
  100550. /** @hidden */
  100551. this._activePointer = false;
  100552. this._id = VRExperienceHelperGazer._idCounter++;
  100553. // Gaze tracker
  100554. if (!gazeTrackerToClone) {
  100555. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  100556. this._gazeTracker.bakeCurrentTransformIntoVertices();
  100557. this._gazeTracker.isPickable = false;
  100558. this._gazeTracker.isVisible = false;
  100559. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  100560. targetMat.specularColor = BABYLON.Color3.Black();
  100561. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100562. targetMat.backFaceCulling = false;
  100563. this._gazeTracker.material = targetMat;
  100564. }
  100565. else {
  100566. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  100567. }
  100568. }
  100569. /** @hidden */
  100570. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  100571. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  100572. };
  100573. /** @hidden */
  100574. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  100575. this._pointerDownOnMeshAsked = true;
  100576. if (this._currentHit) {
  100577. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  100578. }
  100579. };
  100580. /** @hidden */
  100581. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  100582. if (this._currentHit) {
  100583. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  100584. }
  100585. this._pointerDownOnMeshAsked = false;
  100586. };
  100587. /** @hidden */
  100588. VRExperienceHelperGazer.prototype._activatePointer = function () {
  100589. this._activePointer = true;
  100590. };
  100591. /** @hidden */
  100592. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  100593. this._activePointer = false;
  100594. };
  100595. /** @hidden */
  100596. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  100597. if (distance === void 0) { distance = 100; }
  100598. };
  100599. VRExperienceHelperGazer.prototype.dispose = function () {
  100600. this._interactionsEnabled = false;
  100601. this._teleportationEnabled = false;
  100602. if (this._gazeTracker) {
  100603. this._gazeTracker.dispose();
  100604. }
  100605. };
  100606. VRExperienceHelperGazer._idCounter = 0;
  100607. return VRExperienceHelperGazer;
  100608. }());
  100609. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  100610. __extends(VRExperienceHelperControllerGazer, _super);
  100611. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  100612. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  100613. _this.webVRController = webVRController;
  100614. // Laser pointer
  100615. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  100616. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  100617. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100618. laserPointerMaterial.alpha = 0.6;
  100619. _this._laserPointer.material = laserPointerMaterial;
  100620. _this._laserPointer.rotation.x = Math.PI / 2;
  100621. _this._laserPointer.position.z = -0.5;
  100622. _this._laserPointer.isVisible = false;
  100623. _this._laserPointer.isPickable = false;
  100624. if (!webVRController.mesh) {
  100625. // Create an empty mesh that is used prior to loading the high quality model
  100626. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  100627. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  100628. preloadPointerPose.rotation.x = -0.7;
  100629. preloadMesh.addChild(preloadPointerPose);
  100630. webVRController.attachToMesh(preloadMesh);
  100631. }
  100632. _this._setLaserPointerParent(webVRController.mesh);
  100633. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  100634. _this._setLaserPointerParent(mesh);
  100635. });
  100636. return _this;
  100637. }
  100638. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  100639. return this.webVRController.getForwardRay(length);
  100640. };
  100641. /** @hidden */
  100642. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  100643. _super.prototype._activatePointer.call(this);
  100644. this._laserPointer.isVisible = true;
  100645. };
  100646. /** @hidden */
  100647. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  100648. _super.prototype._deactivatePointer.call(this);
  100649. this._laserPointer.isVisible = false;
  100650. };
  100651. /** @hidden */
  100652. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  100653. this._laserPointer.material.emissiveColor = color;
  100654. };
  100655. /** @hidden */
  100656. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  100657. var makeNotPick = function (root) {
  100658. root.isPickable = false;
  100659. root.getChildMeshes().forEach(function (c) {
  100660. makeNotPick(c);
  100661. });
  100662. };
  100663. makeNotPick(mesh);
  100664. var childMeshes = mesh.getChildMeshes();
  100665. this.webVRController._pointingPoseNode = null;
  100666. for (var i = 0; i < childMeshes.length; i++) {
  100667. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  100668. mesh = childMeshes[i];
  100669. this.webVRController._pointingPoseNode = mesh;
  100670. break;
  100671. }
  100672. }
  100673. this._laserPointer.parent = mesh;
  100674. };
  100675. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  100676. if (distance === void 0) { distance = 100; }
  100677. this._laserPointer.scaling.y = distance;
  100678. this._laserPointer.position.z = -distance / 2;
  100679. };
  100680. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  100681. _super.prototype.dispose.call(this);
  100682. this._laserPointer.dispose();
  100683. if (this._meshAttachedObserver) {
  100684. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  100685. }
  100686. };
  100687. return VRExperienceHelperControllerGazer;
  100688. }(VRExperienceHelperGazer));
  100689. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  100690. __extends(VRExperienceHelperCameraGazer, _super);
  100691. function VRExperienceHelperCameraGazer(getCamera, scene) {
  100692. var _this = _super.call(this, scene) || this;
  100693. _this.getCamera = getCamera;
  100694. return _this;
  100695. }
  100696. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  100697. var camera = this.getCamera();
  100698. if (camera) {
  100699. return camera.getForwardRay(length);
  100700. }
  100701. else {
  100702. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  100703. }
  100704. };
  100705. return VRExperienceHelperCameraGazer;
  100706. }(VRExperienceHelperGazer));
  100707. /**
  100708. * Helps to quickly add VR support to an existing scene.
  100709. * See http://doc.babylonjs.com/how_to/webvr_helper
  100710. */
  100711. var VRExperienceHelper = /** @class */ (function () {
  100712. /**
  100713. * Instantiates a VRExperienceHelper.
  100714. * Helps to quickly add VR support to an existing scene.
  100715. * @param scene The scene the VRExperienceHelper belongs to.
  100716. * @param webVROptions Options to modify the vr experience helper's behavior.
  100717. */
  100718. function VRExperienceHelper(scene,
  100719. /** Options to modify the vr experience helper's behavior. */
  100720. webVROptions) {
  100721. if (webVROptions === void 0) { webVROptions = {}; }
  100722. var _this = this;
  100723. this.webVROptions = webVROptions;
  100724. // Can the system support WebVR, even if a headset isn't plugged in?
  100725. this._webVRsupported = false;
  100726. // If WebVR is supported, is a headset plugged in and are we ready to present?
  100727. this._webVRready = false;
  100728. // Are we waiting for the requestPresent callback to complete?
  100729. this._webVRrequesting = false;
  100730. // Are we presenting to the headset right now? (this is the vrDevice state)
  100731. this._webVRpresenting = false;
  100732. // Are we presenting in the fullscreen fallback?
  100733. this._fullscreenVRpresenting = false;
  100734. /**
  100735. * Observable raised when entering VR.
  100736. */
  100737. this.onEnteringVRObservable = new BABYLON.Observable();
  100738. /**
  100739. * Observable raised when exiting VR.
  100740. */
  100741. this.onExitingVRObservable = new BABYLON.Observable();
  100742. /**
  100743. * Observable raised when controller mesh is loaded.
  100744. */
  100745. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100746. this._useCustomVRButton = false;
  100747. this._teleportationRequested = false;
  100748. this._teleportActive = false;
  100749. this._floorMeshesCollection = [];
  100750. this._rotationAllowed = true;
  100751. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  100752. this._isDefaultTeleportationTarget = true;
  100753. this._teleportationFillColor = "#444444";
  100754. this._teleportationBorderColor = "#FFFFFF";
  100755. this._rotationAngle = 0;
  100756. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  100757. this._padSensibilityUp = 0.65;
  100758. this._padSensibilityDown = 0.35;
  100759. this._leftController = null;
  100760. this._rightController = null;
  100761. /**
  100762. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  100763. */
  100764. this.onNewMeshSelected = new BABYLON.Observable();
  100765. /**
  100766. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  100767. */
  100768. this.onNewMeshPicked = new BABYLON.Observable();
  100769. /**
  100770. * Observable raised before camera teleportation
  100771. */
  100772. this.onBeforeCameraTeleport = new BABYLON.Observable();
  100773. /**
  100774. * Observable raised after camera teleportation
  100775. */
  100776. this.onAfterCameraTeleport = new BABYLON.Observable();
  100777. /**
  100778. * Observable raised when current selected mesh gets unselected
  100779. */
  100780. this.onSelectedMeshUnselected = new BABYLON.Observable();
  100781. /**
  100782. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  100783. */
  100784. this.teleportationEnabled = true;
  100785. this._teleportationInitialized = false;
  100786. this._interactionsEnabled = false;
  100787. this._interactionsRequested = false;
  100788. this._displayGaze = true;
  100789. this._displayLaserPointer = true;
  100790. /**
  100791. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  100792. */
  100793. this.updateGazeTrackerScale = true;
  100794. this._onResize = function () {
  100795. _this.moveButtonToBottomRight();
  100796. if (_this._fullscreenVRpresenting && _this._webVRready) {
  100797. _this.exitVR();
  100798. }
  100799. };
  100800. this._onFullscreenChange = function () {
  100801. if (document.fullscreen !== undefined) {
  100802. _this._fullscreenVRpresenting = document.fullscreen;
  100803. }
  100804. else if (document.mozFullScreen !== undefined) {
  100805. _this._fullscreenVRpresenting = document.mozFullScreen;
  100806. }
  100807. else if (document.webkitIsFullScreen !== undefined) {
  100808. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  100809. }
  100810. else if (document.msIsFullScreen !== undefined) {
  100811. _this._fullscreenVRpresenting = document.msIsFullScreen;
  100812. }
  100813. else if (document.msFullscreenElement !== undefined) {
  100814. _this._fullscreenVRpresenting = document.msFullscreenElement;
  100815. }
  100816. if (!_this._fullscreenVRpresenting && _this._canvas) {
  100817. _this.exitVR();
  100818. if (!_this._useCustomVRButton) {
  100819. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  100820. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  100821. }
  100822. }
  100823. };
  100824. this.beforeRender = function () {
  100825. if (_this._leftController && _this._leftController._activePointer) {
  100826. _this._castRayAndSelectObject(_this._leftController);
  100827. }
  100828. if (_this._rightController && _this._rightController._activePointer) {
  100829. _this._castRayAndSelectObject(_this._rightController);
  100830. }
  100831. if (_this._noControllerIsActive) {
  100832. _this._castRayAndSelectObject(_this._cameraGazer);
  100833. }
  100834. else {
  100835. _this._cameraGazer._gazeTracker.isVisible = false;
  100836. }
  100837. };
  100838. this._onNewGamepadConnected = function (gamepad) {
  100839. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  100840. if (gamepad.leftStick) {
  100841. gamepad.onleftstickchanged(function (stickValues) {
  100842. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  100843. // Listening to classic/xbox gamepad only if no VR controller is active
  100844. if ((!_this._leftController && !_this._rightController) ||
  100845. ((_this._leftController && !_this._leftController._activePointer) &&
  100846. (_this._rightController && !_this._rightController._activePointer))) {
  100847. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  100848. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  100849. }
  100850. }
  100851. });
  100852. }
  100853. if (gamepad.rightStick) {
  100854. gamepad.onrightstickchanged(function (stickValues) {
  100855. if (_this._teleportationInitialized) {
  100856. _this._checkRotate(stickValues, _this._cameraGazer);
  100857. }
  100858. });
  100859. }
  100860. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  100861. gamepad.onbuttondown(function (buttonPressed) {
  100862. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100863. _this._cameraGazer._selectionPointerDown();
  100864. }
  100865. });
  100866. gamepad.onbuttonup(function (buttonPressed) {
  100867. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100868. _this._cameraGazer._selectionPointerUp();
  100869. }
  100870. });
  100871. }
  100872. }
  100873. else {
  100874. var webVRController = gamepad;
  100875. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  100876. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  100877. _this._rightController = controller;
  100878. }
  100879. else {
  100880. _this._leftController = controller;
  100881. }
  100882. _this._tryEnableInteractionOnController(controller);
  100883. }
  100884. };
  100885. // 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
  100886. this._tryEnableInteractionOnController = function (controller) {
  100887. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  100888. _this._enableInteractionOnController(controller);
  100889. }
  100890. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  100891. _this._enableTeleportationOnController(controller);
  100892. }
  100893. };
  100894. this._onNewGamepadDisconnected = function (gamepad) {
  100895. if (gamepad instanceof BABYLON.WebVRController) {
  100896. if (gamepad.hand === "left" && _this._leftController != null) {
  100897. _this._leftController.dispose();
  100898. _this._leftController = null;
  100899. }
  100900. if (gamepad.hand === "right" && _this._rightController != null) {
  100901. _this._rightController.dispose();
  100902. _this._rightController = null;
  100903. }
  100904. }
  100905. };
  100906. this._workingVector = BABYLON.Vector3.Zero();
  100907. this._workingQuaternion = BABYLON.Quaternion.Identity();
  100908. this._workingMatrix = BABYLON.Matrix.Identity();
  100909. this._scene = scene;
  100910. this._canvas = scene.getEngine().getRenderingCanvas();
  100911. // Parse options
  100912. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  100913. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  100914. }
  100915. if (webVROptions.createDeviceOrientationCamera === undefined) {
  100916. webVROptions.createDeviceOrientationCamera = true;
  100917. }
  100918. if (webVROptions.laserToggle === undefined) {
  100919. webVROptions.laserToggle = true;
  100920. }
  100921. if (webVROptions.defaultHeight === undefined) {
  100922. webVROptions.defaultHeight = 1.7;
  100923. }
  100924. if (webVROptions.useCustomVRButton) {
  100925. this._useCustomVRButton = true;
  100926. if (webVROptions.customVRButton) {
  100927. this._btnVR = webVROptions.customVRButton;
  100928. }
  100929. }
  100930. if (webVROptions.rayLength) {
  100931. this._rayLength = webVROptions.rayLength;
  100932. }
  100933. this._defaultHeight = webVROptions.defaultHeight;
  100934. if (webVROptions.positionScale) {
  100935. this._rayLength *= webVROptions.positionScale;
  100936. this._defaultHeight *= webVROptions.positionScale;
  100937. }
  100938. this._hasEnteredVR = false;
  100939. // Set position
  100940. if (this._scene.activeCamera) {
  100941. this._position = this._scene.activeCamera.position.clone();
  100942. }
  100943. else {
  100944. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  100945. }
  100946. // Set non-vr camera
  100947. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  100948. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  100949. // Copy data from existing camera
  100950. if (this._scene.activeCamera) {
  100951. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100952. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  100953. // Set rotation from previous camera
  100954. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  100955. var targetCamera = this._scene.activeCamera;
  100956. if (targetCamera.rotationQuaternion) {
  100957. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  100958. }
  100959. else {
  100960. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  100961. }
  100962. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  100963. }
  100964. }
  100965. this._scene.activeCamera = this._deviceOrientationCamera;
  100966. if (this._canvas) {
  100967. this._scene.activeCamera.attachControl(this._canvas);
  100968. }
  100969. }
  100970. else {
  100971. this._existingCamera = this._scene.activeCamera;
  100972. }
  100973. // Create VR cameras
  100974. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100975. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  100976. }
  100977. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  100978. this._webVRCamera.useStandingMatrix();
  100979. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  100980. // Create default button
  100981. if (!this._useCustomVRButton) {
  100982. this._btnVR = document.createElement("BUTTON");
  100983. this._btnVR.className = "babylonVRicon";
  100984. this._btnVR.id = "babylonVRiconbtn";
  100985. this._btnVR.title = "Click to switch to VR";
  100986. 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) }";
  100987. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  100988. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  100989. // css += ".babylonVRicon.vrdisplaysupported { }";
  100990. // css += ".babylonVRicon.vrdisplayready { }";
  100991. // css += ".babylonVRicon.vrdisplayrequesting { }";
  100992. var style = document.createElement('style');
  100993. style.appendChild(document.createTextNode(css));
  100994. document.getElementsByTagName('head')[0].appendChild(style);
  100995. this.moveButtonToBottomRight();
  100996. }
  100997. // VR button click event
  100998. if (this._btnVR) {
  100999. this._btnVR.addEventListener("click", function () {
  101000. if (!_this.isInVRMode) {
  101001. _this.enterVR();
  101002. }
  101003. else {
  101004. _this.exitVR();
  101005. }
  101006. });
  101007. }
  101008. // Window events
  101009. window.addEventListener("resize", this._onResize);
  101010. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  101011. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  101012. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  101013. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  101014. document.onmsfullscreenchange = this._onFullscreenChange;
  101015. // Display vr button when headset is connected
  101016. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  101017. this.displayVRButton();
  101018. }
  101019. else {
  101020. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  101021. if (e.vrDisplay) {
  101022. _this.displayVRButton();
  101023. }
  101024. });
  101025. }
  101026. // Exiting VR mode using 'ESC' key on desktop
  101027. this._onKeyDown = function (event) {
  101028. if (event.keyCode === 27 && _this.isInVRMode) {
  101029. _this.exitVR();
  101030. }
  101031. };
  101032. document.addEventListener("keydown", this._onKeyDown);
  101033. // Exiting VR mode double tapping the touch screen
  101034. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  101035. if (_this.isInVRMode) {
  101036. _this.exitVR();
  101037. if (_this._fullscreenVRpresenting) {
  101038. _this._scene.getEngine().switchFullscreen(true);
  101039. }
  101040. }
  101041. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  101042. // Listen for WebVR display changes
  101043. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  101044. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  101045. this._onVRRequestPresentStart = function () {
  101046. _this._webVRrequesting = true;
  101047. _this.updateButtonVisibility();
  101048. };
  101049. this._onVRRequestPresentComplete = function (success) {
  101050. _this._webVRrequesting = false;
  101051. _this.updateButtonVisibility();
  101052. };
  101053. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  101054. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  101055. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  101056. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101057. scene.onDisposeObservable.add(function () {
  101058. _this.dispose();
  101059. });
  101060. // Gamepad connection events
  101061. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  101062. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  101063. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  101064. this.updateButtonVisibility();
  101065. //create easing functions
  101066. this._circleEase = new BABYLON.CircleEase();
  101067. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101068. if (this.webVROptions.floorMeshes) {
  101069. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  101070. }
  101071. }
  101072. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  101073. /** Return this.onEnteringVRObservable
  101074. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  101075. */
  101076. get: function () {
  101077. return this.onEnteringVRObservable;
  101078. },
  101079. enumerable: true,
  101080. configurable: true
  101081. });
  101082. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  101083. /** Return this.onExitingVRObservable
  101084. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  101085. */
  101086. get: function () {
  101087. return this.onExitingVRObservable;
  101088. },
  101089. enumerable: true,
  101090. configurable: true
  101091. });
  101092. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  101093. /** Return this.onControllerMeshLoadedObservable
  101094. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  101095. */
  101096. get: function () {
  101097. return this.onControllerMeshLoadedObservable;
  101098. },
  101099. enumerable: true,
  101100. configurable: true
  101101. });
  101102. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  101103. /**
  101104. * The mesh used to display where the user is going to teleport.
  101105. */
  101106. get: function () {
  101107. return this._teleportationTarget;
  101108. },
  101109. /**
  101110. * Sets the mesh to be used to display where the user is going to teleport.
  101111. */
  101112. set: function (value) {
  101113. if (value) {
  101114. value.name = "teleportationTarget";
  101115. this._isDefaultTeleportationTarget = false;
  101116. this._teleportationTarget = value;
  101117. }
  101118. },
  101119. enumerable: true,
  101120. configurable: true
  101121. });
  101122. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  101123. /**
  101124. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  101125. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  101126. * See http://doc.babylonjs.com/resources/baking_transformations
  101127. */
  101128. get: function () {
  101129. return this._cameraGazer._gazeTracker;
  101130. },
  101131. set: function (value) {
  101132. if (value) {
  101133. // Dispose of existing meshes
  101134. if (this._cameraGazer._gazeTracker) {
  101135. this._cameraGazer._gazeTracker.dispose();
  101136. }
  101137. if (this._leftController && this._leftController._gazeTracker) {
  101138. this._leftController._gazeTracker.dispose();
  101139. }
  101140. if (this._rightController && this._rightController._gazeTracker) {
  101141. this._rightController._gazeTracker.dispose();
  101142. }
  101143. // Set and create gaze trackers on head and controllers
  101144. this._cameraGazer._gazeTracker = value;
  101145. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  101146. this._cameraGazer._gazeTracker.isPickable = false;
  101147. this._cameraGazer._gazeTracker.isVisible = false;
  101148. this._cameraGazer._gazeTracker.name = "gazeTracker";
  101149. if (this._leftController) {
  101150. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101151. }
  101152. if (this._rightController) {
  101153. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101154. }
  101155. }
  101156. },
  101157. enumerable: true,
  101158. configurable: true
  101159. });
  101160. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  101161. /**
  101162. * The gaze tracking mesh corresponding to the left controller
  101163. */
  101164. get: function () {
  101165. if (this._leftController) {
  101166. return this._leftController._gazeTracker;
  101167. }
  101168. return null;
  101169. },
  101170. enumerable: true,
  101171. configurable: true
  101172. });
  101173. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  101174. /**
  101175. * The gaze tracking mesh corresponding to the right controller
  101176. */
  101177. get: function () {
  101178. if (this._rightController) {
  101179. return this._rightController._gazeTracker;
  101180. }
  101181. return null;
  101182. },
  101183. enumerable: true,
  101184. configurable: true
  101185. });
  101186. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  101187. /**
  101188. * If the ray of the gaze should be displayed.
  101189. */
  101190. get: function () {
  101191. return this._displayGaze;
  101192. },
  101193. /**
  101194. * Sets if the ray of the gaze should be displayed.
  101195. */
  101196. set: function (value) {
  101197. this._displayGaze = value;
  101198. if (!value) {
  101199. this._cameraGazer._gazeTracker.isVisible = false;
  101200. if (this._leftController) {
  101201. this._leftController._gazeTracker.isVisible = false;
  101202. }
  101203. if (this._rightController) {
  101204. this._rightController._gazeTracker.isVisible = false;
  101205. }
  101206. }
  101207. },
  101208. enumerable: true,
  101209. configurable: true
  101210. });
  101211. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  101212. /**
  101213. * If the ray of the LaserPointer should be displayed.
  101214. */
  101215. get: function () {
  101216. return this._displayLaserPointer;
  101217. },
  101218. /**
  101219. * Sets if the ray of the LaserPointer should be displayed.
  101220. */
  101221. set: function (value) {
  101222. this._displayLaserPointer = value;
  101223. if (!value) {
  101224. if (this._rightController) {
  101225. this._rightController._deactivatePointer();
  101226. this._rightController._gazeTracker.isVisible = false;
  101227. }
  101228. if (this._leftController) {
  101229. this._leftController._deactivatePointer();
  101230. this._leftController._gazeTracker.isVisible = false;
  101231. }
  101232. }
  101233. else {
  101234. if (this._rightController) {
  101235. this._rightController._activatePointer();
  101236. }
  101237. if (this._leftController) {
  101238. this._leftController._activatePointer();
  101239. }
  101240. }
  101241. },
  101242. enumerable: true,
  101243. configurable: true
  101244. });
  101245. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  101246. /**
  101247. * The deviceOrientationCamera used as the camera when not in VR.
  101248. */
  101249. get: function () {
  101250. return this._deviceOrientationCamera;
  101251. },
  101252. enumerable: true,
  101253. configurable: true
  101254. });
  101255. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  101256. /**
  101257. * Based on the current WebVR support, returns the current VR camera used.
  101258. */
  101259. get: function () {
  101260. if (this._webVRready) {
  101261. return this._webVRCamera;
  101262. }
  101263. else {
  101264. return this._scene.activeCamera;
  101265. }
  101266. },
  101267. enumerable: true,
  101268. configurable: true
  101269. });
  101270. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  101271. /**
  101272. * The webVRCamera which is used when in VR.
  101273. */
  101274. get: function () {
  101275. return this._webVRCamera;
  101276. },
  101277. enumerable: true,
  101278. configurable: true
  101279. });
  101280. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  101281. /**
  101282. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  101283. */
  101284. get: function () {
  101285. return this._vrDeviceOrientationCamera;
  101286. },
  101287. enumerable: true,
  101288. configurable: true
  101289. });
  101290. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  101291. get: function () {
  101292. var result = this._cameraGazer._teleportationRequestInitiated
  101293. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  101294. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  101295. return result;
  101296. },
  101297. enumerable: true,
  101298. configurable: true
  101299. });
  101300. // Raised when one of the controller has loaded successfully its associated default mesh
  101301. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  101302. if (this._leftController && this._leftController.webVRController == webVRController) {
  101303. if (webVRController.mesh) {
  101304. this._leftController._setLaserPointerParent(webVRController.mesh);
  101305. }
  101306. }
  101307. if (this._rightController && this._rightController.webVRController == webVRController) {
  101308. if (webVRController.mesh) {
  101309. this._rightController._setLaserPointerParent(webVRController.mesh);
  101310. }
  101311. }
  101312. try {
  101313. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  101314. }
  101315. catch (err) {
  101316. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  101317. }
  101318. };
  101319. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  101320. /**
  101321. * Gets a value indicating if we are currently in VR mode.
  101322. */
  101323. get: function () {
  101324. return this._webVRpresenting || this._fullscreenVRpresenting;
  101325. },
  101326. enumerable: true,
  101327. configurable: true
  101328. });
  101329. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  101330. var vrDisplay = this._scene.getEngine().getVRDevice();
  101331. if (vrDisplay) {
  101332. var wasPresenting = this._webVRpresenting;
  101333. this._webVRpresenting = vrDisplay.isPresenting;
  101334. if (wasPresenting && !this._webVRpresenting)
  101335. this.exitVR();
  101336. }
  101337. else {
  101338. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  101339. }
  101340. this.updateButtonVisibility();
  101341. };
  101342. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  101343. this._webVRsupported = eventArgs.vrSupported;
  101344. this._webVRready = !!eventArgs.vrDisplay;
  101345. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  101346. this.updateButtonVisibility();
  101347. };
  101348. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  101349. if (this._canvas && !this._useCustomVRButton) {
  101350. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  101351. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  101352. }
  101353. };
  101354. VRExperienceHelper.prototype.displayVRButton = function () {
  101355. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  101356. document.body.appendChild(this._btnVR);
  101357. this._btnVRDisplayed = true;
  101358. }
  101359. };
  101360. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  101361. if (!this._btnVR || this._useCustomVRButton) {
  101362. return;
  101363. }
  101364. this._btnVR.className = "babylonVRicon";
  101365. if (this.isInVRMode) {
  101366. this._btnVR.className += " vrdisplaypresenting";
  101367. }
  101368. else {
  101369. if (this._webVRready)
  101370. this._btnVR.className += " vrdisplayready";
  101371. if (this._webVRsupported)
  101372. this._btnVR.className += " vrdisplaysupported";
  101373. if (this._webVRrequesting)
  101374. this._btnVR.className += " vrdisplayrequesting";
  101375. }
  101376. };
  101377. /**
  101378. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  101379. * Otherwise, will use the fullscreen API.
  101380. */
  101381. VRExperienceHelper.prototype.enterVR = function () {
  101382. if (this.onEnteringVRObservable) {
  101383. try {
  101384. this.onEnteringVRObservable.notifyObservers(this);
  101385. }
  101386. catch (err) {
  101387. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  101388. }
  101389. }
  101390. if (this._scene.activeCamera) {
  101391. this._position = this._scene.activeCamera.position.clone();
  101392. // make sure that we return to the last active camera
  101393. this._existingCamera = this._scene.activeCamera;
  101394. }
  101395. if (this._webVRrequesting)
  101396. return;
  101397. // If WebVR is supported and a headset is connected
  101398. if (this._webVRready) {
  101399. if (!this._webVRpresenting) {
  101400. this._webVRCamera.position = this._position;
  101401. this._scene.activeCamera = this._webVRCamera;
  101402. }
  101403. }
  101404. else if (this._vrDeviceOrientationCamera) {
  101405. this._vrDeviceOrientationCamera.position = this._position;
  101406. if (this._scene.activeCamera) {
  101407. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101408. }
  101409. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  101410. this._scene.getEngine().switchFullscreen(true);
  101411. this.updateButtonVisibility();
  101412. }
  101413. if (this._scene.activeCamera && this._canvas) {
  101414. this._scene.activeCamera.attachControl(this._canvas);
  101415. }
  101416. if (this._interactionsEnabled) {
  101417. this._scene.registerBeforeRender(this.beforeRender);
  101418. }
  101419. this._hasEnteredVR = true;
  101420. };
  101421. /**
  101422. * Attempt to exit VR, or fullscreen.
  101423. */
  101424. VRExperienceHelper.prototype.exitVR = function () {
  101425. if (this._hasEnteredVR) {
  101426. if (this.onExitingVRObservable) {
  101427. try {
  101428. this.onExitingVRObservable.notifyObservers(this);
  101429. }
  101430. catch (err) {
  101431. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  101432. }
  101433. }
  101434. if (this._webVRpresenting) {
  101435. this._scene.getEngine().disableVR();
  101436. }
  101437. if (this._scene.activeCamera) {
  101438. this._position = this._scene.activeCamera.position.clone();
  101439. }
  101440. if (this._deviceOrientationCamera) {
  101441. this._deviceOrientationCamera.position = this._position;
  101442. this._scene.activeCamera = this._deviceOrientationCamera;
  101443. if (this._canvas) {
  101444. this._scene.activeCamera.attachControl(this._canvas);
  101445. }
  101446. }
  101447. else if (this._existingCamera) {
  101448. this._existingCamera.position = this._position;
  101449. this._scene.activeCamera = this._existingCamera;
  101450. }
  101451. this.updateButtonVisibility();
  101452. if (this._interactionsEnabled) {
  101453. this._scene.unregisterBeforeRender(this.beforeRender);
  101454. this._cameraGazer._gazeTracker.isVisible = false;
  101455. if (this._leftController) {
  101456. this._leftController._gazeTracker.isVisible = false;
  101457. }
  101458. if (this._rightController) {
  101459. this._rightController._gazeTracker.isVisible = false;
  101460. }
  101461. }
  101462. // resize to update width and height when exiting vr exits fullscreen
  101463. this._scene.getEngine().resize();
  101464. this._hasEnteredVR = false;
  101465. }
  101466. };
  101467. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  101468. /**
  101469. * The position of the vr experience helper.
  101470. */
  101471. get: function () {
  101472. return this._position;
  101473. },
  101474. /**
  101475. * Sets the position of the vr experience helper.
  101476. */
  101477. set: function (value) {
  101478. this._position = value;
  101479. if (this._scene.activeCamera) {
  101480. this._scene.activeCamera.position = value;
  101481. }
  101482. },
  101483. enumerable: true,
  101484. configurable: true
  101485. });
  101486. /**
  101487. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  101488. */
  101489. VRExperienceHelper.prototype.enableInteractions = function () {
  101490. var _this = this;
  101491. if (!this._interactionsEnabled) {
  101492. this._interactionsRequested = true;
  101493. if (this._leftController) {
  101494. this._enableInteractionOnController(this._leftController);
  101495. }
  101496. if (this._rightController) {
  101497. this._enableInteractionOnController(this._rightController);
  101498. }
  101499. this.raySelectionPredicate = function (mesh) {
  101500. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  101501. };
  101502. this.meshSelectionPredicate = function (mesh) {
  101503. return true;
  101504. };
  101505. this._raySelectionPredicate = function (mesh) {
  101506. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  101507. && mesh.name.indexOf("teleportationTarget") === -1
  101508. && mesh.name.indexOf("torusTeleportation") === -1)) {
  101509. return _this.raySelectionPredicate(mesh);
  101510. }
  101511. return false;
  101512. };
  101513. this._interactionsEnabled = true;
  101514. }
  101515. };
  101516. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  101517. get: function () {
  101518. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  101519. },
  101520. enumerable: true,
  101521. configurable: true
  101522. });
  101523. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  101524. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  101525. if (this._floorMeshesCollection[i].id === mesh.id) {
  101526. return true;
  101527. }
  101528. }
  101529. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  101530. return true;
  101531. }
  101532. return false;
  101533. };
  101534. /**
  101535. * Adds a floor mesh to be used for teleportation.
  101536. * @param floorMesh the mesh to be used for teleportation.
  101537. */
  101538. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  101539. if (!this._floorMeshesCollection) {
  101540. return;
  101541. }
  101542. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  101543. return;
  101544. }
  101545. this._floorMeshesCollection.push(floorMesh);
  101546. };
  101547. /**
  101548. * Removes a floor mesh from being used for teleportation.
  101549. * @param floorMesh the mesh to be removed.
  101550. */
  101551. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  101552. if (!this._floorMeshesCollection) {
  101553. return;
  101554. }
  101555. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  101556. if (meshIndex !== -1) {
  101557. this._floorMeshesCollection.splice(meshIndex, 1);
  101558. }
  101559. };
  101560. /**
  101561. * Enables interactions and teleportation using the VR controllers and gaze.
  101562. * @param vrTeleportationOptions options to modify teleportation behavior.
  101563. */
  101564. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  101565. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  101566. if (!this._teleportationInitialized) {
  101567. this._teleportationRequested = true;
  101568. this.enableInteractions();
  101569. if (vrTeleportationOptions.floorMeshName) {
  101570. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  101571. }
  101572. if (vrTeleportationOptions.floorMeshes) {
  101573. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  101574. }
  101575. if (this._leftController != null) {
  101576. this._enableTeleportationOnController(this._leftController);
  101577. }
  101578. if (this._rightController != null) {
  101579. this._enableTeleportationOnController(this._rightController);
  101580. }
  101581. // Creates an image processing post process for the vignette not relying
  101582. // on the main scene configuration for image processing to reduce setup and spaces
  101583. // (gamma/linear) conflicts.
  101584. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  101585. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  101586. imageProcessingConfiguration.vignetteEnabled = true;
  101587. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  101588. this._webVRCamera.detachPostProcess(this._postProcessMove);
  101589. this._teleportationInitialized = true;
  101590. if (this._isDefaultTeleportationTarget) {
  101591. this._createTeleportationCircles();
  101592. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  101593. }
  101594. }
  101595. };
  101596. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  101597. var _this = this;
  101598. var controllerMesh = controller.webVRController.mesh;
  101599. if (controllerMesh) {
  101600. controller._interactionsEnabled = true;
  101601. controller._activatePointer();
  101602. if (this.webVROptions.laserToggle) {
  101603. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  101604. // Enabling / disabling laserPointer
  101605. if (_this._displayLaserPointer && stateObject.value === 1) {
  101606. if (controller._activePointer) {
  101607. controller._deactivatePointer();
  101608. }
  101609. else {
  101610. controller._activatePointer();
  101611. }
  101612. if (_this.displayGaze) {
  101613. controller._gazeTracker.isVisible = controller._activePointer;
  101614. }
  101615. }
  101616. });
  101617. }
  101618. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  101619. var gazer = controller;
  101620. if (_this._noControllerIsActive) {
  101621. gazer = _this._cameraGazer;
  101622. }
  101623. if (!gazer._pointerDownOnMeshAsked) {
  101624. if (stateObject.value > _this._padSensibilityUp) {
  101625. gazer._selectionPointerDown();
  101626. }
  101627. }
  101628. else if (stateObject.value < _this._padSensibilityDown) {
  101629. gazer._selectionPointerUp();
  101630. }
  101631. });
  101632. }
  101633. };
  101634. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  101635. // Dont teleport if another gaze already requested teleportation
  101636. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  101637. return;
  101638. }
  101639. if (!gazer._teleportationRequestInitiated) {
  101640. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  101641. gazer._activatePointer();
  101642. gazer._teleportationRequestInitiated = true;
  101643. }
  101644. }
  101645. else {
  101646. // Listening to the proper controller values changes to confirm teleportation
  101647. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  101648. if (this._teleportActive) {
  101649. this.teleportCamera(this._haloCenter);
  101650. }
  101651. gazer._teleportationRequestInitiated = false;
  101652. }
  101653. }
  101654. };
  101655. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  101656. // Only rotate when user is not currently selecting a teleportation location
  101657. if (gazer._teleportationRequestInitiated) {
  101658. return;
  101659. }
  101660. if (!gazer._rotationLeftAsked) {
  101661. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  101662. gazer._rotationLeftAsked = true;
  101663. if (this._rotationAllowed) {
  101664. this._rotateCamera(false);
  101665. }
  101666. }
  101667. }
  101668. else {
  101669. if (stateObject.x > -this._padSensibilityDown) {
  101670. gazer._rotationLeftAsked = false;
  101671. }
  101672. }
  101673. if (!gazer._rotationRightAsked) {
  101674. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  101675. gazer._rotationRightAsked = true;
  101676. if (this._rotationAllowed) {
  101677. this._rotateCamera(true);
  101678. }
  101679. }
  101680. }
  101681. else {
  101682. if (stateObject.x < this._padSensibilityDown) {
  101683. gazer._rotationRightAsked = false;
  101684. }
  101685. }
  101686. };
  101687. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  101688. // Only teleport backwards when user is not currently selecting a teleportation location
  101689. if (gazer._teleportationRequestInitiated) {
  101690. return;
  101691. }
  101692. // Teleport backwards
  101693. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  101694. if (!gazer._teleportationBackRequestInitiated) {
  101695. if (!this.currentVRCamera) {
  101696. return;
  101697. }
  101698. // Get rotation and position of the current camera
  101699. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  101700. var position = this.currentVRCamera.position;
  101701. // If the camera has device position, use that instead
  101702. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  101703. rotation = this.currentVRCamera.deviceRotationQuaternion;
  101704. position = this.currentVRCamera.devicePosition;
  101705. }
  101706. // Get matrix with only the y rotation of the device rotation
  101707. rotation.toEulerAnglesToRef(this._workingVector);
  101708. this._workingVector.z = 0;
  101709. this._workingVector.x = 0;
  101710. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  101711. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  101712. // Rotate backwards ray by device rotation to cast at the ground behind the user
  101713. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  101714. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  101715. var ray = new BABYLON.Ray(position, this._workingVector);
  101716. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101717. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  101718. this.teleportCamera(hit.pickedPoint);
  101719. }
  101720. gazer._teleportationBackRequestInitiated = true;
  101721. }
  101722. }
  101723. else {
  101724. gazer._teleportationBackRequestInitiated = false;
  101725. }
  101726. };
  101727. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  101728. var _this = this;
  101729. var controllerMesh = controller.webVRController.mesh;
  101730. if (controllerMesh) {
  101731. if (!controller._interactionsEnabled) {
  101732. this._enableInteractionOnController(controller);
  101733. }
  101734. controller._interactionsEnabled = true;
  101735. controller._teleportationEnabled = true;
  101736. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101737. controller._dpadPressed = false;
  101738. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  101739. controller._dpadPressed = stateObject.pressed;
  101740. if (!controller._dpadPressed) {
  101741. controller._rotationLeftAsked = false;
  101742. controller._rotationRightAsked = false;
  101743. controller._teleportationBackRequestInitiated = false;
  101744. }
  101745. });
  101746. }
  101747. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  101748. if (_this.teleportationEnabled) {
  101749. _this._checkTeleportBackwards(stateObject, controller);
  101750. _this._checkTeleportWithRay(stateObject, controller);
  101751. }
  101752. _this._checkRotate(stateObject, controller);
  101753. });
  101754. }
  101755. };
  101756. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  101757. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  101758. this._teleportationTarget.isPickable = false;
  101759. var length = 512;
  101760. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  101761. dynamicTexture.hasAlpha = true;
  101762. var context = dynamicTexture.getContext();
  101763. var centerX = length / 2;
  101764. var centerY = length / 2;
  101765. var radius = 200;
  101766. context.beginPath();
  101767. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  101768. context.fillStyle = this._teleportationFillColor;
  101769. context.fill();
  101770. context.lineWidth = 10;
  101771. context.strokeStyle = this._teleportationBorderColor;
  101772. context.stroke();
  101773. context.closePath();
  101774. dynamicTexture.update();
  101775. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  101776. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  101777. this._teleportationTarget.material = teleportationCircleMaterial;
  101778. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  101779. torus.isPickable = false;
  101780. torus.parent = this._teleportationTarget;
  101781. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101782. var keys = [];
  101783. keys.push({
  101784. frame: 0,
  101785. value: 0
  101786. });
  101787. keys.push({
  101788. frame: 30,
  101789. value: 0.4
  101790. });
  101791. keys.push({
  101792. frame: 60,
  101793. value: 0
  101794. });
  101795. animationInnerCircle.setKeys(keys);
  101796. var easingFunction = new BABYLON.SineEase();
  101797. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101798. animationInnerCircle.setEasingFunction(easingFunction);
  101799. torus.animations = [];
  101800. torus.animations.push(animationInnerCircle);
  101801. this._scene.beginAnimation(torus, 0, 60, true);
  101802. this._hideTeleportationTarget();
  101803. };
  101804. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  101805. this._teleportActive = true;
  101806. if (this._teleportationInitialized) {
  101807. this._teleportationTarget.isVisible = true;
  101808. if (this._isDefaultTeleportationTarget) {
  101809. this._teleportationTarget.getChildren()[0].isVisible = true;
  101810. }
  101811. }
  101812. };
  101813. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  101814. this._teleportActive = false;
  101815. if (this._teleportationInitialized) {
  101816. this._teleportationTarget.isVisible = false;
  101817. if (this._isDefaultTeleportationTarget) {
  101818. this._teleportationTarget.getChildren()[0].isVisible = false;
  101819. }
  101820. }
  101821. };
  101822. VRExperienceHelper.prototype._rotateCamera = function (right) {
  101823. var _this = this;
  101824. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101825. return;
  101826. }
  101827. if (right) {
  101828. this._rotationAngle++;
  101829. }
  101830. else {
  101831. this._rotationAngle--;
  101832. }
  101833. this.currentVRCamera.animations = [];
  101834. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  101835. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101836. var animationRotationKeys = [];
  101837. animationRotationKeys.push({
  101838. frame: 0,
  101839. value: this.currentVRCamera.rotationQuaternion
  101840. });
  101841. animationRotationKeys.push({
  101842. frame: 6,
  101843. value: target
  101844. });
  101845. animationRotation.setKeys(animationRotationKeys);
  101846. animationRotation.setEasingFunction(this._circleEase);
  101847. this.currentVRCamera.animations.push(animationRotation);
  101848. this._postProcessMove.animations = [];
  101849. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101850. var vignetteWeightKeys = [];
  101851. vignetteWeightKeys.push({
  101852. frame: 0,
  101853. value: 0
  101854. });
  101855. vignetteWeightKeys.push({
  101856. frame: 3,
  101857. value: 4
  101858. });
  101859. vignetteWeightKeys.push({
  101860. frame: 6,
  101861. value: 0
  101862. });
  101863. animationPP.setKeys(vignetteWeightKeys);
  101864. animationPP.setEasingFunction(this._circleEase);
  101865. this._postProcessMove.animations.push(animationPP);
  101866. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101867. var vignetteStretchKeys = [];
  101868. vignetteStretchKeys.push({
  101869. frame: 0,
  101870. value: 0
  101871. });
  101872. vignetteStretchKeys.push({
  101873. frame: 3,
  101874. value: 10
  101875. });
  101876. vignetteStretchKeys.push({
  101877. frame: 6,
  101878. value: 0
  101879. });
  101880. animationPP2.setKeys(vignetteStretchKeys);
  101881. animationPP2.setEasingFunction(this._circleEase);
  101882. this._postProcessMove.animations.push(animationPP2);
  101883. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101884. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101885. this._postProcessMove.samples = 4;
  101886. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101887. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  101888. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101889. });
  101890. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  101891. };
  101892. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  101893. if (hit.pickedPoint) {
  101894. if (gazer._teleportationRequestInitiated) {
  101895. this._displayTeleportationTarget();
  101896. this._haloCenter.copyFrom(hit.pickedPoint);
  101897. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  101898. }
  101899. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  101900. if (pickNormal) {
  101901. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101902. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101903. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  101904. }
  101905. this._teleportationTarget.position.y += 0.1;
  101906. }
  101907. };
  101908. /**
  101909. * Teleports the users feet to the desired location
  101910. * @param location The location where the user's feet should be placed
  101911. */
  101912. VRExperienceHelper.prototype.teleportCamera = function (location) {
  101913. var _this = this;
  101914. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101915. return;
  101916. }
  101917. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  101918. // offset of the headset from the anchor.
  101919. if (this.webVRCamera.leftCamera) {
  101920. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  101921. this._workingVector.subtractInPlace(this.webVRCamera.position);
  101922. location.subtractToRef(this._workingVector, this._workingVector);
  101923. }
  101924. else {
  101925. this._workingVector.copyFrom(location);
  101926. }
  101927. // Add height to account for user's height offset
  101928. if (this.isInVRMode) {
  101929. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  101930. }
  101931. else {
  101932. this._workingVector.y += this._defaultHeight;
  101933. }
  101934. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  101935. // Create animation from the camera's position to the new location
  101936. this.currentVRCamera.animations = [];
  101937. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101938. var animationCameraTeleportationKeys = [{
  101939. frame: 0,
  101940. value: this.currentVRCamera.position
  101941. },
  101942. {
  101943. frame: 11,
  101944. value: this._workingVector
  101945. }
  101946. ];
  101947. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  101948. animationCameraTeleportation.setEasingFunction(this._circleEase);
  101949. this.currentVRCamera.animations.push(animationCameraTeleportation);
  101950. this._postProcessMove.animations = [];
  101951. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101952. var vignetteWeightKeys = [];
  101953. vignetteWeightKeys.push({
  101954. frame: 0,
  101955. value: 0
  101956. });
  101957. vignetteWeightKeys.push({
  101958. frame: 5,
  101959. value: 8
  101960. });
  101961. vignetteWeightKeys.push({
  101962. frame: 11,
  101963. value: 0
  101964. });
  101965. animationPP.setKeys(vignetteWeightKeys);
  101966. this._postProcessMove.animations.push(animationPP);
  101967. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101968. var vignetteStretchKeys = [];
  101969. vignetteStretchKeys.push({
  101970. frame: 0,
  101971. value: 0
  101972. });
  101973. vignetteStretchKeys.push({
  101974. frame: 5,
  101975. value: 10
  101976. });
  101977. vignetteStretchKeys.push({
  101978. frame: 11,
  101979. value: 0
  101980. });
  101981. animationPP2.setKeys(vignetteStretchKeys);
  101982. this._postProcessMove.animations.push(animationPP2);
  101983. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101984. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101985. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101986. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  101987. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101988. });
  101989. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  101990. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  101991. });
  101992. this._hideTeleportationTarget();
  101993. };
  101994. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  101995. if (normal) {
  101996. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  101997. if (angle < Math.PI / 2) {
  101998. normal.scaleInPlace(-1);
  101999. }
  102000. }
  102001. return normal;
  102002. };
  102003. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  102004. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102005. return;
  102006. }
  102007. var ray = gazer._getForwardRay(this._rayLength);
  102008. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  102009. if (hit) {
  102010. // Populate the contrllers mesh that can be used for drag/drop
  102011. if (gazer._laserPointer) {
  102012. hit.originMesh = gazer._laserPointer.parent;
  102013. }
  102014. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  102015. }
  102016. gazer._currentHit = hit;
  102017. // Moving the gazeTracker on the mesh face targetted
  102018. if (hit && hit.pickedPoint) {
  102019. if (this._displayGaze) {
  102020. var multiplier = 1;
  102021. gazer._gazeTracker.isVisible = true;
  102022. if (gazer._isActionableMesh) {
  102023. multiplier = 3;
  102024. }
  102025. if (this.updateGazeTrackerScale) {
  102026. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  102027. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  102028. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  102029. }
  102030. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  102031. // To avoid z-fighting
  102032. var deltaFighting = 0.002;
  102033. if (pickNormal) {
  102034. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102035. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102036. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  102037. }
  102038. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  102039. if (gazer._gazeTracker.position.x < 0) {
  102040. gazer._gazeTracker.position.x += deltaFighting;
  102041. }
  102042. else {
  102043. gazer._gazeTracker.position.x -= deltaFighting;
  102044. }
  102045. if (gazer._gazeTracker.position.y < 0) {
  102046. gazer._gazeTracker.position.y += deltaFighting;
  102047. }
  102048. else {
  102049. gazer._gazeTracker.position.y -= deltaFighting;
  102050. }
  102051. if (gazer._gazeTracker.position.z < 0) {
  102052. gazer._gazeTracker.position.z += deltaFighting;
  102053. }
  102054. else {
  102055. gazer._gazeTracker.position.z -= deltaFighting;
  102056. }
  102057. }
  102058. // Changing the size of the laser pointer based on the distance from the targetted point
  102059. gazer._updatePointerDistance(hit.distance);
  102060. }
  102061. else {
  102062. gazer._updatePointerDistance();
  102063. gazer._gazeTracker.isVisible = false;
  102064. }
  102065. if (hit && hit.pickedMesh) {
  102066. // The object selected is the floor, we're in a teleportation scenario
  102067. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  102068. // Moving the teleportation area to this targetted point
  102069. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  102070. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  102071. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102072. }
  102073. gazer._currentMeshSelected = null;
  102074. if (gazer._teleportationRequestInitiated) {
  102075. this._moveTeleportationSelectorTo(hit, gazer, ray);
  102076. }
  102077. return;
  102078. }
  102079. // If not, we're in a selection scenario
  102080. //this._teleportationAllowed = false;
  102081. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  102082. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  102083. this.onNewMeshPicked.notifyObservers(hit);
  102084. gazer._currentMeshSelected = hit.pickedMesh;
  102085. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  102086. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  102087. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  102088. gazer._isActionableMesh = true;
  102089. }
  102090. else {
  102091. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102092. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102093. gazer._isActionableMesh = false;
  102094. }
  102095. try {
  102096. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  102097. }
  102098. catch (err) {
  102099. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  102100. }
  102101. }
  102102. else {
  102103. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102104. gazer._currentMeshSelected = null;
  102105. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102106. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102107. }
  102108. }
  102109. }
  102110. else {
  102111. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102112. gazer._currentMeshSelected = null;
  102113. //this._teleportationAllowed = false;
  102114. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102115. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102116. }
  102117. };
  102118. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  102119. if (mesh) {
  102120. this.onSelectedMeshUnselected.notifyObservers(mesh);
  102121. }
  102122. };
  102123. /**
  102124. * Sets the color of the laser ray from the vr controllers.
  102125. * @param color new color for the ray.
  102126. */
  102127. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  102128. if (this._leftController) {
  102129. this._leftController._setLaserPointerColor(color);
  102130. }
  102131. if (this._rightController) {
  102132. this._rightController._setLaserPointerColor(color);
  102133. }
  102134. };
  102135. /**
  102136. * Sets the color of the ray from the vr headsets gaze.
  102137. * @param color new color for the ray.
  102138. */
  102139. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  102140. if (!this._cameraGazer._gazeTracker.material) {
  102141. return;
  102142. }
  102143. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  102144. if (this._leftController) {
  102145. this._leftController._gazeTracker.material.emissiveColor = color;
  102146. }
  102147. if (this._rightController) {
  102148. this._rightController._gazeTracker.material.emissiveColor = color;
  102149. }
  102150. };
  102151. /**
  102152. * Exits VR and disposes of the vr experience helper
  102153. */
  102154. VRExperienceHelper.prototype.dispose = function () {
  102155. if (this.isInVRMode) {
  102156. this.exitVR();
  102157. }
  102158. if (this._postProcessMove) {
  102159. this._postProcessMove.dispose();
  102160. }
  102161. if (this._webVRCamera) {
  102162. this._webVRCamera.dispose();
  102163. }
  102164. if (this._vrDeviceOrientationCamera) {
  102165. this._vrDeviceOrientationCamera.dispose();
  102166. }
  102167. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  102168. document.body.removeChild(this._btnVR);
  102169. }
  102170. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  102171. this._deviceOrientationCamera.dispose();
  102172. }
  102173. if (this._cameraGazer) {
  102174. this._cameraGazer.dispose();
  102175. }
  102176. if (this._leftController) {
  102177. this._leftController.dispose();
  102178. }
  102179. if (this._rightController) {
  102180. this._rightController.dispose();
  102181. }
  102182. if (this._teleportationTarget) {
  102183. this._teleportationTarget.dispose();
  102184. }
  102185. this._floorMeshesCollection = [];
  102186. document.removeEventListener("keydown", this._onKeyDown);
  102187. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102188. window.removeEventListener("resize", this._onResize);
  102189. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  102190. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  102191. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  102192. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  102193. document.onmsfullscreenchange = null;
  102194. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  102195. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  102196. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  102197. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102198. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  102199. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  102200. this._scene.unregisterBeforeRender(this.beforeRender);
  102201. };
  102202. /**
  102203. * Gets the name of the VRExperienceHelper class
  102204. * @returns "VRExperienceHelper"
  102205. */
  102206. VRExperienceHelper.prototype.getClassName = function () {
  102207. return "VRExperienceHelper";
  102208. };
  102209. return VRExperienceHelper;
  102210. }());
  102211. BABYLON.VRExperienceHelper = VRExperienceHelper;
  102212. })(BABYLON || (BABYLON = {}));
  102213. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  102214. // Mainly based on these 2 articles :
  102215. // 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
  102216. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  102217. var BABYLON;
  102218. (function (BABYLON) {
  102219. /**
  102220. * Defines the potential axis of a Joystick
  102221. */
  102222. var JoystickAxis;
  102223. (function (JoystickAxis) {
  102224. /** X axis */
  102225. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  102226. /** Y axis */
  102227. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  102228. /** Z axis */
  102229. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  102230. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  102231. /**
  102232. * Class used to define virtual joystick (used in touch mode)
  102233. */
  102234. var VirtualJoystick = /** @class */ (function () {
  102235. /**
  102236. * Creates a new virtual joystick
  102237. * @param leftJoystick defines that the joystick is for left hand (false by default)
  102238. */
  102239. function VirtualJoystick(leftJoystick) {
  102240. var _this = this;
  102241. if (leftJoystick) {
  102242. this._leftJoystick = true;
  102243. }
  102244. else {
  102245. this._leftJoystick = false;
  102246. }
  102247. VirtualJoystick._globalJoystickIndex++;
  102248. // By default left & right arrow keys are moving the X
  102249. // and up & down keys are moving the Y
  102250. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102251. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102252. this.reverseLeftRight = false;
  102253. this.reverseUpDown = false;
  102254. // collections of pointers
  102255. this._touches = new BABYLON.StringDictionary();
  102256. this.deltaPosition = BABYLON.Vector3.Zero();
  102257. this._joystickSensibility = 25;
  102258. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102259. this._onResize = function (evt) {
  102260. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102261. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102262. if (VirtualJoystick.vjCanvas) {
  102263. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  102264. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  102265. }
  102266. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  102267. };
  102268. // injecting a canvas element on top of the canvas 3D game
  102269. if (!VirtualJoystick.vjCanvas) {
  102270. window.addEventListener("resize", this._onResize, false);
  102271. VirtualJoystick.vjCanvas = document.createElement("canvas");
  102272. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102273. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102274. VirtualJoystick.vjCanvas.width = window.innerWidth;
  102275. VirtualJoystick.vjCanvas.height = window.innerHeight;
  102276. VirtualJoystick.vjCanvas.style.width = "100%";
  102277. VirtualJoystick.vjCanvas.style.height = "100%";
  102278. VirtualJoystick.vjCanvas.style.position = "absolute";
  102279. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  102280. VirtualJoystick.vjCanvas.style.top = "0px";
  102281. VirtualJoystick.vjCanvas.style.left = "0px";
  102282. VirtualJoystick.vjCanvas.style.zIndex = "5";
  102283. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  102284. // Support for jQuery PEP polyfill
  102285. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  102286. var context = VirtualJoystick.vjCanvas.getContext('2d');
  102287. if (!context) {
  102288. throw new Error("Unable to create canvas for virtual joystick");
  102289. }
  102290. VirtualJoystick.vjCanvasContext = context;
  102291. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  102292. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102293. document.body.appendChild(VirtualJoystick.vjCanvas);
  102294. }
  102295. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  102296. this.pressed = false;
  102297. // default joystick color
  102298. this._joystickColor = "cyan";
  102299. this._joystickPointerID = -1;
  102300. // current joystick position
  102301. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  102302. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  102303. // origin joystick position
  102304. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  102305. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  102306. this._onPointerDownHandlerRef = function (evt) {
  102307. _this._onPointerDown(evt);
  102308. };
  102309. this._onPointerMoveHandlerRef = function (evt) {
  102310. _this._onPointerMove(evt);
  102311. };
  102312. this._onPointerUpHandlerRef = function (evt) {
  102313. _this._onPointerUp(evt);
  102314. };
  102315. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  102316. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  102317. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  102318. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  102319. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  102320. evt.preventDefault(); // Disables system menu
  102321. }, false);
  102322. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102323. }
  102324. /**
  102325. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  102326. * @param newJoystickSensibility defines the new sensibility
  102327. */
  102328. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  102329. this._joystickSensibility = newJoystickSensibility;
  102330. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102331. };
  102332. VirtualJoystick.prototype._onPointerDown = function (e) {
  102333. var positionOnScreenCondition;
  102334. e.preventDefault();
  102335. if (this._leftJoystick === true) {
  102336. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  102337. }
  102338. else {
  102339. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  102340. }
  102341. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  102342. // First contact will be dedicated to the virtual joystick
  102343. this._joystickPointerID = e.pointerId;
  102344. this._joystickPointerStartPos.x = e.clientX;
  102345. this._joystickPointerStartPos.y = e.clientY;
  102346. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  102347. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  102348. this._deltaJoystickVector.x = 0;
  102349. this._deltaJoystickVector.y = 0;
  102350. this.pressed = true;
  102351. this._touches.add(e.pointerId.toString(), e);
  102352. }
  102353. else {
  102354. // You can only trigger the action buttons with a joystick declared
  102355. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  102356. this._action();
  102357. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  102358. }
  102359. }
  102360. };
  102361. VirtualJoystick.prototype._onPointerMove = function (e) {
  102362. // If the current pointer is the one associated to the joystick (first touch contact)
  102363. if (this._joystickPointerID == e.pointerId) {
  102364. this._joystickPointerPos.x = e.clientX;
  102365. this._joystickPointerPos.y = e.clientY;
  102366. this._deltaJoystickVector = this._joystickPointerPos.clone();
  102367. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  102368. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  102369. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  102370. switch (this._axisTargetedByLeftAndRight) {
  102371. case JoystickAxis.X:
  102372. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  102373. break;
  102374. case JoystickAxis.Y:
  102375. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  102376. break;
  102377. case JoystickAxis.Z:
  102378. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  102379. break;
  102380. }
  102381. var directionUpDown = this.reverseUpDown ? 1 : -1;
  102382. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  102383. switch (this._axisTargetedByUpAndDown) {
  102384. case JoystickAxis.X:
  102385. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  102386. break;
  102387. case JoystickAxis.Y:
  102388. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  102389. break;
  102390. case JoystickAxis.Z:
  102391. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  102392. break;
  102393. }
  102394. }
  102395. else {
  102396. var data = this._touches.get(e.pointerId.toString());
  102397. if (data) {
  102398. data.x = e.clientX;
  102399. data.y = e.clientY;
  102400. }
  102401. }
  102402. };
  102403. VirtualJoystick.prototype._onPointerUp = function (e) {
  102404. if (this._joystickPointerID == e.pointerId) {
  102405. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  102406. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  102407. this._joystickPointerID = -1;
  102408. this.pressed = false;
  102409. }
  102410. else {
  102411. var touch = this._touches.get(e.pointerId.toString());
  102412. if (touch) {
  102413. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102414. }
  102415. }
  102416. this._deltaJoystickVector.x = 0;
  102417. this._deltaJoystickVector.y = 0;
  102418. this._touches.remove(e.pointerId.toString());
  102419. };
  102420. /**
  102421. * Change the color of the virtual joystick
  102422. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  102423. */
  102424. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  102425. this._joystickColor = newColor;
  102426. };
  102427. /**
  102428. * Defines a callback to call when the joystick is touched
  102429. * @param action defines the callback
  102430. */
  102431. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  102432. this._action = action;
  102433. };
  102434. /**
  102435. * Defines which axis you'd like to control for left & right
  102436. * @param axis defines the axis to use
  102437. */
  102438. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  102439. switch (axis) {
  102440. case JoystickAxis.X:
  102441. case JoystickAxis.Y:
  102442. case JoystickAxis.Z:
  102443. this._axisTargetedByLeftAndRight = axis;
  102444. break;
  102445. default:
  102446. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102447. break;
  102448. }
  102449. };
  102450. /**
  102451. * Defines which axis you'd like to control for up & down
  102452. * @param axis defines the axis to use
  102453. */
  102454. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  102455. switch (axis) {
  102456. case JoystickAxis.X:
  102457. case JoystickAxis.Y:
  102458. case JoystickAxis.Z:
  102459. this._axisTargetedByUpAndDown = axis;
  102460. break;
  102461. default:
  102462. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102463. break;
  102464. }
  102465. };
  102466. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  102467. var _this = this;
  102468. if (this.pressed) {
  102469. this._touches.forEach(function (key, touch) {
  102470. if (touch.pointerId === _this._joystickPointerID) {
  102471. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  102472. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  102473. VirtualJoystick.vjCanvasContext.beginPath();
  102474. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102475. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102476. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  102477. VirtualJoystick.vjCanvasContext.stroke();
  102478. VirtualJoystick.vjCanvasContext.closePath();
  102479. VirtualJoystick.vjCanvasContext.beginPath();
  102480. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102481. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102482. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  102483. VirtualJoystick.vjCanvasContext.stroke();
  102484. VirtualJoystick.vjCanvasContext.closePath();
  102485. VirtualJoystick.vjCanvasContext.beginPath();
  102486. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102487. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  102488. VirtualJoystick.vjCanvasContext.stroke();
  102489. VirtualJoystick.vjCanvasContext.closePath();
  102490. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  102491. }
  102492. else {
  102493. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102494. VirtualJoystick.vjCanvasContext.beginPath();
  102495. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  102496. VirtualJoystick.vjCanvasContext.beginPath();
  102497. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  102498. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102499. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  102500. VirtualJoystick.vjCanvasContext.stroke();
  102501. VirtualJoystick.vjCanvasContext.closePath();
  102502. touch.prevX = touch.x;
  102503. touch.prevY = touch.y;
  102504. }
  102505. ;
  102506. });
  102507. }
  102508. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102509. };
  102510. /**
  102511. * Release internal HTML canvas
  102512. */
  102513. VirtualJoystick.prototype.releaseCanvas = function () {
  102514. if (VirtualJoystick.vjCanvas) {
  102515. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  102516. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  102517. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  102518. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  102519. window.removeEventListener("resize", this._onResize);
  102520. document.body.removeChild(VirtualJoystick.vjCanvas);
  102521. VirtualJoystick.vjCanvas = null;
  102522. }
  102523. };
  102524. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  102525. VirtualJoystick._globalJoystickIndex = 0;
  102526. return VirtualJoystick;
  102527. }());
  102528. BABYLON.VirtualJoystick = VirtualJoystick;
  102529. })(BABYLON || (BABYLON = {}));
  102530. //# sourceMappingURL=babylon.virtualJoystick.js.map
  102531. var BABYLON;
  102532. (function (BABYLON) {
  102533. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  102534. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  102535. });
  102536. /**
  102537. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  102538. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102539. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102540. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102541. */
  102542. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  102543. __extends(VirtualJoysticksCamera, _super);
  102544. /**
  102545. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  102546. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102547. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102548. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102549. * @param name Define the name of the camera in the scene
  102550. * @param position Define the start position of the camera in the scene
  102551. * @param scene Define the scene the camera belongs to
  102552. */
  102553. function VirtualJoysticksCamera(name, position, scene) {
  102554. var _this = _super.call(this, name, position, scene) || this;
  102555. _this.inputs.addVirtualJoystick();
  102556. return _this;
  102557. }
  102558. /**
  102559. * Gets the current object class name.
  102560. * @return the class name
  102561. */
  102562. VirtualJoysticksCamera.prototype.getClassName = function () {
  102563. return "VirtualJoysticksCamera";
  102564. };
  102565. return VirtualJoysticksCamera;
  102566. }(BABYLON.FreeCamera));
  102567. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  102568. })(BABYLON || (BABYLON = {}));
  102569. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  102570. var BABYLON;
  102571. (function (BABYLON) {
  102572. /**
  102573. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  102574. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  102575. */
  102576. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  102577. function FreeCameraVirtualJoystickInput() {
  102578. }
  102579. /**
  102580. * Gets the left stick of the virtual joystick.
  102581. * @returns The virtual Joystick
  102582. */
  102583. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  102584. return this._leftjoystick;
  102585. };
  102586. /**
  102587. * Gets the right stick of the virtual joystick.
  102588. * @returns The virtual Joystick
  102589. */
  102590. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  102591. return this._rightjoystick;
  102592. };
  102593. /**
  102594. * Update the current camera state depending on the inputs that have been used this frame.
  102595. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  102596. */
  102597. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  102598. if (this._leftjoystick) {
  102599. var camera = this.camera;
  102600. var speed = camera._computeLocalCameraSpeed() * 50;
  102601. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  102602. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  102603. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  102604. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  102605. if (!this._leftjoystick.pressed) {
  102606. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  102607. }
  102608. if (!this._rightjoystick.pressed) {
  102609. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  102610. }
  102611. }
  102612. };
  102613. /**
  102614. * Attach the input controls to a specific dom element to get the input from.
  102615. * @param element Defines the element the controls should be listened from
  102616. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  102617. */
  102618. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  102619. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  102620. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  102621. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  102622. this._leftjoystick.setJoystickSensibility(0.15);
  102623. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  102624. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  102625. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  102626. this._rightjoystick.reverseUpDown = true;
  102627. this._rightjoystick.setJoystickSensibility(0.05);
  102628. this._rightjoystick.setJoystickColor("yellow");
  102629. };
  102630. /**
  102631. * Detach the current controls from the specified dom element.
  102632. * @param element Defines the element to stop listening the inputs from
  102633. */
  102634. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  102635. this._leftjoystick.releaseCanvas();
  102636. this._rightjoystick.releaseCanvas();
  102637. };
  102638. /**
  102639. * Gets the class name of the current intput.
  102640. * @returns the class name
  102641. */
  102642. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  102643. return "FreeCameraVirtualJoystickInput";
  102644. };
  102645. /**
  102646. * Get the friendly name associated with the input class.
  102647. * @returns the input friendly name
  102648. */
  102649. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  102650. return "virtualJoystick";
  102651. };
  102652. return FreeCameraVirtualJoystickInput;
  102653. }());
  102654. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  102655. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  102656. })(BABYLON || (BABYLON = {}));
  102657. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  102658. var BABYLON;
  102659. (function (BABYLON) {
  102660. var SimplificationSettings = /** @class */ (function () {
  102661. function SimplificationSettings(quality, distance, optimizeMesh) {
  102662. this.quality = quality;
  102663. this.distance = distance;
  102664. this.optimizeMesh = optimizeMesh;
  102665. }
  102666. return SimplificationSettings;
  102667. }());
  102668. BABYLON.SimplificationSettings = SimplificationSettings;
  102669. var SimplificationQueue = /** @class */ (function () {
  102670. function SimplificationQueue() {
  102671. this.running = false;
  102672. this._simplificationArray = [];
  102673. }
  102674. SimplificationQueue.prototype.addTask = function (task) {
  102675. this._simplificationArray.push(task);
  102676. };
  102677. SimplificationQueue.prototype.executeNext = function () {
  102678. var task = this._simplificationArray.pop();
  102679. if (task) {
  102680. this.running = true;
  102681. this.runSimplification(task);
  102682. }
  102683. else {
  102684. this.running = false;
  102685. }
  102686. };
  102687. SimplificationQueue.prototype.runSimplification = function (task) {
  102688. var _this = this;
  102689. if (task.parallelProcessing) {
  102690. //parallel simplifier
  102691. task.settings.forEach(function (setting) {
  102692. var simplifier = _this.getSimplifier(task);
  102693. simplifier.simplify(setting, function (newMesh) {
  102694. task.mesh.addLODLevel(setting.distance, newMesh);
  102695. newMesh.isVisible = true;
  102696. //check if it is the last
  102697. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  102698. //all done, run the success callback.
  102699. task.successCallback();
  102700. }
  102701. _this.executeNext();
  102702. });
  102703. });
  102704. }
  102705. else {
  102706. //single simplifier.
  102707. var simplifier = this.getSimplifier(task);
  102708. var runDecimation = function (setting, callback) {
  102709. simplifier.simplify(setting, function (newMesh) {
  102710. task.mesh.addLODLevel(setting.distance, newMesh);
  102711. newMesh.isVisible = true;
  102712. //run the next quality level
  102713. callback();
  102714. });
  102715. };
  102716. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  102717. runDecimation(task.settings[loop.index], function () {
  102718. loop.executeNext();
  102719. });
  102720. }, function () {
  102721. //execution ended, run the success callback.
  102722. if (task.successCallback) {
  102723. task.successCallback();
  102724. }
  102725. _this.executeNext();
  102726. });
  102727. }
  102728. };
  102729. SimplificationQueue.prototype.getSimplifier = function (task) {
  102730. switch (task.simplificationType) {
  102731. case SimplificationType.QUADRATIC:
  102732. default:
  102733. return new QuadraticErrorSimplification(task.mesh);
  102734. }
  102735. };
  102736. return SimplificationQueue;
  102737. }());
  102738. BABYLON.SimplificationQueue = SimplificationQueue;
  102739. /**
  102740. * The implemented types of simplification
  102741. * At the moment only Quadratic Error Decimation is implemented
  102742. */
  102743. var SimplificationType;
  102744. (function (SimplificationType) {
  102745. /** Quadratic error decimation */
  102746. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  102747. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  102748. var DecimationTriangle = /** @class */ (function () {
  102749. function DecimationTriangle(vertices) {
  102750. this.vertices = vertices;
  102751. this.error = new Array(4);
  102752. this.deleted = false;
  102753. this.isDirty = false;
  102754. this.deletePending = false;
  102755. this.borderFactor = 0;
  102756. }
  102757. return DecimationTriangle;
  102758. }());
  102759. BABYLON.DecimationTriangle = DecimationTriangle;
  102760. var DecimationVertex = /** @class */ (function () {
  102761. function DecimationVertex(position, id) {
  102762. this.position = position;
  102763. this.id = id;
  102764. this.isBorder = true;
  102765. this.q = new QuadraticMatrix();
  102766. this.triangleCount = 0;
  102767. this.triangleStart = 0;
  102768. this.originalOffsets = [];
  102769. }
  102770. DecimationVertex.prototype.updatePosition = function (newPosition) {
  102771. this.position.copyFrom(newPosition);
  102772. };
  102773. return DecimationVertex;
  102774. }());
  102775. BABYLON.DecimationVertex = DecimationVertex;
  102776. var QuadraticMatrix = /** @class */ (function () {
  102777. function QuadraticMatrix(data) {
  102778. this.data = new Array(10);
  102779. for (var i = 0; i < 10; ++i) {
  102780. if (data && data[i]) {
  102781. this.data[i] = data[i];
  102782. }
  102783. else {
  102784. this.data[i] = 0;
  102785. }
  102786. }
  102787. }
  102788. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  102789. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  102790. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  102791. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  102792. return det;
  102793. };
  102794. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  102795. for (var i = 0; i < 10; ++i) {
  102796. this.data[i] += matrix.data[i];
  102797. }
  102798. };
  102799. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  102800. for (var i = 0; i < 10; ++i) {
  102801. this.data[i] += data[i];
  102802. }
  102803. };
  102804. QuadraticMatrix.prototype.add = function (matrix) {
  102805. var m = new QuadraticMatrix();
  102806. for (var i = 0; i < 10; ++i) {
  102807. m.data[i] = this.data[i] + matrix.data[i];
  102808. }
  102809. return m;
  102810. };
  102811. QuadraticMatrix.FromData = function (a, b, c, d) {
  102812. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  102813. };
  102814. //returning an array to avoid garbage collection
  102815. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  102816. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  102817. };
  102818. return QuadraticMatrix;
  102819. }());
  102820. BABYLON.QuadraticMatrix = QuadraticMatrix;
  102821. var Reference = /** @class */ (function () {
  102822. function Reference(vertexId, triangleId) {
  102823. this.vertexId = vertexId;
  102824. this.triangleId = triangleId;
  102825. }
  102826. return Reference;
  102827. }());
  102828. BABYLON.Reference = Reference;
  102829. /**
  102830. * An implementation of the Quadratic Error simplification algorithm.
  102831. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  102832. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  102833. * @author RaananW
  102834. */
  102835. var QuadraticErrorSimplification = /** @class */ (function () {
  102836. function QuadraticErrorSimplification(_mesh) {
  102837. this._mesh = _mesh;
  102838. this.syncIterations = 5000;
  102839. this.aggressiveness = 7;
  102840. this.decimationIterations = 100;
  102841. this.boundingBoxEpsilon = BABYLON.Epsilon;
  102842. }
  102843. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  102844. var _this = this;
  102845. this.initDecimatedMesh();
  102846. //iterating through the submeshes array, one after the other.
  102847. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  102848. _this.initWithMesh(loop.index, function () {
  102849. _this.runDecimation(settings, loop.index, function () {
  102850. loop.executeNext();
  102851. });
  102852. }, settings.optimizeMesh);
  102853. }, function () {
  102854. setTimeout(function () {
  102855. successCallback(_this._reconstructedMesh);
  102856. }, 0);
  102857. });
  102858. };
  102859. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  102860. var _this = this;
  102861. var targetCount = ~~(this.triangles.length * settings.quality);
  102862. var deletedTriangles = 0;
  102863. var triangleCount = this.triangles.length;
  102864. var iterationFunction = function (iteration, callback) {
  102865. setTimeout(function () {
  102866. if (iteration % 5 === 0) {
  102867. _this.updateMesh(iteration === 0);
  102868. }
  102869. for (var i = 0; i < _this.triangles.length; ++i) {
  102870. _this.triangles[i].isDirty = false;
  102871. }
  102872. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  102873. var trianglesIterator = function (i) {
  102874. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  102875. var t = _this.triangles[tIdx];
  102876. if (!t)
  102877. return;
  102878. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  102879. return;
  102880. }
  102881. for (var j = 0; j < 3; ++j) {
  102882. if (t.error[j] < threshold) {
  102883. var deleted0 = [];
  102884. var deleted1 = [];
  102885. var v0 = t.vertices[j];
  102886. var v1 = t.vertices[(j + 1) % 3];
  102887. if (v0.isBorder || v1.isBorder)
  102888. continue;
  102889. var p = BABYLON.Vector3.Zero();
  102890. var n = BABYLON.Vector3.Zero();
  102891. var uv = BABYLON.Vector2.Zero();
  102892. var color = new BABYLON.Color4(0, 0, 0, 1);
  102893. _this.calculateError(v0, v1, p, n, uv, color);
  102894. var delTr = new Array();
  102895. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  102896. continue;
  102897. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  102898. continue;
  102899. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  102900. continue;
  102901. var uniqueArray = new Array();
  102902. delTr.forEach(function (deletedT) {
  102903. if (uniqueArray.indexOf(deletedT) === -1) {
  102904. deletedT.deletePending = true;
  102905. uniqueArray.push(deletedT);
  102906. }
  102907. });
  102908. if (uniqueArray.length % 2 !== 0) {
  102909. continue;
  102910. }
  102911. v0.q = v1.q.add(v0.q);
  102912. v0.updatePosition(p);
  102913. var tStart = _this.references.length;
  102914. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  102915. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  102916. var tCount = _this.references.length - tStart;
  102917. if (tCount <= v0.triangleCount) {
  102918. if (tCount) {
  102919. for (var c = 0; c < tCount; c++) {
  102920. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  102921. }
  102922. }
  102923. }
  102924. else {
  102925. v0.triangleStart = tStart;
  102926. }
  102927. v0.triangleCount = tCount;
  102928. break;
  102929. }
  102930. }
  102931. };
  102932. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  102933. }, 0);
  102934. };
  102935. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  102936. if (triangleCount - deletedTriangles <= targetCount)
  102937. loop.breakLoop();
  102938. else {
  102939. iterationFunction(loop.index, function () {
  102940. loop.executeNext();
  102941. });
  102942. }
  102943. }, function () {
  102944. setTimeout(function () {
  102945. //reconstruct this part of the mesh
  102946. _this.reconstructMesh(submeshIndex);
  102947. successCallback();
  102948. }, 0);
  102949. });
  102950. };
  102951. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  102952. var _this = this;
  102953. this.vertices = [];
  102954. this.triangles = [];
  102955. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102956. var indices = this._mesh.getIndices();
  102957. var submesh = this._mesh.subMeshes[submeshIndex];
  102958. var findInVertices = function (positionToSearch) {
  102959. if (optimizeMesh) {
  102960. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  102961. if (_this.vertices[ii].position.equals(positionToSearch)) {
  102962. return _this.vertices[ii];
  102963. }
  102964. }
  102965. }
  102966. return null;
  102967. };
  102968. var vertexReferences = [];
  102969. var vertexInit = function (i) {
  102970. if (!positionData) {
  102971. return;
  102972. }
  102973. var offset = i + submesh.verticesStart;
  102974. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  102975. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  102976. vertex.originalOffsets.push(offset);
  102977. if (vertex.id === _this.vertices.length) {
  102978. _this.vertices.push(vertex);
  102979. }
  102980. vertexReferences.push(vertex.id);
  102981. };
  102982. //var totalVertices = mesh.getTotalVertices();
  102983. var totalVertices = submesh.verticesCount;
  102984. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  102985. var indicesInit = function (i) {
  102986. if (!indices) {
  102987. return;
  102988. }
  102989. var offset = (submesh.indexStart / 3) + i;
  102990. var pos = (offset * 3);
  102991. var i0 = indices[pos + 0];
  102992. var i1 = indices[pos + 1];
  102993. var i2 = indices[pos + 2];
  102994. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  102995. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  102996. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  102997. var triangle = new DecimationTriangle([v0, v1, v2]);
  102998. triangle.originalOffset = pos;
  102999. _this.triangles.push(triangle);
  103000. };
  103001. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  103002. _this.init(callback);
  103003. });
  103004. });
  103005. };
  103006. QuadraticErrorSimplification.prototype.init = function (callback) {
  103007. var _this = this;
  103008. var triangleInit1 = function (i) {
  103009. var t = _this.triangles[i];
  103010. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  103011. for (var j = 0; j < 3; j++) {
  103012. 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))));
  103013. }
  103014. };
  103015. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  103016. var triangleInit2 = function (i) {
  103017. var t = _this.triangles[i];
  103018. for (var j = 0; j < 3; ++j) {
  103019. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  103020. }
  103021. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103022. };
  103023. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  103024. callback();
  103025. });
  103026. });
  103027. };
  103028. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  103029. var newTriangles = [];
  103030. var i;
  103031. for (i = 0; i < this.vertices.length; ++i) {
  103032. this.vertices[i].triangleCount = 0;
  103033. }
  103034. var t;
  103035. var j;
  103036. for (i = 0; i < this.triangles.length; ++i) {
  103037. if (!this.triangles[i].deleted) {
  103038. t = this.triangles[i];
  103039. for (j = 0; j < 3; ++j) {
  103040. t.vertices[j].triangleCount = 1;
  103041. }
  103042. newTriangles.push(t);
  103043. }
  103044. }
  103045. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  103046. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  103047. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  103048. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  103049. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  103050. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  103051. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  103052. var vertexCount = 0;
  103053. for (i = 0; i < this.vertices.length; ++i) {
  103054. var vertex = this.vertices[i];
  103055. vertex.id = vertexCount;
  103056. if (vertex.triangleCount) {
  103057. vertex.originalOffsets.forEach(function (originalOffset) {
  103058. if (!normalData) {
  103059. return;
  103060. }
  103061. newPositionData.push(vertex.position.x);
  103062. newPositionData.push(vertex.position.y);
  103063. newPositionData.push(vertex.position.z);
  103064. newNormalData.push(normalData[originalOffset * 3]);
  103065. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  103066. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  103067. if (uvs && uvs.length) {
  103068. newUVsData.push(uvs[(originalOffset * 2)]);
  103069. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  103070. }
  103071. else if (colorsData && colorsData.length) {
  103072. newColorsData.push(colorsData[(originalOffset * 4)]);
  103073. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  103074. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  103075. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  103076. }
  103077. ++vertexCount;
  103078. });
  103079. }
  103080. }
  103081. var startingIndex = this._reconstructedMesh.getTotalIndices();
  103082. var startingVertex = this._reconstructedMesh.getTotalVertices();
  103083. var submeshesArray = this._reconstructedMesh.subMeshes;
  103084. this._reconstructedMesh.subMeshes = [];
  103085. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  103086. var originalIndices = this._mesh.getIndices();
  103087. for (i = 0; i < newTriangles.length; ++i) {
  103088. t = newTriangles[i]; //now get the new referencing point for each vertex
  103089. [0, 1, 2].forEach(function (idx) {
  103090. var id = originalIndices[t.originalOffset + idx];
  103091. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  103092. if (offset < 0)
  103093. offset = 0;
  103094. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  103095. });
  103096. }
  103097. //overwriting the old vertex buffers and indices.
  103098. this._reconstructedMesh.setIndices(newIndicesArray);
  103099. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  103100. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  103101. if (newUVsData.length > 0)
  103102. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  103103. if (newColorsData.length > 0)
  103104. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  103105. //create submesh
  103106. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  103107. if (submeshIndex > 0) {
  103108. this._reconstructedMesh.subMeshes = [];
  103109. submeshesArray.forEach(function (submesh) {
  103110. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  103111. });
  103112. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  103113. }
  103114. };
  103115. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  103116. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  103117. this._reconstructedMesh.material = this._mesh.material;
  103118. this._reconstructedMesh.parent = this._mesh.parent;
  103119. this._reconstructedMesh.isVisible = false;
  103120. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  103121. };
  103122. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  103123. for (var i = 0; i < vertex1.triangleCount; ++i) {
  103124. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  103125. if (t.deleted)
  103126. continue;
  103127. var s = this.references[vertex1.triangleStart + i].vertexId;
  103128. var v1 = t.vertices[(s + 1) % 3];
  103129. var v2 = t.vertices[(s + 2) % 3];
  103130. if ((v1 === vertex2 || v2 === vertex2)) {
  103131. deletedArray[i] = true;
  103132. delTr.push(t);
  103133. continue;
  103134. }
  103135. var d1 = v1.position.subtract(point);
  103136. d1 = d1.normalize();
  103137. var d2 = v2.position.subtract(point);
  103138. d2 = d2.normalize();
  103139. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  103140. return true;
  103141. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  103142. deletedArray[i] = false;
  103143. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  103144. return true;
  103145. }
  103146. return false;
  103147. };
  103148. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  103149. var newDeleted = deletedTriangles;
  103150. for (var i = 0; i < vertex.triangleCount; ++i) {
  103151. var ref = this.references[vertex.triangleStart + i];
  103152. var t = this.triangles[ref.triangleId];
  103153. if (t.deleted)
  103154. continue;
  103155. if (deletedArray[i] && t.deletePending) {
  103156. t.deleted = true;
  103157. newDeleted++;
  103158. continue;
  103159. }
  103160. t.vertices[ref.vertexId] = origVertex;
  103161. t.isDirty = true;
  103162. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  103163. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  103164. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  103165. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103166. this.references.push(ref);
  103167. }
  103168. return newDeleted;
  103169. };
  103170. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  103171. for (var i = 0; i < this.vertices.length; ++i) {
  103172. var vCount = [];
  103173. var vId = [];
  103174. var v = this.vertices[i];
  103175. var j;
  103176. for (j = 0; j < v.triangleCount; ++j) {
  103177. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  103178. for (var ii = 0; ii < 3; ii++) {
  103179. var ofs = 0;
  103180. var vv = triangle.vertices[ii];
  103181. while (ofs < vCount.length) {
  103182. if (vId[ofs] === vv.id)
  103183. break;
  103184. ++ofs;
  103185. }
  103186. if (ofs === vCount.length) {
  103187. vCount.push(1);
  103188. vId.push(vv.id);
  103189. }
  103190. else {
  103191. vCount[ofs]++;
  103192. }
  103193. }
  103194. }
  103195. for (j = 0; j < vCount.length; ++j) {
  103196. if (vCount[j] === 1) {
  103197. this.vertices[vId[j]].isBorder = true;
  103198. }
  103199. else {
  103200. this.vertices[vId[j]].isBorder = false;
  103201. }
  103202. }
  103203. }
  103204. };
  103205. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  103206. if (identifyBorders === void 0) { identifyBorders = false; }
  103207. var i;
  103208. if (!identifyBorders) {
  103209. var newTrianglesVector = [];
  103210. for (i = 0; i < this.triangles.length; ++i) {
  103211. if (!this.triangles[i].deleted) {
  103212. newTrianglesVector.push(this.triangles[i]);
  103213. }
  103214. }
  103215. this.triangles = newTrianglesVector;
  103216. }
  103217. for (i = 0; i < this.vertices.length; ++i) {
  103218. this.vertices[i].triangleCount = 0;
  103219. this.vertices[i].triangleStart = 0;
  103220. }
  103221. var t;
  103222. var j;
  103223. var v;
  103224. for (i = 0; i < this.triangles.length; ++i) {
  103225. t = this.triangles[i];
  103226. for (j = 0; j < 3; ++j) {
  103227. v = t.vertices[j];
  103228. v.triangleCount++;
  103229. }
  103230. }
  103231. var tStart = 0;
  103232. for (i = 0; i < this.vertices.length; ++i) {
  103233. this.vertices[i].triangleStart = tStart;
  103234. tStart += this.vertices[i].triangleCount;
  103235. this.vertices[i].triangleCount = 0;
  103236. }
  103237. var newReferences = new Array(this.triangles.length * 3);
  103238. for (i = 0; i < this.triangles.length; ++i) {
  103239. t = this.triangles[i];
  103240. for (j = 0; j < 3; ++j) {
  103241. v = t.vertices[j];
  103242. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  103243. v.triangleCount++;
  103244. }
  103245. }
  103246. this.references = newReferences;
  103247. if (identifyBorders) {
  103248. this.identifyBorder();
  103249. }
  103250. };
  103251. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  103252. var x = point.x;
  103253. var y = point.y;
  103254. var z = point.z;
  103255. 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
  103256. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  103257. };
  103258. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  103259. var q = vertex1.q.add(vertex2.q);
  103260. var border = vertex1.isBorder && vertex2.isBorder;
  103261. var error = 0;
  103262. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  103263. if (qDet !== 0 && !border) {
  103264. if (!pointResult) {
  103265. pointResult = BABYLON.Vector3.Zero();
  103266. }
  103267. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  103268. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  103269. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  103270. error = this.vertexError(q, pointResult);
  103271. }
  103272. else {
  103273. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  103274. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  103275. var error1 = this.vertexError(q, vertex1.position);
  103276. var error2 = this.vertexError(q, vertex2.position);
  103277. var error3 = this.vertexError(q, p3);
  103278. error = Math.min(error1, error2, error3);
  103279. if (error === error1) {
  103280. if (pointResult) {
  103281. pointResult.copyFrom(vertex1.position);
  103282. }
  103283. }
  103284. else if (error === error2) {
  103285. if (pointResult) {
  103286. pointResult.copyFrom(vertex2.position);
  103287. }
  103288. }
  103289. else {
  103290. if (pointResult) {
  103291. pointResult.copyFrom(p3);
  103292. }
  103293. }
  103294. }
  103295. return error;
  103296. };
  103297. return QuadraticErrorSimplification;
  103298. }());
  103299. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  103300. })(BABYLON || (BABYLON = {}));
  103301. //# sourceMappingURL=babylon.meshSimplification.js.map
  103302. var BABYLON;
  103303. (function (BABYLON) {
  103304. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  103305. get: function () {
  103306. if (!this._simplificationQueue) {
  103307. this._simplificationQueue = new BABYLON.SimplificationQueue();
  103308. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  103309. if (!component) {
  103310. component = new SimplicationQueueSceneComponent(this);
  103311. this._addComponent(component);
  103312. }
  103313. }
  103314. return this._simplificationQueue;
  103315. },
  103316. set: function (value) {
  103317. this._simplificationQueue = value;
  103318. },
  103319. enumerable: true,
  103320. configurable: true
  103321. });
  103322. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  103323. if (parallelProcessing === void 0) { parallelProcessing = true; }
  103324. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  103325. this.getScene().simplificationQueue.addTask({
  103326. settings: settings,
  103327. parallelProcessing: parallelProcessing,
  103328. mesh: this,
  103329. simplificationType: simplificationType,
  103330. successCallback: successCallback
  103331. });
  103332. return this;
  103333. };
  103334. /**
  103335. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  103336. * created in a scene
  103337. */
  103338. var SimplicationQueueSceneComponent = /** @class */ (function () {
  103339. /**
  103340. * Creates a new instance of the component for the given scene
  103341. * @param scene Defines the scene to register the component in
  103342. */
  103343. function SimplicationQueueSceneComponent(scene) {
  103344. /**
  103345. * The component name helpfull to identify the component in the list of scene components.
  103346. */
  103347. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  103348. this.scene = scene;
  103349. }
  103350. /**
  103351. * Registers the component in a given scene
  103352. */
  103353. SimplicationQueueSceneComponent.prototype.register = function () {
  103354. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  103355. };
  103356. /**
  103357. * Rebuilds the elements related to this component in case of
  103358. * context lost for instance.
  103359. */
  103360. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  103361. // Nothing to do for this component
  103362. };
  103363. /**
  103364. * Disposes the component and the associated ressources
  103365. */
  103366. SimplicationQueueSceneComponent.prototype.dispose = function () {
  103367. // Nothing to do for this component
  103368. };
  103369. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  103370. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  103371. this.scene._simplificationQueue.executeNext();
  103372. }
  103373. };
  103374. return SimplicationQueueSceneComponent;
  103375. }());
  103376. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  103377. })(BABYLON || (BABYLON = {}));
  103378. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  103379. var BABYLON;
  103380. (function (BABYLON) {
  103381. /**
  103382. * Class used to represent a specific level of detail of a mesh
  103383. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  103384. */
  103385. var MeshLODLevel = /** @class */ (function () {
  103386. /**
  103387. * Creates a new LOD level
  103388. * @param distance defines the distance where this level should star being displayed
  103389. * @param mesh defines the mesh to use to render this level
  103390. */
  103391. function MeshLODLevel(
  103392. /** Defines the distance where this level should star being displayed */
  103393. distance,
  103394. /** Defines the mesh to use to render this level */
  103395. mesh) {
  103396. this.distance = distance;
  103397. this.mesh = mesh;
  103398. }
  103399. return MeshLODLevel;
  103400. }());
  103401. BABYLON.MeshLODLevel = MeshLODLevel;
  103402. })(BABYLON || (BABYLON = {}));
  103403. //# sourceMappingURL=babylon.meshLODLevel.js.map
  103404. var BABYLON;
  103405. (function (BABYLON) {
  103406. /**
  103407. * Defines the root class used to create scene optimization to use with SceneOptimizer
  103408. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103409. */
  103410. var SceneOptimization = /** @class */ (function () {
  103411. /**
  103412. * Creates the SceneOptimization object
  103413. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103414. * @param desc defines the description associated with the optimization
  103415. */
  103416. function SceneOptimization(
  103417. /**
  103418. * Defines the priority of this optimization (0 by default which means first in the list)
  103419. */
  103420. priority) {
  103421. if (priority === void 0) { priority = 0; }
  103422. this.priority = priority;
  103423. }
  103424. /**
  103425. * Gets a string describing the action executed by the current optimization
  103426. * @returns description string
  103427. */
  103428. SceneOptimization.prototype.getDescription = function () {
  103429. return "";
  103430. };
  103431. /**
  103432. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103433. * @param scene defines the current scene where to apply this optimization
  103434. * @param optimizer defines the current optimizer
  103435. * @returns true if everything that can be done was applied
  103436. */
  103437. SceneOptimization.prototype.apply = function (scene, optimizer) {
  103438. return true;
  103439. };
  103440. ;
  103441. return SceneOptimization;
  103442. }());
  103443. BABYLON.SceneOptimization = SceneOptimization;
  103444. /**
  103445. * Defines an optimization used to reduce the size of render target textures
  103446. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103447. */
  103448. var TextureOptimization = /** @class */ (function (_super) {
  103449. __extends(TextureOptimization, _super);
  103450. /**
  103451. * Creates the TextureOptimization object
  103452. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103453. * @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
  103454. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103455. */
  103456. function TextureOptimization(
  103457. /**
  103458. * Defines the priority of this optimization (0 by default which means first in the list)
  103459. */
  103460. priority,
  103461. /**
  103462. * 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
  103463. */
  103464. maximumSize,
  103465. /**
  103466. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103467. */
  103468. step) {
  103469. if (priority === void 0) { priority = 0; }
  103470. if (maximumSize === void 0) { maximumSize = 1024; }
  103471. if (step === void 0) { step = 0.5; }
  103472. var _this = _super.call(this, priority) || this;
  103473. _this.priority = priority;
  103474. _this.maximumSize = maximumSize;
  103475. _this.step = step;
  103476. return _this;
  103477. }
  103478. /**
  103479. * Gets a string describing the action executed by the current optimization
  103480. * @returns description string
  103481. */
  103482. TextureOptimization.prototype.getDescription = function () {
  103483. return "Reducing render target texture size to " + this.maximumSize;
  103484. };
  103485. /**
  103486. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103487. * @param scene defines the current scene where to apply this optimization
  103488. * @param optimizer defines the current optimizer
  103489. * @returns true if everything that can be done was applied
  103490. */
  103491. TextureOptimization.prototype.apply = function (scene, optimizer) {
  103492. var allDone = true;
  103493. for (var index = 0; index < scene.textures.length; index++) {
  103494. var texture = scene.textures[index];
  103495. if (!texture.canRescale || texture.getContext) {
  103496. continue;
  103497. }
  103498. var currentSize = texture.getSize();
  103499. var maxDimension = Math.max(currentSize.width, currentSize.height);
  103500. if (maxDimension > this.maximumSize) {
  103501. texture.scale(this.step);
  103502. allDone = false;
  103503. }
  103504. }
  103505. return allDone;
  103506. };
  103507. return TextureOptimization;
  103508. }(SceneOptimization));
  103509. BABYLON.TextureOptimization = TextureOptimization;
  103510. /**
  103511. * Defines an optimization used to increase or decrease the rendering resolution
  103512. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103513. */
  103514. var HardwareScalingOptimization = /** @class */ (function (_super) {
  103515. __extends(HardwareScalingOptimization, _super);
  103516. /**
  103517. * Creates the HardwareScalingOptimization object
  103518. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103519. * @param maximumScale defines the maximum scale to use (2 by default)
  103520. * @param step defines the step to use between two passes (0.5 by default)
  103521. */
  103522. function HardwareScalingOptimization(
  103523. /**
  103524. * Defines the priority of this optimization (0 by default which means first in the list)
  103525. */
  103526. priority,
  103527. /**
  103528. * Defines the maximum scale to use (2 by default)
  103529. */
  103530. maximumScale,
  103531. /**
  103532. * Defines the step to use between two passes (0.5 by default)
  103533. */
  103534. step) {
  103535. if (priority === void 0) { priority = 0; }
  103536. if (maximumScale === void 0) { maximumScale = 2; }
  103537. if (step === void 0) { step = 0.25; }
  103538. var _this = _super.call(this, priority) || this;
  103539. _this.priority = priority;
  103540. _this.maximumScale = maximumScale;
  103541. _this.step = step;
  103542. _this._currentScale = -1;
  103543. _this._directionOffset = 1;
  103544. return _this;
  103545. }
  103546. /**
  103547. * Gets a string describing the action executed by the current optimization
  103548. * @return description string
  103549. */
  103550. HardwareScalingOptimization.prototype.getDescription = function () {
  103551. return "Setting hardware scaling level to " + this._currentScale;
  103552. };
  103553. /**
  103554. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103555. * @param scene defines the current scene where to apply this optimization
  103556. * @param optimizer defines the current optimizer
  103557. * @returns true if everything that can be done was applied
  103558. */
  103559. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  103560. if (this._currentScale === -1) {
  103561. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  103562. if (this._currentScale > this.maximumScale) {
  103563. this._directionOffset = -1;
  103564. }
  103565. }
  103566. this._currentScale += this._directionOffset * this.step;
  103567. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  103568. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  103569. };
  103570. ;
  103571. return HardwareScalingOptimization;
  103572. }(SceneOptimization));
  103573. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  103574. /**
  103575. * Defines an optimization used to remove shadows
  103576. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103577. */
  103578. var ShadowsOptimization = /** @class */ (function (_super) {
  103579. __extends(ShadowsOptimization, _super);
  103580. function ShadowsOptimization() {
  103581. return _super !== null && _super.apply(this, arguments) || this;
  103582. }
  103583. /**
  103584. * Gets a string describing the action executed by the current optimization
  103585. * @return description string
  103586. */
  103587. ShadowsOptimization.prototype.getDescription = function () {
  103588. return "Turning shadows on/off";
  103589. };
  103590. /**
  103591. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103592. * @param scene defines the current scene where to apply this optimization
  103593. * @param optimizer defines the current optimizer
  103594. * @returns true if everything that can be done was applied
  103595. */
  103596. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  103597. scene.shadowsEnabled = optimizer.isInImprovementMode;
  103598. return true;
  103599. };
  103600. ;
  103601. return ShadowsOptimization;
  103602. }(SceneOptimization));
  103603. BABYLON.ShadowsOptimization = ShadowsOptimization;
  103604. /**
  103605. * Defines an optimization used to turn post-processes off
  103606. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103607. */
  103608. var PostProcessesOptimization = /** @class */ (function (_super) {
  103609. __extends(PostProcessesOptimization, _super);
  103610. function PostProcessesOptimization() {
  103611. return _super !== null && _super.apply(this, arguments) || this;
  103612. }
  103613. /**
  103614. * Gets a string describing the action executed by the current optimization
  103615. * @return description string
  103616. */
  103617. PostProcessesOptimization.prototype.getDescription = function () {
  103618. return "Turning post-processes on/off";
  103619. };
  103620. /**
  103621. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103622. * @param scene defines the current scene where to apply this optimization
  103623. * @param optimizer defines the current optimizer
  103624. * @returns true if everything that can be done was applied
  103625. */
  103626. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  103627. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  103628. return true;
  103629. };
  103630. ;
  103631. return PostProcessesOptimization;
  103632. }(SceneOptimization));
  103633. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  103634. /**
  103635. * Defines an optimization used to turn lens flares off
  103636. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103637. */
  103638. var LensFlaresOptimization = /** @class */ (function (_super) {
  103639. __extends(LensFlaresOptimization, _super);
  103640. function LensFlaresOptimization() {
  103641. return _super !== null && _super.apply(this, arguments) || this;
  103642. }
  103643. /**
  103644. * Gets a string describing the action executed by the current optimization
  103645. * @return description string
  103646. */
  103647. LensFlaresOptimization.prototype.getDescription = function () {
  103648. return "Turning lens flares on/off";
  103649. };
  103650. /**
  103651. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103652. * @param scene defines the current scene where to apply this optimization
  103653. * @param optimizer defines the current optimizer
  103654. * @returns true if everything that can be done was applied
  103655. */
  103656. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  103657. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  103658. return true;
  103659. };
  103660. ;
  103661. return LensFlaresOptimization;
  103662. }(SceneOptimization));
  103663. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  103664. /**
  103665. * Defines an optimization based on user defined callback.
  103666. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103667. */
  103668. var CustomOptimization = /** @class */ (function (_super) {
  103669. __extends(CustomOptimization, _super);
  103670. function CustomOptimization() {
  103671. return _super !== null && _super.apply(this, arguments) || this;
  103672. }
  103673. /**
  103674. * Gets a string describing the action executed by the current optimization
  103675. * @returns description string
  103676. */
  103677. CustomOptimization.prototype.getDescription = function () {
  103678. if (this.onGetDescription) {
  103679. return this.onGetDescription();
  103680. }
  103681. return "Running user defined callback";
  103682. };
  103683. /**
  103684. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103685. * @param scene defines the current scene where to apply this optimization
  103686. * @param optimizer defines the current optimizer
  103687. * @returns true if everything that can be done was applied
  103688. */
  103689. CustomOptimization.prototype.apply = function (scene, optimizer) {
  103690. if (this.onApply) {
  103691. return this.onApply(scene, optimizer);
  103692. }
  103693. return true;
  103694. };
  103695. ;
  103696. return CustomOptimization;
  103697. }(SceneOptimization));
  103698. BABYLON.CustomOptimization = CustomOptimization;
  103699. /**
  103700. * Defines an optimization used to turn particles off
  103701. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103702. */
  103703. var ParticlesOptimization = /** @class */ (function (_super) {
  103704. __extends(ParticlesOptimization, _super);
  103705. function ParticlesOptimization() {
  103706. return _super !== null && _super.apply(this, arguments) || this;
  103707. }
  103708. /**
  103709. * Gets a string describing the action executed by the current optimization
  103710. * @return description string
  103711. */
  103712. ParticlesOptimization.prototype.getDescription = function () {
  103713. return "Turning particles on/off";
  103714. };
  103715. /**
  103716. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103717. * @param scene defines the current scene where to apply this optimization
  103718. * @param optimizer defines the current optimizer
  103719. * @returns true if everything that can be done was applied
  103720. */
  103721. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  103722. scene.particlesEnabled = optimizer.isInImprovementMode;
  103723. return true;
  103724. };
  103725. ;
  103726. return ParticlesOptimization;
  103727. }(SceneOptimization));
  103728. BABYLON.ParticlesOptimization = ParticlesOptimization;
  103729. /**
  103730. * Defines an optimization used to turn render targets off
  103731. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103732. */
  103733. var RenderTargetsOptimization = /** @class */ (function (_super) {
  103734. __extends(RenderTargetsOptimization, _super);
  103735. function RenderTargetsOptimization() {
  103736. return _super !== null && _super.apply(this, arguments) || this;
  103737. }
  103738. /**
  103739. * Gets a string describing the action executed by the current optimization
  103740. * @return description string
  103741. */
  103742. RenderTargetsOptimization.prototype.getDescription = function () {
  103743. return "Turning render targets off";
  103744. };
  103745. /**
  103746. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103747. * @param scene defines the current scene where to apply this optimization
  103748. * @param optimizer defines the current optimizer
  103749. * @returns true if everything that can be done was applied
  103750. */
  103751. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  103752. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  103753. return true;
  103754. };
  103755. ;
  103756. return RenderTargetsOptimization;
  103757. }(SceneOptimization));
  103758. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  103759. /**
  103760. * Defines an optimization used to merge meshes with compatible materials
  103761. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103762. */
  103763. var MergeMeshesOptimization = /** @class */ (function (_super) {
  103764. __extends(MergeMeshesOptimization, _super);
  103765. function MergeMeshesOptimization() {
  103766. var _this = _super !== null && _super.apply(this, arguments) || this;
  103767. _this._canBeMerged = function (abstractMesh) {
  103768. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  103769. return false;
  103770. }
  103771. var mesh = abstractMesh;
  103772. if (mesh.isDisposed()) {
  103773. return false;
  103774. }
  103775. if (!mesh.isVisible || !mesh.isEnabled()) {
  103776. return false;
  103777. }
  103778. if (mesh.instances.length > 0) {
  103779. return false;
  103780. }
  103781. if (mesh.skeleton || mesh.hasLODLevels) {
  103782. return false;
  103783. }
  103784. return true;
  103785. };
  103786. return _this;
  103787. }
  103788. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  103789. /**
  103790. * Gets or sets a boolean which defines if optimization octree has to be updated
  103791. */
  103792. get: function () {
  103793. return MergeMeshesOptimization._UpdateSelectionTree;
  103794. },
  103795. /**
  103796. * Gets or sets a boolean which defines if optimization octree has to be updated
  103797. */
  103798. set: function (value) {
  103799. MergeMeshesOptimization._UpdateSelectionTree = value;
  103800. },
  103801. enumerable: true,
  103802. configurable: true
  103803. });
  103804. /**
  103805. * Gets a string describing the action executed by the current optimization
  103806. * @return description string
  103807. */
  103808. MergeMeshesOptimization.prototype.getDescription = function () {
  103809. return "Merging similar meshes together";
  103810. };
  103811. /**
  103812. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103813. * @param scene defines the current scene where to apply this optimization
  103814. * @param optimizer defines the current optimizer
  103815. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  103816. * @returns true if everything that can be done was applied
  103817. */
  103818. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  103819. var globalPool = scene.meshes.slice(0);
  103820. var globalLength = globalPool.length;
  103821. for (var index = 0; index < globalLength; index++) {
  103822. var currentPool = new Array();
  103823. var current = globalPool[index];
  103824. // Checks
  103825. if (!this._canBeMerged(current)) {
  103826. continue;
  103827. }
  103828. currentPool.push(current);
  103829. // Find compatible meshes
  103830. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  103831. var otherMesh = globalPool[subIndex];
  103832. if (!this._canBeMerged(otherMesh)) {
  103833. continue;
  103834. }
  103835. if (otherMesh.material !== current.material) {
  103836. continue;
  103837. }
  103838. if (otherMesh.checkCollisions !== current.checkCollisions) {
  103839. continue;
  103840. }
  103841. currentPool.push(otherMesh);
  103842. globalLength--;
  103843. globalPool.splice(subIndex, 1);
  103844. subIndex--;
  103845. }
  103846. if (currentPool.length < 2) {
  103847. continue;
  103848. }
  103849. // Merge meshes
  103850. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  103851. }
  103852. // Call the octree system optimization if it is defined.
  103853. var sceneAsAny = scene;
  103854. if (sceneAsAny.createOrUpdateSelectionOctree) {
  103855. if (updateSelectionTree != undefined) {
  103856. if (updateSelectionTree) {
  103857. sceneAsAny.createOrUpdateSelectionOctree();
  103858. }
  103859. }
  103860. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  103861. sceneAsAny.createOrUpdateSelectionOctree();
  103862. }
  103863. }
  103864. return true;
  103865. };
  103866. ;
  103867. MergeMeshesOptimization._UpdateSelectionTree = false;
  103868. return MergeMeshesOptimization;
  103869. }(SceneOptimization));
  103870. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  103871. /**
  103872. * Defines a list of options used by SceneOptimizer
  103873. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103874. */
  103875. var SceneOptimizerOptions = /** @class */ (function () {
  103876. /**
  103877. * Creates a new list of options used by SceneOptimizer
  103878. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  103879. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  103880. */
  103881. function SceneOptimizerOptions(
  103882. /**
  103883. * Defines the target frame rate to reach (60 by default)
  103884. */
  103885. targetFrameRate,
  103886. /**
  103887. * Defines the interval between two checkes (2000ms by default)
  103888. */
  103889. trackerDuration) {
  103890. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  103891. if (trackerDuration === void 0) { trackerDuration = 2000; }
  103892. this.targetFrameRate = targetFrameRate;
  103893. this.trackerDuration = trackerDuration;
  103894. /**
  103895. * Gets the list of optimizations to apply
  103896. */
  103897. this.optimizations = new Array();
  103898. }
  103899. /**
  103900. * Add a new optimization
  103901. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  103902. * @returns the current SceneOptimizerOptions
  103903. */
  103904. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  103905. this.optimizations.push(optimization);
  103906. return this;
  103907. };
  103908. /**
  103909. * Add a new custom optimization
  103910. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  103911. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  103912. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103913. * @returns the current SceneOptimizerOptions
  103914. */
  103915. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  103916. if (priority === void 0) { priority = 0; }
  103917. var optimization = new CustomOptimization(priority);
  103918. optimization.onApply = onApply;
  103919. optimization.onGetDescription = onGetDescription;
  103920. this.optimizations.push(optimization);
  103921. return this;
  103922. };
  103923. /**
  103924. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  103925. * @param targetFrameRate defines the target frame rate (60 by default)
  103926. * @returns a SceneOptimizerOptions object
  103927. */
  103928. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  103929. var result = new SceneOptimizerOptions(targetFrameRate);
  103930. var priority = 0;
  103931. result.addOptimization(new MergeMeshesOptimization(priority));
  103932. result.addOptimization(new ShadowsOptimization(priority));
  103933. result.addOptimization(new LensFlaresOptimization(priority));
  103934. // Next priority
  103935. priority++;
  103936. result.addOptimization(new PostProcessesOptimization(priority));
  103937. result.addOptimization(new ParticlesOptimization(priority));
  103938. // Next priority
  103939. priority++;
  103940. result.addOptimization(new TextureOptimization(priority, 1024));
  103941. return result;
  103942. };
  103943. /**
  103944. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  103945. * @param targetFrameRate defines the target frame rate (60 by default)
  103946. * @returns a SceneOptimizerOptions object
  103947. */
  103948. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  103949. var result = new SceneOptimizerOptions(targetFrameRate);
  103950. var priority = 0;
  103951. result.addOptimization(new MergeMeshesOptimization(priority));
  103952. result.addOptimization(new ShadowsOptimization(priority));
  103953. result.addOptimization(new LensFlaresOptimization(priority));
  103954. // Next priority
  103955. priority++;
  103956. result.addOptimization(new PostProcessesOptimization(priority));
  103957. result.addOptimization(new ParticlesOptimization(priority));
  103958. // Next priority
  103959. priority++;
  103960. result.addOptimization(new TextureOptimization(priority, 512));
  103961. // Next priority
  103962. priority++;
  103963. result.addOptimization(new RenderTargetsOptimization(priority));
  103964. // Next priority
  103965. priority++;
  103966. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  103967. return result;
  103968. };
  103969. /**
  103970. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  103971. * @param targetFrameRate defines the target frame rate (60 by default)
  103972. * @returns a SceneOptimizerOptions object
  103973. */
  103974. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  103975. var result = new SceneOptimizerOptions(targetFrameRate);
  103976. var priority = 0;
  103977. result.addOptimization(new MergeMeshesOptimization(priority));
  103978. result.addOptimization(new ShadowsOptimization(priority));
  103979. result.addOptimization(new LensFlaresOptimization(priority));
  103980. // Next priority
  103981. priority++;
  103982. result.addOptimization(new PostProcessesOptimization(priority));
  103983. result.addOptimization(new ParticlesOptimization(priority));
  103984. // Next priority
  103985. priority++;
  103986. result.addOptimization(new TextureOptimization(priority, 256));
  103987. // Next priority
  103988. priority++;
  103989. result.addOptimization(new RenderTargetsOptimization(priority));
  103990. // Next priority
  103991. priority++;
  103992. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  103993. return result;
  103994. };
  103995. return SceneOptimizerOptions;
  103996. }());
  103997. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  103998. /**
  103999. * Class used to run optimizations in order to reach a target frame rate
  104000. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104001. */
  104002. var SceneOptimizer = /** @class */ (function () {
  104003. /**
  104004. * Creates a new SceneOptimizer
  104005. * @param scene defines the scene to work on
  104006. * @param options defines the options to use with the SceneOptimizer
  104007. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  104008. * @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)
  104009. */
  104010. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  104011. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  104012. if (improvementMode === void 0) { improvementMode = false; }
  104013. var _this = this;
  104014. this._isRunning = false;
  104015. this._currentPriorityLevel = 0;
  104016. this._targetFrameRate = 60;
  104017. this._trackerDuration = 2000;
  104018. this._currentFrameRate = 0;
  104019. this._improvementMode = false;
  104020. /**
  104021. * Defines an observable called when the optimizer reaches the target frame rate
  104022. */
  104023. this.onSuccessObservable = new BABYLON.Observable();
  104024. /**
  104025. * Defines an observable called when the optimizer enables an optimization
  104026. */
  104027. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  104028. /**
  104029. * Defines an observable called when the optimizer is not able to reach the target frame rate
  104030. */
  104031. this.onFailureObservable = new BABYLON.Observable();
  104032. if (!options) {
  104033. this._options = new SceneOptimizerOptions();
  104034. }
  104035. else {
  104036. this._options = options;
  104037. }
  104038. if (this._options.targetFrameRate) {
  104039. this._targetFrameRate = this._options.targetFrameRate;
  104040. }
  104041. if (this._options.trackerDuration) {
  104042. this._trackerDuration = this._options.trackerDuration;
  104043. }
  104044. if (autoGeneratePriorities) {
  104045. var priority = 0;
  104046. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  104047. var optim = _a[_i];
  104048. optim.priority = priority++;
  104049. }
  104050. }
  104051. this._improvementMode = improvementMode;
  104052. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104053. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  104054. _this._sceneDisposeObserver = null;
  104055. _this.dispose();
  104056. });
  104057. }
  104058. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  104059. /**
  104060. * Gets a boolean indicating if the optimizer is in improvement mode
  104061. */
  104062. get: function () {
  104063. return this._improvementMode;
  104064. },
  104065. enumerable: true,
  104066. configurable: true
  104067. });
  104068. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  104069. /**
  104070. * Gets the current priority level (0 at start)
  104071. */
  104072. get: function () {
  104073. return this._currentPriorityLevel;
  104074. },
  104075. enumerable: true,
  104076. configurable: true
  104077. });
  104078. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  104079. /**
  104080. * Gets the current frame rate checked by the SceneOptimizer
  104081. */
  104082. get: function () {
  104083. return this._currentFrameRate;
  104084. },
  104085. enumerable: true,
  104086. configurable: true
  104087. });
  104088. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  104089. /**
  104090. * Gets or sets the current target frame rate (60 by default)
  104091. */
  104092. get: function () {
  104093. return this._targetFrameRate;
  104094. },
  104095. /**
  104096. * Gets or sets the current target frame rate (60 by default)
  104097. */
  104098. set: function (value) {
  104099. this._targetFrameRate = value;
  104100. },
  104101. enumerable: true,
  104102. configurable: true
  104103. });
  104104. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  104105. /**
  104106. * Gets or sets the current interval between two checks (every 2000ms by default)
  104107. */
  104108. get: function () {
  104109. return this._trackerDuration;
  104110. },
  104111. /**
  104112. * Gets or sets the current interval between two checks (every 2000ms by default)
  104113. */
  104114. set: function (value) {
  104115. this._trackerDuration = value;
  104116. },
  104117. enumerable: true,
  104118. configurable: true
  104119. });
  104120. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  104121. /**
  104122. * Gets the list of active optimizations
  104123. */
  104124. get: function () {
  104125. return this._options.optimizations;
  104126. },
  104127. enumerable: true,
  104128. configurable: true
  104129. });
  104130. /**
  104131. * Stops the current optimizer
  104132. */
  104133. SceneOptimizer.prototype.stop = function () {
  104134. this._isRunning = false;
  104135. };
  104136. /**
  104137. * Reset the optimizer to initial step (current priority level = 0)
  104138. */
  104139. SceneOptimizer.prototype.reset = function () {
  104140. this._currentPriorityLevel = 0;
  104141. };
  104142. /**
  104143. * Start the optimizer. By default it will try to reach a specific framerate
  104144. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  104145. */
  104146. SceneOptimizer.prototype.start = function () {
  104147. var _this = this;
  104148. if (this._isRunning) {
  104149. return;
  104150. }
  104151. this._isRunning = true;
  104152. // Let's wait for the scene to be ready before running our check
  104153. this._scene.executeWhenReady(function () {
  104154. setTimeout(function () {
  104155. _this._checkCurrentState();
  104156. }, _this._trackerDuration);
  104157. });
  104158. };
  104159. SceneOptimizer.prototype._checkCurrentState = function () {
  104160. var _this = this;
  104161. if (!this._isRunning) {
  104162. return;
  104163. }
  104164. var scene = this._scene;
  104165. var options = this._options;
  104166. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  104167. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  104168. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  104169. this._isRunning = false;
  104170. this.onSuccessObservable.notifyObservers(this);
  104171. return;
  104172. }
  104173. // Apply current level of optimizations
  104174. var allDone = true;
  104175. var noOptimizationApplied = true;
  104176. for (var index = 0; index < options.optimizations.length; index++) {
  104177. var optimization = options.optimizations[index];
  104178. if (optimization.priority === this._currentPriorityLevel) {
  104179. noOptimizationApplied = false;
  104180. allDone = allDone && optimization.apply(scene, this);
  104181. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  104182. }
  104183. }
  104184. // If no optimization was applied, this is a failure :(
  104185. if (noOptimizationApplied) {
  104186. this._isRunning = false;
  104187. this.onFailureObservable.notifyObservers(this);
  104188. return;
  104189. }
  104190. // If all optimizations were done, move to next level
  104191. if (allDone) {
  104192. this._currentPriorityLevel++;
  104193. }
  104194. // Let's the system running for a specific amount of time before checking FPS
  104195. scene.executeWhenReady(function () {
  104196. setTimeout(function () {
  104197. _this._checkCurrentState();
  104198. }, _this._trackerDuration);
  104199. });
  104200. };
  104201. /**
  104202. * Release all resources
  104203. */
  104204. SceneOptimizer.prototype.dispose = function () {
  104205. this.stop();
  104206. this.onSuccessObservable.clear();
  104207. this.onFailureObservable.clear();
  104208. this.onNewOptimizationAppliedObservable.clear();
  104209. if (this._sceneDisposeObserver) {
  104210. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  104211. }
  104212. };
  104213. /**
  104214. * Helper function to create a SceneOptimizer with one single line of code
  104215. * @param scene defines the scene to work on
  104216. * @param options defines the options to use with the SceneOptimizer
  104217. * @param onSuccess defines a callback to call on success
  104218. * @param onFailure defines a callback to call on failure
  104219. * @returns the new SceneOptimizer object
  104220. */
  104221. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  104222. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  104223. if (onSuccess) {
  104224. optimizer.onSuccessObservable.add(function () {
  104225. onSuccess();
  104226. });
  104227. }
  104228. if (onFailure) {
  104229. optimizer.onFailureObservable.add(function () {
  104230. onFailure();
  104231. });
  104232. }
  104233. optimizer.start();
  104234. return optimizer;
  104235. };
  104236. return SceneOptimizer;
  104237. }());
  104238. BABYLON.SceneOptimizer = SceneOptimizer;
  104239. })(BABYLON || (BABYLON = {}));
  104240. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  104241. var BABYLON;
  104242. (function (BABYLON) {
  104243. /**
  104244. * Gets the outline renderer associated with the scene
  104245. * @returns a OutlineRenderer
  104246. */
  104247. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  104248. if (!this._outlineRenderer) {
  104249. this._outlineRenderer = new OutlineRenderer(this);
  104250. }
  104251. return this._outlineRenderer;
  104252. };
  104253. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  104254. get: function () {
  104255. return this._renderOutline;
  104256. },
  104257. set: function (value) {
  104258. if (value) {
  104259. // Lazy Load the component.
  104260. this.getScene().getOutlineRenderer();
  104261. }
  104262. this._renderOutline = value;
  104263. },
  104264. enumerable: true,
  104265. configurable: true
  104266. });
  104267. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  104268. get: function () {
  104269. return this._renderOverlay;
  104270. },
  104271. set: function (value) {
  104272. if (value) {
  104273. // Lazy Load the component.
  104274. this.getScene().getOutlineRenderer();
  104275. }
  104276. this._renderOverlay = value;
  104277. },
  104278. enumerable: true,
  104279. configurable: true
  104280. });
  104281. /**
  104282. * This class is responsible to draw bothe outline/overlay of meshes.
  104283. * It should not be used directly but through the available method on mesh.
  104284. */
  104285. var OutlineRenderer = /** @class */ (function () {
  104286. /**
  104287. * Instantiates a new outline renderer. (There could be only one per scene).
  104288. * @param scene Defines the scene it belongs to
  104289. */
  104290. function OutlineRenderer(scene) {
  104291. /**
  104292. * The name of the component. Each component must have a unique name.
  104293. */
  104294. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  104295. /**
  104296. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  104297. */
  104298. this.zOffset = 1;
  104299. this.scene = scene;
  104300. this._engine = scene.getEngine();
  104301. this.scene._addComponent(this);
  104302. }
  104303. /**
  104304. * Register the component to one instance of a scene.
  104305. */
  104306. OutlineRenderer.prototype.register = function () {
  104307. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  104308. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  104309. };
  104310. /**
  104311. * Rebuilds the elements related to this component in case of
  104312. * context lost for instance.
  104313. */
  104314. OutlineRenderer.prototype.rebuild = function () {
  104315. // Nothing to do here.
  104316. };
  104317. /**
  104318. * Disposes the component and the associated ressources.
  104319. */
  104320. OutlineRenderer.prototype.dispose = function () {
  104321. // Nothing to do here.
  104322. };
  104323. /**
  104324. * Renders the outline in the canvas.
  104325. * @param subMesh Defines the sumesh to render
  104326. * @param batch Defines the batch of meshes in case of instances
  104327. * @param useOverlay Defines if the rendering is for the overlay or the outline
  104328. */
  104329. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  104330. var _this = this;
  104331. if (useOverlay === void 0) { useOverlay = false; }
  104332. var scene = this.scene;
  104333. var engine = scene.getEngine();
  104334. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104335. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  104336. return;
  104337. }
  104338. var mesh = subMesh.getRenderingMesh();
  104339. var material = subMesh.getMaterial();
  104340. if (!material || !scene.activeCamera) {
  104341. return;
  104342. }
  104343. engine.enableEffect(this._effect);
  104344. // Logarithmic depth
  104345. if (material.useLogarithmicDepth) {
  104346. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  104347. }
  104348. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  104349. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  104350. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  104351. // Bones
  104352. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104353. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104354. }
  104355. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  104356. // Alpha test
  104357. if (material && material.needAlphaTesting()) {
  104358. var alphaTexture = material.getAlphaTestTexture();
  104359. if (alphaTexture) {
  104360. this._effect.setTexture("diffuseSampler", alphaTexture);
  104361. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  104362. }
  104363. }
  104364. engine.setZOffset(-this.zOffset);
  104365. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  104366. engine.setZOffset(0);
  104367. };
  104368. /**
  104369. * Returns whether or not the outline renderer is ready for a given submesh.
  104370. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  104371. * @param subMesh Defines the submesh to check readyness for
  104372. * @param useInstances Defines wheter wee are trying to render instances or not
  104373. * @returns true if ready otherwise false
  104374. */
  104375. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  104376. var defines = [];
  104377. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  104378. var mesh = subMesh.getMesh();
  104379. var material = subMesh.getMaterial();
  104380. if (material) {
  104381. // Alpha test
  104382. if (material.needAlphaTesting()) {
  104383. defines.push("#define ALPHATEST");
  104384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104385. attribs.push(BABYLON.VertexBuffer.UVKind);
  104386. defines.push("#define UV1");
  104387. }
  104388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  104389. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104390. defines.push("#define UV2");
  104391. }
  104392. }
  104393. //Logarithmic depth
  104394. if (material.useLogarithmicDepth) {
  104395. defines.push("#define LOGARITHMICDEPTH");
  104396. }
  104397. }
  104398. // Bones
  104399. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104400. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104401. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104402. if (mesh.numBoneInfluencers > 4) {
  104403. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104404. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104405. }
  104406. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104407. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  104408. }
  104409. else {
  104410. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104411. }
  104412. // Instances
  104413. if (useInstances) {
  104414. defines.push("#define INSTANCES");
  104415. attribs.push("world0");
  104416. attribs.push("world1");
  104417. attribs.push("world2");
  104418. attribs.push("world3");
  104419. }
  104420. // Get correct effect
  104421. var join = defines.join("\n");
  104422. if (this._cachedDefines !== join) {
  104423. this._cachedDefines = join;
  104424. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  104425. }
  104426. return this._effect.isReady();
  104427. };
  104428. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  104429. // Outline - step 1
  104430. this._savedDepthWrite = this._engine.getDepthWrite();
  104431. if (mesh.renderOutline) {
  104432. this._engine.setDepthWrite(false);
  104433. this.render(subMesh, batch);
  104434. this._engine.setDepthWrite(this._savedDepthWrite);
  104435. }
  104436. };
  104437. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  104438. // Outline - step 2
  104439. if (mesh.renderOutline && this._savedDepthWrite) {
  104440. this._engine.setDepthWrite(true);
  104441. this._engine.setColorWrite(false);
  104442. this.render(subMesh, batch);
  104443. this._engine.setColorWrite(true);
  104444. }
  104445. // Overlay
  104446. if (mesh.renderOverlay) {
  104447. var currentMode = this._engine.getAlphaMode();
  104448. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104449. this.render(subMesh, batch, true);
  104450. this._engine.setAlphaMode(currentMode);
  104451. }
  104452. };
  104453. return OutlineRenderer;
  104454. }());
  104455. BABYLON.OutlineRenderer = OutlineRenderer;
  104456. })(BABYLON || (BABYLON = {}));
  104457. //# sourceMappingURL=babylon.outlineRenderer.js.map
  104458. var BABYLON;
  104459. (function (BABYLON) {
  104460. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  104461. if (this._edgesRenderer) {
  104462. this._edgesRenderer.dispose();
  104463. this._edgesRenderer = null;
  104464. }
  104465. return this;
  104466. };
  104467. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104468. if (epsilon === void 0) { epsilon = 0.95; }
  104469. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104470. this.disableEdgesRendering();
  104471. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104472. return this;
  104473. };
  104474. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  104475. get: function () {
  104476. return this._edgesRenderer;
  104477. },
  104478. enumerable: true,
  104479. configurable: true
  104480. });
  104481. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104482. if (epsilon === void 0) { epsilon = 0.95; }
  104483. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104484. this.disableEdgesRendering();
  104485. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104486. return this;
  104487. };
  104488. /**
  104489. * FaceAdjacencies Helper class to generate edges
  104490. */
  104491. var FaceAdjacencies = /** @class */ (function () {
  104492. function FaceAdjacencies() {
  104493. this.edges = new Array();
  104494. this.edgesConnectedCount = 0;
  104495. }
  104496. return FaceAdjacencies;
  104497. }());
  104498. /**
  104499. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  104500. */
  104501. var EdgesRenderer = /** @class */ (function () {
  104502. /**
  104503. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  104504. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  104505. * @param source Mesh used to create edges
  104506. * @param epsilon sum of angles in adjacency to check for edge
  104507. * @param checkVerticesInsteadOfIndices
  104508. * @param generateEdgesLines - should generate Lines or only prepare resources.
  104509. */
  104510. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  104511. if (epsilon === void 0) { epsilon = 0.95; }
  104512. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104513. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  104514. var _this = this;
  104515. /**
  104516. * Define the size of the edges with an orthographic camera
  104517. */
  104518. this.edgesWidthScalerForOrthographic = 1000.0;
  104519. /**
  104520. * Define the size of the edges with a perspective camera
  104521. */
  104522. this.edgesWidthScalerForPerspective = 50.0;
  104523. this._linesPositions = new Array();
  104524. this._linesNormals = new Array();
  104525. this._linesIndices = new Array();
  104526. this._buffers = {};
  104527. this._checkVerticesInsteadOfIndices = false;
  104528. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  104529. this.isEnabled = true;
  104530. this._source = source;
  104531. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  104532. this._epsilon = epsilon;
  104533. this._prepareRessources();
  104534. if (generateEdgesLines) {
  104535. this._generateEdgesLines();
  104536. }
  104537. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  104538. _this._rebuild();
  104539. });
  104540. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  104541. _this.dispose();
  104542. });
  104543. }
  104544. EdgesRenderer.prototype._prepareRessources = function () {
  104545. if (this._lineShader) {
  104546. return;
  104547. }
  104548. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  104549. attributes: ["position", "normal"],
  104550. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  104551. });
  104552. this._lineShader.disableDepthWrite = true;
  104553. this._lineShader.backFaceCulling = false;
  104554. };
  104555. /** @hidden */
  104556. EdgesRenderer.prototype._rebuild = function () {
  104557. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104558. if (buffer) {
  104559. buffer._rebuild();
  104560. }
  104561. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104562. if (buffer) {
  104563. buffer._rebuild();
  104564. }
  104565. var scene = this._source.getScene();
  104566. var engine = scene.getEngine();
  104567. this._ib = engine.createIndexBuffer(this._linesIndices);
  104568. };
  104569. /**
  104570. * Releases the required resources for the edges renderer
  104571. */
  104572. EdgesRenderer.prototype.dispose = function () {
  104573. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  104574. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  104575. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104576. if (buffer) {
  104577. buffer.dispose();
  104578. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  104579. }
  104580. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104581. if (buffer) {
  104582. buffer.dispose();
  104583. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  104584. }
  104585. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  104586. this._lineShader.dispose();
  104587. };
  104588. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  104589. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  104590. return 0;
  104591. }
  104592. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  104593. return 1;
  104594. }
  104595. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  104596. return 2;
  104597. }
  104598. return -1;
  104599. };
  104600. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  104601. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  104602. return 0;
  104603. }
  104604. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  104605. return 1;
  104606. }
  104607. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  104608. return 2;
  104609. }
  104610. return -1;
  104611. };
  104612. /**
  104613. * Checks if the pair of p0 and p1 is en edge
  104614. * @param faceIndex
  104615. * @param edge
  104616. * @param faceNormals
  104617. * @param p0
  104618. * @param p1
  104619. * @private
  104620. */
  104621. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104622. var needToCreateLine;
  104623. if (edge === undefined) {
  104624. needToCreateLine = true;
  104625. }
  104626. else {
  104627. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  104628. needToCreateLine = dotProduct < this._epsilon;
  104629. }
  104630. if (needToCreateLine) {
  104631. var offset = this._linesPositions.length / 3;
  104632. var normal = p0.subtract(p1);
  104633. normal.normalize();
  104634. // Positions
  104635. this._linesPositions.push(p0.x);
  104636. this._linesPositions.push(p0.y);
  104637. this._linesPositions.push(p0.z);
  104638. this._linesPositions.push(p0.x);
  104639. this._linesPositions.push(p0.y);
  104640. this._linesPositions.push(p0.z);
  104641. this._linesPositions.push(p1.x);
  104642. this._linesPositions.push(p1.y);
  104643. this._linesPositions.push(p1.z);
  104644. this._linesPositions.push(p1.x);
  104645. this._linesPositions.push(p1.y);
  104646. this._linesPositions.push(p1.z);
  104647. // Normals
  104648. this._linesNormals.push(p1.x);
  104649. this._linesNormals.push(p1.y);
  104650. this._linesNormals.push(p1.z);
  104651. this._linesNormals.push(-1);
  104652. this._linesNormals.push(p1.x);
  104653. this._linesNormals.push(p1.y);
  104654. this._linesNormals.push(p1.z);
  104655. this._linesNormals.push(1);
  104656. this._linesNormals.push(p0.x);
  104657. this._linesNormals.push(p0.y);
  104658. this._linesNormals.push(p0.z);
  104659. this._linesNormals.push(-1);
  104660. this._linesNormals.push(p0.x);
  104661. this._linesNormals.push(p0.y);
  104662. this._linesNormals.push(p0.z);
  104663. this._linesNormals.push(1);
  104664. // Indices
  104665. this._linesIndices.push(offset);
  104666. this._linesIndices.push(offset + 1);
  104667. this._linesIndices.push(offset + 2);
  104668. this._linesIndices.push(offset);
  104669. this._linesIndices.push(offset + 2);
  104670. this._linesIndices.push(offset + 3);
  104671. }
  104672. };
  104673. /**
  104674. * Generates lines edges from adjacencjes
  104675. * @private
  104676. */
  104677. EdgesRenderer.prototype._generateEdgesLines = function () {
  104678. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104679. var indices = this._source.getIndices();
  104680. if (!indices || !positions) {
  104681. return;
  104682. }
  104683. // First let's find adjacencies
  104684. var adjacencies = new Array();
  104685. var faceNormals = new Array();
  104686. var index;
  104687. var faceAdjacencies;
  104688. // Prepare faces
  104689. for (index = 0; index < indices.length; index += 3) {
  104690. faceAdjacencies = new FaceAdjacencies();
  104691. var p0Index = indices[index];
  104692. var p1Index = indices[index + 1];
  104693. var p2Index = indices[index + 2];
  104694. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  104695. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  104696. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  104697. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  104698. faceNormal.normalize();
  104699. faceNormals.push(faceNormal);
  104700. adjacencies.push(faceAdjacencies);
  104701. }
  104702. // Scan
  104703. for (index = 0; index < adjacencies.length; index++) {
  104704. faceAdjacencies = adjacencies[index];
  104705. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  104706. var otherFaceAdjacencies = adjacencies[otherIndex];
  104707. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  104708. break;
  104709. }
  104710. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  104711. continue;
  104712. }
  104713. var otherP0 = indices[otherIndex * 3];
  104714. var otherP1 = indices[otherIndex * 3 + 1];
  104715. var otherP2 = indices[otherIndex * 3 + 2];
  104716. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  104717. var otherEdgeIndex = 0;
  104718. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  104719. continue;
  104720. }
  104721. switch (edgeIndex) {
  104722. case 0:
  104723. if (this._checkVerticesInsteadOfIndices) {
  104724. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104725. }
  104726. else {
  104727. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  104728. }
  104729. break;
  104730. case 1:
  104731. if (this._checkVerticesInsteadOfIndices) {
  104732. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104733. }
  104734. else {
  104735. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  104736. }
  104737. break;
  104738. case 2:
  104739. if (this._checkVerticesInsteadOfIndices) {
  104740. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104741. }
  104742. else {
  104743. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  104744. }
  104745. break;
  104746. }
  104747. if (otherEdgeIndex === -1) {
  104748. continue;
  104749. }
  104750. faceAdjacencies.edges[edgeIndex] = otherIndex;
  104751. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  104752. faceAdjacencies.edgesConnectedCount++;
  104753. otherFaceAdjacencies.edgesConnectedCount++;
  104754. if (faceAdjacencies.edgesConnectedCount === 3) {
  104755. break;
  104756. }
  104757. }
  104758. }
  104759. }
  104760. // Create lines
  104761. for (index = 0; index < adjacencies.length; index++) {
  104762. // 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
  104763. var current = adjacencies[index];
  104764. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104765. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  104766. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  104767. }
  104768. // Merge into a single mesh
  104769. var engine = this._source.getScene().getEngine();
  104770. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104771. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104772. this._ib = engine.createIndexBuffer(this._linesIndices);
  104773. this._indicesCount = this._linesIndices.length;
  104774. };
  104775. /**
  104776. * Checks wether or not the edges renderer is ready to render.
  104777. * @return true if ready, otherwise false.
  104778. */
  104779. EdgesRenderer.prototype.isReady = function () {
  104780. return this._lineShader.isReady();
  104781. };
  104782. /**
  104783. * Renders the edges of the attached mesh,
  104784. */
  104785. EdgesRenderer.prototype.render = function () {
  104786. var scene = this._source.getScene();
  104787. if (!this.isReady() || !scene.activeCamera) {
  104788. return;
  104789. }
  104790. var engine = scene.getEngine();
  104791. this._lineShader._preBind();
  104792. if (this._source.edgesColor.a !== 1) {
  104793. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104794. }
  104795. else {
  104796. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104797. }
  104798. // VBOs
  104799. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  104800. scene.resetCachedMaterial();
  104801. this._lineShader.setColor4("color", this._source.edgesColor);
  104802. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  104803. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  104804. }
  104805. else {
  104806. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  104807. }
  104808. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  104809. this._lineShader.bind(this._source.getWorldMatrix());
  104810. // Draw order
  104811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  104812. this._lineShader.unbind();
  104813. };
  104814. return EdgesRenderer;
  104815. }());
  104816. BABYLON.EdgesRenderer = EdgesRenderer;
  104817. })(BABYLON || (BABYLON = {}));
  104818. //# sourceMappingURL=babylon.edgesRenderer.js.map
  104819. var BABYLON;
  104820. (function (BABYLON) {
  104821. /**
  104822. * FaceAdjacencies Helper class to generate edges
  104823. */
  104824. var FaceAdjacencies = /** @class */ (function () {
  104825. function FaceAdjacencies() {
  104826. this.edges = new Array();
  104827. this.edgesConnectedCount = 0;
  104828. }
  104829. return FaceAdjacencies;
  104830. }());
  104831. /**
  104832. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  104833. */
  104834. var LineEdgesRenderer = /** @class */ (function (_super) {
  104835. __extends(LineEdgesRenderer, _super);
  104836. /**
  104837. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  104838. * @param source LineMesh used to generate edges
  104839. * @param epsilon not important (specified angle for edge detection)
  104840. * @param checkVerticesInsteadOfIndices not important for LineMesh
  104841. */
  104842. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  104843. if (epsilon === void 0) { epsilon = 0.95; }
  104844. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104845. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  104846. _this._generateEdgesLines();
  104847. return _this;
  104848. }
  104849. /**
  104850. * Always create the edge since its a line so only important things are p0 and p1
  104851. * @param faceIndex not important for LineMesh
  104852. * @param edge not important for LineMesh
  104853. * @param faceNormals not important for LineMesh
  104854. * @param p0 beginnig of line
  104855. * @param p1 end of line
  104856. */
  104857. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104858. var offset = this._linesPositions.length / 3;
  104859. var normal = p0.subtract(p1);
  104860. normal.normalize();
  104861. // Positions
  104862. this._linesPositions.push(p0.x);
  104863. this._linesPositions.push(p0.y);
  104864. this._linesPositions.push(p0.z);
  104865. this._linesPositions.push(p0.x);
  104866. this._linesPositions.push(p0.y);
  104867. this._linesPositions.push(p0.z);
  104868. this._linesPositions.push(p1.x);
  104869. this._linesPositions.push(p1.y);
  104870. this._linesPositions.push(p1.z);
  104871. this._linesPositions.push(p1.x);
  104872. this._linesPositions.push(p1.y);
  104873. this._linesPositions.push(p1.z);
  104874. // Normals
  104875. this._linesNormals.push(p1.x);
  104876. this._linesNormals.push(p1.y);
  104877. this._linesNormals.push(p1.z);
  104878. this._linesNormals.push(-1);
  104879. this._linesNormals.push(p1.x);
  104880. this._linesNormals.push(p1.y);
  104881. this._linesNormals.push(p1.z);
  104882. this._linesNormals.push(1);
  104883. this._linesNormals.push(p0.x);
  104884. this._linesNormals.push(p0.y);
  104885. this._linesNormals.push(p0.z);
  104886. this._linesNormals.push(-1);
  104887. this._linesNormals.push(p0.x);
  104888. this._linesNormals.push(p0.y);
  104889. this._linesNormals.push(p0.z);
  104890. this._linesNormals.push(1);
  104891. // Indices
  104892. this._linesIndices.push(offset);
  104893. this._linesIndices.push(offset + 1);
  104894. this._linesIndices.push(offset + 2);
  104895. this._linesIndices.push(offset);
  104896. this._linesIndices.push(offset + 2);
  104897. this._linesIndices.push(offset + 3);
  104898. };
  104899. /**
  104900. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  104901. */
  104902. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  104903. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104904. var indices = this._source.getIndices();
  104905. if (!indices || !positions) {
  104906. return;
  104907. }
  104908. // First let's find adjacencies
  104909. var adjacencies = new Array();
  104910. var faceNormals = new Array();
  104911. var index;
  104912. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  104913. var currentAdjecancy = new FaceAdjacencies();
  104914. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  104915. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  104916. adjacencies.push(currentAdjecancy);
  104917. }
  104918. // Create lines
  104919. for (index = 0; index < adjacencies.length; index++) {
  104920. // 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
  104921. var current = adjacencies[index];
  104922. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104923. }
  104924. // Merge into a single mesh
  104925. var engine = this._source.getScene().getEngine();
  104926. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104927. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104928. this._ib = engine.createIndexBuffer(this._linesIndices);
  104929. this._indicesCount = this._linesIndices.length;
  104930. };
  104931. return LineEdgesRenderer;
  104932. }(BABYLON.EdgesRenderer));
  104933. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  104934. })(BABYLON || (BABYLON = {}));
  104935. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  104936. var BABYLON;
  104937. (function (BABYLON) {
  104938. // Adds the parser to the scene parsers.
  104939. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  104940. if (parsedData.effectLayers) {
  104941. if (!container.effectLayers) {
  104942. container.effectLayers = new Array();
  104943. }
  104944. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  104945. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  104946. container.effectLayers.push(effectLayer);
  104947. }
  104948. }
  104949. });
  104950. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  104951. var index = this.effectLayers.indexOf(toRemove);
  104952. if (index !== -1) {
  104953. this.effectLayers.splice(index, 1);
  104954. }
  104955. return index;
  104956. };
  104957. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  104958. this.effectLayers.push(newEffectLayer);
  104959. };
  104960. /**
  104961. * Defines the layer scene component responsible to manage any effect layers
  104962. * in a given scene.
  104963. */
  104964. var EffectLayerSceneComponent = /** @class */ (function () {
  104965. /**
  104966. * Creates a new instance of the component for the given scene
  104967. * @param scene Defines the scene to register the component in
  104968. */
  104969. function EffectLayerSceneComponent(scene) {
  104970. /**
  104971. * The component name helpfull to identify the component in the list of scene components.
  104972. */
  104973. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  104974. this._renderEffects = false;
  104975. this._needStencil = false;
  104976. this._previousStencilState = false;
  104977. this.scene = scene;
  104978. this._engine = scene.getEngine();
  104979. scene.effectLayers = new Array();
  104980. }
  104981. /**
  104982. * Registers the component in a given scene
  104983. */
  104984. EffectLayerSceneComponent.prototype.register = function () {
  104985. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  104986. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  104987. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  104988. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  104989. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  104990. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  104991. };
  104992. /**
  104993. * Rebuilds the elements related to this component in case of
  104994. * context lost for instance.
  104995. */
  104996. EffectLayerSceneComponent.prototype.rebuild = function () {
  104997. var layers = this.scene.effectLayers;
  104998. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104999. var effectLayer = layers_1[_i];
  105000. effectLayer._rebuild();
  105001. }
  105002. };
  105003. /**
  105004. * Serializes the component data to the specified json object
  105005. * @param serializationObject The object to serialize to
  105006. */
  105007. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  105008. // Effect layers
  105009. serializationObject.effectLayers = [];
  105010. var layers = this.scene.effectLayers;
  105011. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105012. var effectLayer = layers_2[_i];
  105013. if (effectLayer.serialize) {
  105014. serializationObject.effectLayers.push(effectLayer.serialize());
  105015. }
  105016. }
  105017. };
  105018. /**
  105019. * Adds all the element from the container to the scene
  105020. * @param container the container holding the elements
  105021. */
  105022. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  105023. var _this = this;
  105024. if (!container.effectLayers) {
  105025. return;
  105026. }
  105027. container.effectLayers.forEach(function (o) {
  105028. _this.scene.addEffectLayer(o);
  105029. });
  105030. };
  105031. /**
  105032. * Removes all the elements in the container from the scene
  105033. * @param container contains the elements to remove
  105034. */
  105035. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  105036. var _this = this;
  105037. if (!container.effectLayers) {
  105038. return;
  105039. }
  105040. container.effectLayers.forEach(function (o) {
  105041. _this.scene.removeEffectLayer(o);
  105042. });
  105043. };
  105044. /**
  105045. * Disposes the component and the associated ressources.
  105046. */
  105047. EffectLayerSceneComponent.prototype.dispose = function () {
  105048. var layers = this.scene.effectLayers;
  105049. while (layers.length) {
  105050. layers[0].dispose();
  105051. }
  105052. };
  105053. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  105054. var layers = this.scene.effectLayers;
  105055. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  105056. var layer = layers_3[_i];
  105057. if (!layer.hasMesh(mesh)) {
  105058. continue;
  105059. }
  105060. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  105061. var subMesh = _b[_a];
  105062. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  105063. return false;
  105064. }
  105065. }
  105066. }
  105067. return true;
  105068. };
  105069. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  105070. this._renderEffects = false;
  105071. this._needStencil = false;
  105072. var layers = this.scene.effectLayers;
  105073. if (layers && layers.length > 0) {
  105074. this._previousStencilState = this._engine.getStencilBuffer();
  105075. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  105076. var effectLayer = layers_4[_i];
  105077. if (effectLayer.shouldRender() &&
  105078. (!effectLayer.camera ||
  105079. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  105080. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  105081. this._renderEffects = true;
  105082. this._needStencil = this._needStencil || effectLayer.needStencil();
  105083. var renderTarget = effectLayer._mainTexture;
  105084. if (renderTarget._shouldRender()) {
  105085. this.scene.incrementRenderId();
  105086. renderTarget.render(false, false);
  105087. }
  105088. }
  105089. }
  105090. this.scene.incrementRenderId();
  105091. }
  105092. };
  105093. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  105094. // Activate effect Layer stencil
  105095. if (this._needStencil) {
  105096. this._engine.setStencilBuffer(true);
  105097. }
  105098. };
  105099. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  105100. // Restore effect Layer stencil
  105101. if (this._needStencil) {
  105102. this._engine.setStencilBuffer(this._previousStencilState);
  105103. }
  105104. };
  105105. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  105106. if (this._renderEffects) {
  105107. this._engine.setDepthBuffer(false);
  105108. var layers = this.scene.effectLayers;
  105109. for (var i = 0; i < layers.length; i++) {
  105110. var effectLayer = layers[i];
  105111. if (effectLayer.renderingGroupId === renderingGroupId) {
  105112. if (effectLayer.shouldRender()) {
  105113. effectLayer.render();
  105114. }
  105115. }
  105116. }
  105117. this._engine.setDepthBuffer(true);
  105118. }
  105119. };
  105120. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  105121. if (this._renderEffects) {
  105122. this._draw(-1);
  105123. }
  105124. };
  105125. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  105126. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  105127. this._draw(index);
  105128. }
  105129. };
  105130. return EffectLayerSceneComponent;
  105131. }());
  105132. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  105133. })(BABYLON || (BABYLON = {}));
  105134. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  105135. var __assign = (this && this.__assign) || function () {
  105136. __assign = Object.assign || function(t) {
  105137. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105138. s = arguments[i];
  105139. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105140. t[p] = s[p];
  105141. }
  105142. return t;
  105143. };
  105144. return __assign.apply(this, arguments);
  105145. };
  105146. var BABYLON;
  105147. (function (BABYLON) {
  105148. /**
  105149. * The effect layer Helps adding post process effect blended with the main pass.
  105150. *
  105151. * This can be for instance use to generate glow or higlight effects on the scene.
  105152. *
  105153. * The effect layer class can not be used directly and is intented to inherited from to be
  105154. * customized per effects.
  105155. */
  105156. var EffectLayer = /** @class */ (function () {
  105157. /**
  105158. * Instantiates a new effect Layer and references it in the scene.
  105159. * @param name The name of the layer
  105160. * @param scene The scene to use the layer in
  105161. */
  105162. function EffectLayer(
  105163. /** The Friendly of the effect in the scene */
  105164. name, scene) {
  105165. this._vertexBuffers = {};
  105166. this._maxSize = 0;
  105167. this._mainTextureDesiredSize = { width: 0, height: 0 };
  105168. this._shouldRender = true;
  105169. this._postProcesses = [];
  105170. this._textures = [];
  105171. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  105172. /**
  105173. * The clear color of the texture used to generate the glow map.
  105174. */
  105175. this.neutralColor = new BABYLON.Color4();
  105176. /**
  105177. * Specifies wether the highlight layer is enabled or not.
  105178. */
  105179. this.isEnabled = true;
  105180. /**
  105181. * An event triggered when the effect layer has been disposed.
  105182. */
  105183. this.onDisposeObservable = new BABYLON.Observable();
  105184. /**
  105185. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  105186. */
  105187. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  105188. /**
  105189. * An event triggered when the generated texture is being merged in the scene.
  105190. */
  105191. this.onBeforeComposeObservable = new BABYLON.Observable();
  105192. /**
  105193. * An event triggered when the generated texture has been merged in the scene.
  105194. */
  105195. this.onAfterComposeObservable = new BABYLON.Observable();
  105196. /**
  105197. * An event triggered when the efffect layer changes its size.
  105198. */
  105199. this.onSizeChangedObservable = new BABYLON.Observable();
  105200. this.name = name;
  105201. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105202. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  105203. if (!component) {
  105204. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  105205. this._scene._addComponent(component);
  105206. }
  105207. this._engine = this._scene.getEngine();
  105208. this._maxSize = this._engine.getCaps().maxTextureSize;
  105209. this._scene.effectLayers.push(this);
  105210. // Generate Buffers
  105211. this._generateIndexBuffer();
  105212. this._genrateVertexBuffer();
  105213. }
  105214. Object.defineProperty(EffectLayer.prototype, "camera", {
  105215. /**
  105216. * Gets the camera attached to the layer.
  105217. */
  105218. get: function () {
  105219. return this._effectLayerOptions.camera;
  105220. },
  105221. enumerable: true,
  105222. configurable: true
  105223. });
  105224. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  105225. /**
  105226. * Gets the rendering group id the layer should render in.
  105227. */
  105228. get: function () {
  105229. return this._effectLayerOptions.renderingGroupId;
  105230. },
  105231. enumerable: true,
  105232. configurable: true
  105233. });
  105234. /**
  105235. * Initializes the effect layer with the required options.
  105236. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  105237. */
  105238. EffectLayer.prototype._init = function (options) {
  105239. // Adapt options
  105240. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105241. this._setMainTextureSize();
  105242. this._createMainTexture();
  105243. this._createTextureAndPostProcesses();
  105244. this._mergeEffect = this._createMergeEffect();
  105245. };
  105246. /**
  105247. * Generates the index buffer of the full screen quad blending to the main canvas.
  105248. */
  105249. EffectLayer.prototype._generateIndexBuffer = function () {
  105250. // Indices
  105251. var indices = [];
  105252. indices.push(0);
  105253. indices.push(1);
  105254. indices.push(2);
  105255. indices.push(0);
  105256. indices.push(2);
  105257. indices.push(3);
  105258. this._indexBuffer = this._engine.createIndexBuffer(indices);
  105259. };
  105260. /**
  105261. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  105262. */
  105263. EffectLayer.prototype._genrateVertexBuffer = function () {
  105264. // VBO
  105265. var vertices = [];
  105266. vertices.push(1, 1);
  105267. vertices.push(-1, 1);
  105268. vertices.push(-1, -1);
  105269. vertices.push(1, -1);
  105270. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105271. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105272. };
  105273. /**
  105274. * Sets the main texture desired size which is the closest power of two
  105275. * of the engine canvas size.
  105276. */
  105277. EffectLayer.prototype._setMainTextureSize = function () {
  105278. if (this._effectLayerOptions.mainTextureFixedSize) {
  105279. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  105280. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  105281. }
  105282. else {
  105283. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  105284. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  105285. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  105286. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  105287. }
  105288. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  105289. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  105290. };
  105291. /**
  105292. * Creates the main texture for the effect layer.
  105293. */
  105294. EffectLayer.prototype._createMainTexture = function () {
  105295. var _this = this;
  105296. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  105297. width: this._mainTextureDesiredSize.width,
  105298. height: this._mainTextureDesiredSize.height
  105299. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105300. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  105301. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105302. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105303. this._mainTexture.anisotropicFilteringLevel = 1;
  105304. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105305. this._mainTexture.renderParticles = false;
  105306. this._mainTexture.renderList = null;
  105307. this._mainTexture.ignoreCameraViewport = true;
  105308. // Custom render function
  105309. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  105310. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  105311. var index;
  105312. var engine = _this._scene.getEngine();
  105313. if (depthOnlySubMeshes.length) {
  105314. engine.setColorWrite(false);
  105315. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  105316. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  105317. }
  105318. engine.setColorWrite(true);
  105319. }
  105320. for (index = 0; index < opaqueSubMeshes.length; index++) {
  105321. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  105322. }
  105323. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  105324. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  105325. }
  105326. for (index = 0; index < transparentSubMeshes.length; index++) {
  105327. _this._renderSubMesh(transparentSubMeshes.data[index]);
  105328. }
  105329. };
  105330. this._mainTexture.onClearObservable.add(function (engine) {
  105331. engine.clear(_this.neutralColor, true, true, true);
  105332. });
  105333. };
  105334. /**
  105335. * Checks for the readiness of the element composing the layer.
  105336. * @param subMesh the mesh to check for
  105337. * @param useInstances specify wether or not to use instances to render the mesh
  105338. * @param emissiveTexture the associated emissive texture used to generate the glow
  105339. * @return true if ready otherwise, false
  105340. */
  105341. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  105342. var material = subMesh.getMaterial();
  105343. if (!material) {
  105344. return false;
  105345. }
  105346. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  105347. return false;
  105348. }
  105349. var defines = [];
  105350. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105351. var mesh = subMesh.getMesh();
  105352. var uv1 = false;
  105353. var uv2 = false;
  105354. // Alpha test
  105355. if (material && material.needAlphaTesting()) {
  105356. var alphaTexture = material.getAlphaTestTexture();
  105357. if (alphaTexture) {
  105358. defines.push("#define ALPHATEST");
  105359. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105360. alphaTexture.coordinatesIndex === 1) {
  105361. defines.push("#define DIFFUSEUV2");
  105362. uv2 = true;
  105363. }
  105364. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105365. defines.push("#define DIFFUSEUV1");
  105366. uv1 = true;
  105367. }
  105368. }
  105369. }
  105370. // Emissive
  105371. if (emissiveTexture) {
  105372. defines.push("#define EMISSIVE");
  105373. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105374. emissiveTexture.coordinatesIndex === 1) {
  105375. defines.push("#define EMISSIVEUV2");
  105376. uv2 = true;
  105377. }
  105378. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105379. defines.push("#define EMISSIVEUV1");
  105380. uv1 = true;
  105381. }
  105382. }
  105383. if (uv1) {
  105384. attribs.push(BABYLON.VertexBuffer.UVKind);
  105385. defines.push("#define UV1");
  105386. }
  105387. if (uv2) {
  105388. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105389. defines.push("#define UV2");
  105390. }
  105391. // Bones
  105392. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105395. if (mesh.numBoneInfluencers > 4) {
  105396. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105397. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105398. }
  105399. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105400. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  105401. }
  105402. else {
  105403. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105404. }
  105405. // Morph targets
  105406. var manager = mesh.morphTargetManager;
  105407. var morphInfluencers = 0;
  105408. if (manager) {
  105409. if (manager.numInfluencers > 0) {
  105410. defines.push("#define MORPHTARGETS");
  105411. morphInfluencers = manager.numInfluencers;
  105412. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  105413. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  105414. }
  105415. }
  105416. // Instances
  105417. if (useInstances) {
  105418. defines.push("#define INSTANCES");
  105419. attribs.push("world0");
  105420. attribs.push("world1");
  105421. attribs.push("world2");
  105422. attribs.push("world3");
  105423. }
  105424. // Get correct effect
  105425. var join = defines.join("\n");
  105426. if (this._cachedDefines !== join) {
  105427. this._cachedDefines = join;
  105428. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  105429. }
  105430. return this._effectLayerMapGenerationEffect.isReady();
  105431. };
  105432. /**
  105433. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  105434. */
  105435. EffectLayer.prototype.render = function () {
  105436. var currentEffect = this._mergeEffect;
  105437. // Check
  105438. if (!currentEffect.isReady())
  105439. return;
  105440. for (var i = 0; i < this._postProcesses.length; i++) {
  105441. if (!this._postProcesses[i].isReady()) {
  105442. return;
  105443. }
  105444. }
  105445. var engine = this._scene.getEngine();
  105446. this.onBeforeComposeObservable.notifyObservers(this);
  105447. // Render
  105448. engine.enableEffect(currentEffect);
  105449. engine.setState(false);
  105450. // VBOs
  105451. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105452. // Cache
  105453. var previousAlphaMode = engine.getAlphaMode();
  105454. // Go Blend.
  105455. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  105456. // Blends the map on the main canvas.
  105457. this._internalRender(currentEffect);
  105458. // Restore Alpha
  105459. engine.setAlphaMode(previousAlphaMode);
  105460. this.onAfterComposeObservable.notifyObservers(this);
  105461. // Handle size changes.
  105462. var size = this._mainTexture.getSize();
  105463. this._setMainTextureSize();
  105464. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  105465. // Recreate RTT and post processes on size change.
  105466. this.onSizeChangedObservable.notifyObservers(this);
  105467. this._disposeTextureAndPostProcesses();
  105468. this._createMainTexture();
  105469. this._createTextureAndPostProcesses();
  105470. }
  105471. };
  105472. /**
  105473. * Determine if a given mesh will be used in the current effect.
  105474. * @param mesh mesh to test
  105475. * @returns true if the mesh will be used
  105476. */
  105477. EffectLayer.prototype.hasMesh = function (mesh) {
  105478. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  105479. return true;
  105480. }
  105481. return false;
  105482. };
  105483. /**
  105484. * Returns true if the layer contains information to display, otherwise false.
  105485. * @returns true if the glow layer should be rendered
  105486. */
  105487. EffectLayer.prototype.shouldRender = function () {
  105488. return this.isEnabled && this._shouldRender;
  105489. };
  105490. /**
  105491. * Returns true if the mesh should render, otherwise false.
  105492. * @param mesh The mesh to render
  105493. * @returns true if it should render otherwise false
  105494. */
  105495. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  105496. return true;
  105497. };
  105498. /**
  105499. * Returns true if the mesh should render, otherwise false.
  105500. * @param mesh The mesh to render
  105501. * @returns true if it should render otherwise false
  105502. */
  105503. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  105504. return true;
  105505. };
  105506. /**
  105507. * Renders the submesh passed in parameter to the generation map.
  105508. */
  105509. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  105510. var _this = this;
  105511. if (!this.shouldRender()) {
  105512. return;
  105513. }
  105514. var material = subMesh.getMaterial();
  105515. var mesh = subMesh.getRenderingMesh();
  105516. var scene = this._scene;
  105517. var engine = scene.getEngine();
  105518. if (!material) {
  105519. return;
  105520. }
  105521. // Do not block in blend mode.
  105522. if (material.needAlphaBlendingForMesh(mesh)) {
  105523. return;
  105524. }
  105525. // Culling
  105526. engine.setState(material.backFaceCulling);
  105527. // Managing instances
  105528. var batch = mesh._getInstancesRenderList(subMesh._id);
  105529. if (batch.mustReturn) {
  105530. return;
  105531. }
  105532. // Early Exit per mesh
  105533. if (!this._shouldRenderMesh(mesh)) {
  105534. return;
  105535. }
  105536. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  105537. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  105538. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  105539. engine.enableEffect(this._effectLayerMapGenerationEffect);
  105540. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  105541. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  105542. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  105543. // Alpha test
  105544. if (material && material.needAlphaTesting()) {
  105545. var alphaTexture = material.getAlphaTestTexture();
  105546. if (alphaTexture) {
  105547. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  105548. var textureMatrix = alphaTexture.getTextureMatrix();
  105549. if (textureMatrix) {
  105550. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  105551. }
  105552. }
  105553. }
  105554. // Glow emissive only
  105555. if (this._emissiveTextureAndColor.texture) {
  105556. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  105557. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  105558. }
  105559. // Bones
  105560. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  105561. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  105562. }
  105563. // Morph targets
  105564. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  105565. // Draw
  105566. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  105567. }
  105568. else {
  105569. // Need to reset refresh rate of the main map
  105570. this._mainTexture.resetRefreshCounter();
  105571. }
  105572. };
  105573. /**
  105574. * Rebuild the required buffers.
  105575. * @hidden Internal use only.
  105576. */
  105577. EffectLayer.prototype._rebuild = function () {
  105578. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105579. if (vb) {
  105580. vb._rebuild();
  105581. }
  105582. this._generateIndexBuffer();
  105583. };
  105584. /**
  105585. * Dispose only the render target textures and post process.
  105586. */
  105587. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  105588. this._mainTexture.dispose();
  105589. for (var i = 0; i < this._postProcesses.length; i++) {
  105590. if (this._postProcesses[i]) {
  105591. this._postProcesses[i].dispose();
  105592. }
  105593. }
  105594. this._postProcesses = [];
  105595. for (var i = 0; i < this._textures.length; i++) {
  105596. if (this._textures[i]) {
  105597. this._textures[i].dispose();
  105598. }
  105599. }
  105600. this._textures = [];
  105601. };
  105602. /**
  105603. * Dispose the highlight layer and free resources.
  105604. */
  105605. EffectLayer.prototype.dispose = function () {
  105606. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105607. if (vertexBuffer) {
  105608. vertexBuffer.dispose();
  105609. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105610. }
  105611. if (this._indexBuffer) {
  105612. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105613. this._indexBuffer = null;
  105614. }
  105615. // Clean textures and post processes
  105616. this._disposeTextureAndPostProcesses();
  105617. // Remove from scene
  105618. var index = this._scene.effectLayers.indexOf(this, 0);
  105619. if (index > -1) {
  105620. this._scene.effectLayers.splice(index, 1);
  105621. }
  105622. // Callback
  105623. this.onDisposeObservable.notifyObservers(this);
  105624. this.onDisposeObservable.clear();
  105625. this.onBeforeRenderMainTextureObservable.clear();
  105626. this.onBeforeComposeObservable.clear();
  105627. this.onAfterComposeObservable.clear();
  105628. this.onSizeChangedObservable.clear();
  105629. };
  105630. /**
  105631. * Gets the class name of the effect layer
  105632. * @returns the string with the class name of the effect layer
  105633. */
  105634. EffectLayer.prototype.getClassName = function () {
  105635. return "EffectLayer";
  105636. };
  105637. /**
  105638. * Creates an effect layer from parsed effect layer data
  105639. * @param parsedEffectLayer defines effect layer data
  105640. * @param scene defines the current scene
  105641. * @param rootUrl defines the root URL containing the effect layer information
  105642. * @returns a parsed effect Layer
  105643. */
  105644. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  105645. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  105646. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  105647. };
  105648. __decorate([
  105649. BABYLON.serialize()
  105650. ], EffectLayer.prototype, "name", void 0);
  105651. __decorate([
  105652. BABYLON.serializeAsColor4()
  105653. ], EffectLayer.prototype, "neutralColor", void 0);
  105654. __decorate([
  105655. BABYLON.serialize()
  105656. ], EffectLayer.prototype, "isEnabled", void 0);
  105657. __decorate([
  105658. BABYLON.serializeAsCameraReference()
  105659. ], EffectLayer.prototype, "camera", null);
  105660. __decorate([
  105661. BABYLON.serialize()
  105662. ], EffectLayer.prototype, "renderingGroupId", null);
  105663. return EffectLayer;
  105664. }());
  105665. BABYLON.EffectLayer = EffectLayer;
  105666. })(BABYLON || (BABYLON = {}));
  105667. //# sourceMappingURL=babylon.effectLayer.js.map
  105668. var BABYLON;
  105669. (function (BABYLON) {
  105670. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  105671. for (var index = 0; index < this.effectLayers.length; index++) {
  105672. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  105673. return this.effectLayers[index];
  105674. }
  105675. }
  105676. return null;
  105677. };
  105678. /**
  105679. * Special Glow Blur post process only blurring the alpha channel
  105680. * It enforces keeping the most luminous color in the color channel.
  105681. */
  105682. var GlowBlurPostProcess = /** @class */ (function (_super) {
  105683. __extends(GlowBlurPostProcess, _super);
  105684. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  105685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  105686. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  105687. _this.direction = direction;
  105688. _this.kernel = kernel;
  105689. _this.onApplyObservable.add(function (effect) {
  105690. effect.setFloat2("screenSize", _this.width, _this.height);
  105691. effect.setVector2("direction", _this.direction);
  105692. effect.setFloat("blurWidth", _this.kernel);
  105693. });
  105694. return _this;
  105695. }
  105696. return GlowBlurPostProcess;
  105697. }(BABYLON.PostProcess));
  105698. /**
  105699. * The highlight layer Helps adding a glow effect around a mesh.
  105700. *
  105701. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105702. * glowy meshes to your scene.
  105703. *
  105704. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  105705. */
  105706. var HighlightLayer = /** @class */ (function (_super) {
  105707. __extends(HighlightLayer, _super);
  105708. /**
  105709. * Instantiates a new highlight Layer and references it to the scene..
  105710. * @param name The name of the layer
  105711. * @param scene The scene to use the layer in
  105712. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  105713. */
  105714. function HighlightLayer(name, scene, options) {
  105715. var _this = _super.call(this, name, scene) || this;
  105716. _this.name = name;
  105717. /**
  105718. * Specifies whether or not the inner glow is ACTIVE in the layer.
  105719. */
  105720. _this.innerGlow = true;
  105721. /**
  105722. * Specifies whether or not the outer glow is ACTIVE in the layer.
  105723. */
  105724. _this.outerGlow = true;
  105725. /**
  105726. * An event triggered when the highlight layer is being blurred.
  105727. */
  105728. _this.onBeforeBlurObservable = new BABYLON.Observable();
  105729. /**
  105730. * An event triggered when the highlight layer has been blurred.
  105731. */
  105732. _this.onAfterBlurObservable = new BABYLON.Observable();
  105733. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  105734. _this._meshes = {};
  105735. _this._excludedMeshes = {};
  105736. _this.neutralColor = HighlightLayer.NeutralColor;
  105737. // Warn on stencil
  105738. if (!_this._engine.isStencilEnable) {
  105739. 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 }");
  105740. }
  105741. // Adapt options
  105742. _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);
  105743. // Initialize the layer
  105744. _this._init({
  105745. alphaBlendingMode: _this._options.alphaBlendingMode,
  105746. camera: _this._options.camera,
  105747. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105748. mainTextureRatio: _this._options.mainTextureRatio,
  105749. renderingGroupId: _this._options.renderingGroupId
  105750. });
  105751. // Do not render as long as no meshes have been added
  105752. _this._shouldRender = false;
  105753. return _this;
  105754. }
  105755. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  105756. /**
  105757. * Gets the horizontal size of the blur.
  105758. */
  105759. get: function () {
  105760. return this._horizontalBlurPostprocess.kernel;
  105761. },
  105762. /**
  105763. * Specifies the horizontal size of the blur.
  105764. */
  105765. set: function (value) {
  105766. this._horizontalBlurPostprocess.kernel = value;
  105767. },
  105768. enumerable: true,
  105769. configurable: true
  105770. });
  105771. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  105772. /**
  105773. * Gets the vertical size of the blur.
  105774. */
  105775. get: function () {
  105776. return this._verticalBlurPostprocess.kernel;
  105777. },
  105778. /**
  105779. * Specifies the vertical size of the blur.
  105780. */
  105781. set: function (value) {
  105782. this._verticalBlurPostprocess.kernel = value;
  105783. },
  105784. enumerable: true,
  105785. configurable: true
  105786. });
  105787. /**
  105788. * Get the effect name of the layer.
  105789. * @return The effect name
  105790. */
  105791. HighlightLayer.prototype.getEffectName = function () {
  105792. return HighlightLayer.EffectName;
  105793. };
  105794. /**
  105795. * Create the merge effect. This is the shader use to blit the information back
  105796. * to the main canvas at the end of the scene rendering.
  105797. */
  105798. HighlightLayer.prototype._createMergeEffect = function () {
  105799. // Effect
  105800. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  105801. };
  105802. /**
  105803. * Creates the render target textures and post processes used in the highlight layer.
  105804. */
  105805. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  105806. var _this = this;
  105807. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  105808. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  105809. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105810. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105811. var textureType = 0;
  105812. if (this._engine.getCaps().textureHalfFloatRender) {
  105813. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105814. }
  105815. else {
  105816. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105817. }
  105818. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  105819. width: blurTextureWidth,
  105820. height: blurTextureHeight
  105821. }, this._scene, false, true, textureType);
  105822. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105823. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105824. this._blurTexture.anisotropicFilteringLevel = 16;
  105825. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  105826. this._blurTexture.renderParticles = false;
  105827. this._blurTexture.ignoreCameraViewport = true;
  105828. this._textures = [this._blurTexture];
  105829. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  105830. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105831. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  105832. effect.setTexture("textureSampler", _this._mainTexture);
  105833. });
  105834. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105835. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105836. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105837. });
  105838. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105839. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  105840. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105841. });
  105842. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105843. }
  105844. else {
  105845. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  105846. width: blurTextureWidth,
  105847. height: blurTextureHeight
  105848. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105849. this._horizontalBlurPostprocess.width = blurTextureWidth;
  105850. this._horizontalBlurPostprocess.height = blurTextureHeight;
  105851. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105852. effect.setTexture("textureSampler", _this._mainTexture);
  105853. });
  105854. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  105855. width: blurTextureWidth,
  105856. height: blurTextureHeight
  105857. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105858. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105859. }
  105860. this._mainTexture.onAfterUnbindObservable.add(function () {
  105861. _this.onBeforeBlurObservable.notifyObservers(_this);
  105862. var internalTexture = _this._blurTexture.getInternalTexture();
  105863. if (internalTexture) {
  105864. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  105865. }
  105866. _this.onAfterBlurObservable.notifyObservers(_this);
  105867. });
  105868. // Prevent autoClear.
  105869. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105870. };
  105871. /**
  105872. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105873. */
  105874. HighlightLayer.prototype.needStencil = function () {
  105875. return true;
  105876. };
  105877. /**
  105878. * Checks for the readiness of the element composing the layer.
  105879. * @param subMesh the mesh to check for
  105880. * @param useInstances specify wether or not to use instances to render the mesh
  105881. * @param emissiveTexture the associated emissive texture used to generate the glow
  105882. * @return true if ready otherwise, false
  105883. */
  105884. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  105885. var material = subMesh.getMaterial();
  105886. var mesh = subMesh.getRenderingMesh();
  105887. if (!material || !mesh || !this._meshes) {
  105888. return false;
  105889. }
  105890. var emissiveTexture = null;
  105891. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105892. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105893. emissiveTexture = material.emissiveTexture;
  105894. }
  105895. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105896. };
  105897. /**
  105898. * Implementation specific of rendering the generating effect on the main canvas.
  105899. * @param effect The effect used to render through
  105900. */
  105901. HighlightLayer.prototype._internalRender = function (effect) {
  105902. // Texture
  105903. effect.setTexture("textureSampler", this._blurTexture);
  105904. // Cache
  105905. var engine = this._engine;
  105906. var previousStencilBuffer = engine.getStencilBuffer();
  105907. var previousStencilFunction = engine.getStencilFunction();
  105908. var previousStencilMask = engine.getStencilMask();
  105909. var previousStencilOperationPass = engine.getStencilOperationPass();
  105910. var previousStencilOperationFail = engine.getStencilOperationFail();
  105911. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  105912. var previousStencilReference = engine.getStencilFunctionReference();
  105913. // Stencil operations
  105914. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  105915. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  105916. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  105917. // Draw order
  105918. engine.setStencilMask(0x00);
  105919. engine.setStencilBuffer(true);
  105920. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  105921. // 2 passes inner outer
  105922. if (this.outerGlow) {
  105923. effect.setFloat("offset", 0);
  105924. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  105925. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105926. }
  105927. if (this.innerGlow) {
  105928. effect.setFloat("offset", 1);
  105929. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  105930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105931. }
  105932. // Restore Cache
  105933. engine.setStencilFunction(previousStencilFunction);
  105934. engine.setStencilMask(previousStencilMask);
  105935. engine.setStencilBuffer(previousStencilBuffer);
  105936. engine.setStencilOperationPass(previousStencilOperationPass);
  105937. engine.setStencilOperationFail(previousStencilOperationFail);
  105938. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  105939. engine.setStencilFunctionReference(previousStencilReference);
  105940. };
  105941. /**
  105942. * Returns true if the layer contains information to display, otherwise false.
  105943. */
  105944. HighlightLayer.prototype.shouldRender = function () {
  105945. if (_super.prototype.shouldRender.call(this)) {
  105946. return this._meshes ? true : false;
  105947. }
  105948. return false;
  105949. };
  105950. /**
  105951. * Returns true if the mesh should render, otherwise false.
  105952. * @param mesh The mesh to render
  105953. * @returns true if it should render otherwise false
  105954. */
  105955. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  105956. // Excluded Mesh
  105957. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  105958. return false;
  105959. }
  105960. ;
  105961. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105962. return false;
  105963. }
  105964. return true;
  105965. };
  105966. /**
  105967. * Sets the required values for both the emissive texture and and the main color.
  105968. */
  105969. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105970. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105971. if (highlightLayerMesh) {
  105972. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  105973. }
  105974. else {
  105975. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105976. }
  105977. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105978. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105979. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  105980. }
  105981. else {
  105982. this._emissiveTextureAndColor.texture = null;
  105983. }
  105984. };
  105985. /**
  105986. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  105987. * @param mesh The mesh to exclude from the highlight layer
  105988. */
  105989. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  105990. if (!this._excludedMeshes) {
  105991. return;
  105992. }
  105993. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105994. if (!meshExcluded) {
  105995. this._excludedMeshes[mesh.uniqueId] = {
  105996. mesh: mesh,
  105997. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  105998. mesh.getEngine().setStencilBuffer(false);
  105999. }),
  106000. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  106001. mesh.getEngine().setStencilBuffer(true);
  106002. }),
  106003. };
  106004. }
  106005. };
  106006. /**
  106007. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  106008. * @param mesh The mesh to highlight
  106009. */
  106010. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  106011. if (!this._excludedMeshes) {
  106012. return;
  106013. }
  106014. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  106015. if (meshExcluded) {
  106016. if (meshExcluded.beforeRender) {
  106017. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  106018. }
  106019. if (meshExcluded.afterRender) {
  106020. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  106021. }
  106022. }
  106023. this._excludedMeshes[mesh.uniqueId] = null;
  106024. };
  106025. /**
  106026. * Determine if a given mesh will be highlighted by the current HighlightLayer
  106027. * @param mesh mesh to test
  106028. * @returns true if the mesh will be highlighted by the current HighlightLayer
  106029. */
  106030. HighlightLayer.prototype.hasMesh = function (mesh) {
  106031. if (!this._meshes) {
  106032. return false;
  106033. }
  106034. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106035. return false;
  106036. }
  106037. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  106038. };
  106039. /**
  106040. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  106041. * @param mesh The mesh to highlight
  106042. * @param color The color of the highlight
  106043. * @param glowEmissiveOnly Extract the glow from the emissive texture
  106044. */
  106045. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  106046. var _this = this;
  106047. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  106048. if (!this._meshes) {
  106049. return;
  106050. }
  106051. var meshHighlight = this._meshes[mesh.uniqueId];
  106052. if (meshHighlight) {
  106053. meshHighlight.color = color;
  106054. }
  106055. else {
  106056. this._meshes[mesh.uniqueId] = {
  106057. mesh: mesh,
  106058. color: color,
  106059. // Lambda required for capture due to Observable this context
  106060. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  106061. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  106062. _this._defaultStencilReference(mesh);
  106063. }
  106064. else {
  106065. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  106066. }
  106067. }),
  106068. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  106069. glowEmissiveOnly: glowEmissiveOnly
  106070. };
  106071. mesh.onDisposeObservable.add(function () {
  106072. _this._disposeMesh(mesh);
  106073. });
  106074. }
  106075. this._shouldRender = true;
  106076. };
  106077. /**
  106078. * Remove a mesh from the highlight layer in order to make it stop glowing.
  106079. * @param mesh The mesh to highlight
  106080. */
  106081. HighlightLayer.prototype.removeMesh = function (mesh) {
  106082. if (!this._meshes) {
  106083. return;
  106084. }
  106085. var meshHighlight = this._meshes[mesh.uniqueId];
  106086. if (meshHighlight) {
  106087. if (meshHighlight.observerHighlight) {
  106088. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106089. }
  106090. if (meshHighlight.observerDefault) {
  106091. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106092. }
  106093. delete this._meshes[mesh.uniqueId];
  106094. }
  106095. this._shouldRender = false;
  106096. for (var meshHighlightToCheck in this._meshes) {
  106097. if (this._meshes[meshHighlightToCheck]) {
  106098. this._shouldRender = true;
  106099. break;
  106100. }
  106101. }
  106102. };
  106103. /**
  106104. * Force the stencil to the normal expected value for none glowing parts
  106105. */
  106106. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  106107. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  106108. };
  106109. /**
  106110. * Free any resources and references associated to a mesh.
  106111. * Internal use
  106112. * @param mesh The mesh to free.
  106113. * @hidden
  106114. */
  106115. HighlightLayer.prototype._disposeMesh = function (mesh) {
  106116. this.removeMesh(mesh);
  106117. this.removeExcludedMesh(mesh);
  106118. };
  106119. /**
  106120. * Dispose the highlight layer and free resources.
  106121. */
  106122. HighlightLayer.prototype.dispose = function () {
  106123. if (this._meshes) {
  106124. // Clean mesh references
  106125. for (var id in this._meshes) {
  106126. var meshHighlight = this._meshes[id];
  106127. if (meshHighlight && meshHighlight.mesh) {
  106128. if (meshHighlight.observerHighlight) {
  106129. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106130. }
  106131. if (meshHighlight.observerDefault) {
  106132. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106133. }
  106134. }
  106135. }
  106136. this._meshes = null;
  106137. }
  106138. if (this._excludedMeshes) {
  106139. for (var id in this._excludedMeshes) {
  106140. var meshHighlight = this._excludedMeshes[id];
  106141. if (meshHighlight) {
  106142. if (meshHighlight.beforeRender) {
  106143. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  106144. }
  106145. if (meshHighlight.afterRender) {
  106146. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  106147. }
  106148. }
  106149. }
  106150. this._excludedMeshes = null;
  106151. }
  106152. _super.prototype.dispose.call(this);
  106153. };
  106154. /**
  106155. * Gets the class name of the effect layer
  106156. * @returns the string with the class name of the effect layer
  106157. */
  106158. HighlightLayer.prototype.getClassName = function () {
  106159. return "HighlightLayer";
  106160. };
  106161. /**
  106162. * Serializes this Highlight layer
  106163. * @returns a serialized Highlight layer object
  106164. */
  106165. HighlightLayer.prototype.serialize = function () {
  106166. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106167. serializationObject.customType = "BABYLON.HighlightLayer";
  106168. // Highlighted meshes
  106169. serializationObject.meshes = [];
  106170. if (this._meshes) {
  106171. for (var m in this._meshes) {
  106172. var mesh = this._meshes[m];
  106173. if (mesh) {
  106174. serializationObject.meshes.push({
  106175. glowEmissiveOnly: mesh.glowEmissiveOnly,
  106176. color: mesh.color.asArray(),
  106177. meshId: mesh.mesh.id
  106178. });
  106179. }
  106180. }
  106181. }
  106182. // Excluded meshes
  106183. serializationObject.excludedMeshes = [];
  106184. if (this._excludedMeshes) {
  106185. for (var e in this._excludedMeshes) {
  106186. var excludedMesh = this._excludedMeshes[e];
  106187. if (excludedMesh) {
  106188. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  106189. }
  106190. }
  106191. }
  106192. return serializationObject;
  106193. };
  106194. /**
  106195. * Creates a Highlight layer from parsed Highlight layer data
  106196. * @param parsedHightlightLayer defines the Highlight layer data
  106197. * @param scene defines the current scene
  106198. * @param rootUrl defines the root URL containing the Highlight layer information
  106199. * @returns a parsed Highlight layer
  106200. */
  106201. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  106202. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  106203. var index;
  106204. // Excluded meshes
  106205. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  106206. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  106207. if (mesh) {
  106208. hl.addExcludedMesh(mesh);
  106209. }
  106210. }
  106211. // Included meshes
  106212. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  106213. var highlightedMesh = parsedHightlightLayer.meshes[index];
  106214. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  106215. if (mesh) {
  106216. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  106217. }
  106218. }
  106219. return hl;
  106220. };
  106221. /**
  106222. * Effect Name of the highlight layer.
  106223. */
  106224. HighlightLayer.EffectName = "HighlightLayer";
  106225. /**
  106226. * The neutral color used during the preparation of the glow effect.
  106227. * This is black by default as the blend operation is a blend operation.
  106228. */
  106229. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  106230. /**
  106231. * Stencil value used for glowing meshes.
  106232. */
  106233. HighlightLayer.GlowingMeshStencilReference = 0x02;
  106234. /**
  106235. * Stencil value used for the other meshes in the scene.
  106236. */
  106237. HighlightLayer.NormalMeshStencilReference = 0x01;
  106238. __decorate([
  106239. BABYLON.serialize()
  106240. ], HighlightLayer.prototype, "innerGlow", void 0);
  106241. __decorate([
  106242. BABYLON.serialize()
  106243. ], HighlightLayer.prototype, "outerGlow", void 0);
  106244. __decorate([
  106245. BABYLON.serialize()
  106246. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  106247. __decorate([
  106248. BABYLON.serialize()
  106249. ], HighlightLayer.prototype, "blurVerticalSize", null);
  106250. __decorate([
  106251. BABYLON.serialize("options")
  106252. ], HighlightLayer.prototype, "_options", void 0);
  106253. return HighlightLayer;
  106254. }(BABYLON.EffectLayer));
  106255. BABYLON.HighlightLayer = HighlightLayer;
  106256. })(BABYLON || (BABYLON = {}));
  106257. //# sourceMappingURL=babylon.highlightLayer.js.map
  106258. var BABYLON;
  106259. (function (BABYLON) {
  106260. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  106261. for (var index = 0; index < this.effectLayers.length; index++) {
  106262. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  106263. return this.effectLayers[index];
  106264. }
  106265. }
  106266. return null;
  106267. };
  106268. /**
  106269. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  106270. *
  106271. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106272. * glowy meshes to your scene.
  106273. *
  106274. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  106275. */
  106276. var GlowLayer = /** @class */ (function (_super) {
  106277. __extends(GlowLayer, _super);
  106278. /**
  106279. * Instantiates a new glow Layer and references it to the scene.
  106280. * @param name The name of the layer
  106281. * @param scene The scene to use the layer in
  106282. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  106283. */
  106284. function GlowLayer(name, scene, options) {
  106285. var _this = _super.call(this, name, scene) || this;
  106286. _this._intensity = 1.0;
  106287. _this._includedOnlyMeshes = [];
  106288. _this._excludedMeshes = [];
  106289. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  106290. // Adapt options
  106291. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  106292. // Initialize the layer
  106293. _this._init({
  106294. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  106295. camera: _this._options.camera,
  106296. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106297. mainTextureRatio: _this._options.mainTextureRatio,
  106298. renderingGroupId: _this._options.renderingGroupId
  106299. });
  106300. return _this;
  106301. }
  106302. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  106303. /**
  106304. * Gets the kernel size of the blur.
  106305. */
  106306. get: function () {
  106307. return this._horizontalBlurPostprocess1.kernel;
  106308. },
  106309. /**
  106310. * Sets the kernel size of the blur.
  106311. */
  106312. set: function (value) {
  106313. this._horizontalBlurPostprocess1.kernel = value;
  106314. this._verticalBlurPostprocess1.kernel = value;
  106315. this._horizontalBlurPostprocess2.kernel = value;
  106316. this._verticalBlurPostprocess2.kernel = value;
  106317. },
  106318. enumerable: true,
  106319. configurable: true
  106320. });
  106321. Object.defineProperty(GlowLayer.prototype, "intensity", {
  106322. /**
  106323. * Gets the glow intensity.
  106324. */
  106325. get: function () {
  106326. return this._intensity;
  106327. },
  106328. /**
  106329. * Sets the glow intensity.
  106330. */
  106331. set: function (value) {
  106332. this._intensity = value;
  106333. },
  106334. enumerable: true,
  106335. configurable: true
  106336. });
  106337. /**
  106338. * Get the effect name of the layer.
  106339. * @return The effect name
  106340. */
  106341. GlowLayer.prototype.getEffectName = function () {
  106342. return GlowLayer.EffectName;
  106343. };
  106344. /**
  106345. * Create the merge effect. This is the shader use to blit the information back
  106346. * to the main canvas at the end of the scene rendering.
  106347. */
  106348. GlowLayer.prototype._createMergeEffect = function () {
  106349. // Effect
  106350. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  106351. };
  106352. /**
  106353. * Creates the render target textures and post processes used in the glow layer.
  106354. */
  106355. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  106356. var _this = this;
  106357. var blurTextureWidth = this._mainTextureDesiredSize.width;
  106358. var blurTextureHeight = this._mainTextureDesiredSize.height;
  106359. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106360. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106361. var textureType = 0;
  106362. if (this._engine.getCaps().textureHalfFloatRender) {
  106363. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106364. }
  106365. else {
  106366. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106367. }
  106368. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  106369. width: blurTextureWidth,
  106370. height: blurTextureHeight
  106371. }, this._scene, false, true, textureType);
  106372. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106373. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106374. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106375. this._blurTexture1.renderParticles = false;
  106376. this._blurTexture1.ignoreCameraViewport = true;
  106377. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  106378. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  106379. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  106380. width: blurTextureWidth2,
  106381. height: blurTextureHeight2
  106382. }, this._scene, false, true, textureType);
  106383. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106384. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106385. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106386. this._blurTexture2.renderParticles = false;
  106387. this._blurTexture2.ignoreCameraViewport = true;
  106388. this._textures = [this._blurTexture1, this._blurTexture2];
  106389. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106390. width: blurTextureWidth,
  106391. height: blurTextureHeight
  106392. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106393. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  106394. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  106395. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  106396. effect.setTexture("textureSampler", _this._mainTexture);
  106397. });
  106398. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106399. width: blurTextureWidth,
  106400. height: blurTextureHeight
  106401. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106402. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106403. width: blurTextureWidth2,
  106404. height: blurTextureHeight2
  106405. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106406. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  106407. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  106408. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  106409. effect.setTexture("textureSampler", _this._blurTexture1);
  106410. });
  106411. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106412. width: blurTextureWidth2,
  106413. height: blurTextureHeight2
  106414. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106415. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106416. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  106417. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106418. this._mainTexture.samples = this._options.mainTextureSamples;
  106419. this._mainTexture.onAfterUnbindObservable.add(function () {
  106420. var internalTexture = _this._blurTexture1.getInternalTexture();
  106421. if (internalTexture) {
  106422. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  106423. internalTexture = _this._blurTexture2.getInternalTexture();
  106424. if (internalTexture) {
  106425. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  106426. }
  106427. }
  106428. });
  106429. // Prevent autoClear.
  106430. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106431. };
  106432. /**
  106433. * Checks for the readiness of the element composing the layer.
  106434. * @param subMesh the mesh to check for
  106435. * @param useInstances specify wether or not to use instances to render the mesh
  106436. * @param emissiveTexture the associated emissive texture used to generate the glow
  106437. * @return true if ready otherwise, false
  106438. */
  106439. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  106440. var material = subMesh.getMaterial();
  106441. var mesh = subMesh.getRenderingMesh();
  106442. if (!material || !mesh) {
  106443. return false;
  106444. }
  106445. var emissiveTexture = material.emissiveTexture;
  106446. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  106447. };
  106448. /**
  106449. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  106450. */
  106451. GlowLayer.prototype.needStencil = function () {
  106452. return false;
  106453. };
  106454. /**
  106455. * Implementation specific of rendering the generating effect on the main canvas.
  106456. * @param effect The effect used to render through
  106457. */
  106458. GlowLayer.prototype._internalRender = function (effect) {
  106459. // Texture
  106460. effect.setTexture("textureSampler", this._blurTexture1);
  106461. effect.setTexture("textureSampler2", this._blurTexture2);
  106462. effect.setFloat("offset", this._intensity);
  106463. // Cache
  106464. var engine = this._engine;
  106465. var previousStencilBuffer = engine.getStencilBuffer();
  106466. // Draw order
  106467. engine.setStencilBuffer(false);
  106468. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106469. // Draw order
  106470. engine.setStencilBuffer(previousStencilBuffer);
  106471. };
  106472. /**
  106473. * Sets the required values for both the emissive texture and and the main color.
  106474. */
  106475. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  106476. var textureLevel = 1.0;
  106477. if (this.customEmissiveTextureSelector) {
  106478. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  106479. }
  106480. else {
  106481. if (material) {
  106482. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  106483. if (this._emissiveTextureAndColor.texture) {
  106484. textureLevel = this._emissiveTextureAndColor.texture.level;
  106485. }
  106486. }
  106487. else {
  106488. this._emissiveTextureAndColor.texture = null;
  106489. }
  106490. }
  106491. if (this.customEmissiveColorSelector) {
  106492. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  106493. }
  106494. else {
  106495. if (material.emissiveColor) {
  106496. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  106497. }
  106498. else {
  106499. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  106500. }
  106501. }
  106502. };
  106503. /**
  106504. * Returns true if the mesh should render, otherwise false.
  106505. * @param mesh The mesh to render
  106506. * @returns true if it should render otherwise false
  106507. */
  106508. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  106509. return this.hasMesh(mesh);
  106510. };
  106511. /**
  106512. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  106513. * @param mesh The mesh to exclude from the glow layer
  106514. */
  106515. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  106516. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  106517. this._excludedMeshes.push(mesh.uniqueId);
  106518. }
  106519. };
  106520. /**
  106521. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  106522. * @param mesh The mesh to remove
  106523. */
  106524. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  106525. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  106526. if (index !== -1) {
  106527. this._excludedMeshes.splice(index, 1);
  106528. }
  106529. };
  106530. /**
  106531. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  106532. * @param mesh The mesh to include in the glow layer
  106533. */
  106534. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  106535. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  106536. this._includedOnlyMeshes.push(mesh.uniqueId);
  106537. }
  106538. };
  106539. /**
  106540. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  106541. * @param mesh The mesh to remove
  106542. */
  106543. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  106544. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  106545. if (index !== -1) {
  106546. this._includedOnlyMeshes.splice(index, 1);
  106547. }
  106548. };
  106549. /**
  106550. * Determine if a given mesh will be used in the glow layer
  106551. * @param mesh The mesh to test
  106552. * @returns true if the mesh will be highlighted by the current glow layer
  106553. */
  106554. GlowLayer.prototype.hasMesh = function (mesh) {
  106555. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106556. return false;
  106557. }
  106558. // Included Mesh
  106559. if (this._includedOnlyMeshes.length) {
  106560. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  106561. }
  106562. ;
  106563. // Excluded Mesh
  106564. if (this._excludedMeshes.length) {
  106565. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  106566. }
  106567. ;
  106568. return true;
  106569. };
  106570. /**
  106571. * Free any resources and references associated to a mesh.
  106572. * Internal use
  106573. * @param mesh The mesh to free.
  106574. * @hidden
  106575. */
  106576. GlowLayer.prototype._disposeMesh = function (mesh) {
  106577. this.removeIncludedOnlyMesh(mesh);
  106578. this.removeExcludedMesh(mesh);
  106579. };
  106580. /**
  106581. * Gets the class name of the effect layer
  106582. * @returns the string with the class name of the effect layer
  106583. */
  106584. GlowLayer.prototype.getClassName = function () {
  106585. return "GlowLayer";
  106586. };
  106587. /**
  106588. * Serializes this glow layer
  106589. * @returns a serialized glow layer object
  106590. */
  106591. GlowLayer.prototype.serialize = function () {
  106592. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106593. serializationObject.customType = "BABYLON.GlowLayer";
  106594. var index;
  106595. // Included meshes
  106596. serializationObject.includedMeshes = [];
  106597. if (this._includedOnlyMeshes.length) {
  106598. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  106599. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  106600. if (mesh) {
  106601. serializationObject.includedMeshes.push(mesh.id);
  106602. }
  106603. }
  106604. }
  106605. // Excluded meshes
  106606. serializationObject.excludedMeshes = [];
  106607. if (this._excludedMeshes.length) {
  106608. for (index = 0; index < this._excludedMeshes.length; index++) {
  106609. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  106610. if (mesh) {
  106611. serializationObject.excludedMeshes.push(mesh.id);
  106612. }
  106613. }
  106614. }
  106615. return serializationObject;
  106616. };
  106617. /**
  106618. * Creates a Glow Layer from parsed glow layer data
  106619. * @param parsedGlowLayer defines glow layer data
  106620. * @param scene defines the current scene
  106621. * @param rootUrl defines the root URL containing the glow layer information
  106622. * @returns a parsed Glow Layer
  106623. */
  106624. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  106625. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  106626. var index;
  106627. // Excluded meshes
  106628. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  106629. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  106630. if (mesh) {
  106631. gl.addExcludedMesh(mesh);
  106632. }
  106633. }
  106634. // Included meshes
  106635. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  106636. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  106637. if (mesh) {
  106638. gl.addIncludedOnlyMesh(mesh);
  106639. }
  106640. }
  106641. return gl;
  106642. };
  106643. /**
  106644. * Effect Name of the layer.
  106645. */
  106646. GlowLayer.EffectName = "GlowLayer";
  106647. /**
  106648. * The default blur kernel size used for the glow.
  106649. */
  106650. GlowLayer.DefaultBlurKernelSize = 32;
  106651. /**
  106652. * The default texture size ratio used for the glow.
  106653. */
  106654. GlowLayer.DefaultTextureRatio = 0.5;
  106655. __decorate([
  106656. BABYLON.serialize()
  106657. ], GlowLayer.prototype, "blurKernelSize", null);
  106658. __decorate([
  106659. BABYLON.serialize()
  106660. ], GlowLayer.prototype, "intensity", null);
  106661. __decorate([
  106662. BABYLON.serialize("options")
  106663. ], GlowLayer.prototype, "_options", void 0);
  106664. return GlowLayer;
  106665. }(BABYLON.EffectLayer));
  106666. BABYLON.GlowLayer = GlowLayer;
  106667. })(BABYLON || (BABYLON = {}));
  106668. //# sourceMappingURL=babylon.glowLayer.js.map
  106669. var BABYLON;
  106670. (function (BABYLON) {
  106671. /**
  106672. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  106673. */
  106674. var AssetTaskState;
  106675. (function (AssetTaskState) {
  106676. /**
  106677. * Initialization
  106678. */
  106679. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  106680. /**
  106681. * Running
  106682. */
  106683. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  106684. /**
  106685. * Done
  106686. */
  106687. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  106688. /**
  106689. * Error
  106690. */
  106691. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  106692. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  106693. /**
  106694. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  106695. */
  106696. var AbstractAssetTask = /** @class */ (function () {
  106697. /**
  106698. * Creates a new {BABYLON.AssetsManager}
  106699. * @param name defines the name of the task
  106700. */
  106701. function AbstractAssetTask(
  106702. /**
  106703. * Task name
  106704. */ name) {
  106705. this.name = name;
  106706. this._isCompleted = false;
  106707. this._taskState = AssetTaskState.INIT;
  106708. }
  106709. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  106710. /**
  106711. * Get if the task is completed
  106712. */
  106713. get: function () {
  106714. return this._isCompleted;
  106715. },
  106716. enumerable: true,
  106717. configurable: true
  106718. });
  106719. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  106720. /**
  106721. * Gets the current state of the task
  106722. */
  106723. get: function () {
  106724. return this._taskState;
  106725. },
  106726. enumerable: true,
  106727. configurable: true
  106728. });
  106729. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  106730. /**
  106731. * Gets the current error object (if task is in error)
  106732. */
  106733. get: function () {
  106734. return this._errorObject;
  106735. },
  106736. enumerable: true,
  106737. configurable: true
  106738. });
  106739. /**
  106740. * Internal only
  106741. * @hidden
  106742. */
  106743. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  106744. if (this._errorObject) {
  106745. return;
  106746. }
  106747. this._errorObject = {
  106748. message: message,
  106749. exception: exception
  106750. };
  106751. };
  106752. /**
  106753. * Execute the current task
  106754. * @param scene defines the scene where you want your assets to be loaded
  106755. * @param onSuccess is a callback called when the task is successfully executed
  106756. * @param onError is a callback called if an error occurs
  106757. */
  106758. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106759. var _this = this;
  106760. this._taskState = AssetTaskState.RUNNING;
  106761. this.runTask(scene, function () {
  106762. _this.onDoneCallback(onSuccess, onError);
  106763. }, function (msg, exception) {
  106764. _this.onErrorCallback(onError, msg, exception);
  106765. });
  106766. };
  106767. /**
  106768. * Execute the current task
  106769. * @param scene defines the scene where you want your assets to be loaded
  106770. * @param onSuccess is a callback called when the task is successfully executed
  106771. * @param onError is a callback called if an error occurs
  106772. */
  106773. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106774. throw new Error("runTask is not implemented");
  106775. };
  106776. /**
  106777. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  106778. * This can be used with failed tasks that have the reason for failure fixed.
  106779. */
  106780. AbstractAssetTask.prototype.reset = function () {
  106781. this._taskState = AssetTaskState.INIT;
  106782. };
  106783. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  106784. this._taskState = AssetTaskState.ERROR;
  106785. this._errorObject = {
  106786. message: message,
  106787. exception: exception
  106788. };
  106789. if (this.onError) {
  106790. this.onError(this, message, exception);
  106791. }
  106792. onError();
  106793. };
  106794. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  106795. try {
  106796. this._taskState = AssetTaskState.DONE;
  106797. this._isCompleted = true;
  106798. if (this.onSuccess) {
  106799. this.onSuccess(this);
  106800. }
  106801. onSuccess();
  106802. }
  106803. catch (e) {
  106804. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  106805. }
  106806. };
  106807. return AbstractAssetTask;
  106808. }());
  106809. BABYLON.AbstractAssetTask = AbstractAssetTask;
  106810. /**
  106811. * Class used to share progress information about assets loading
  106812. */
  106813. var AssetsProgressEvent = /** @class */ (function () {
  106814. /**
  106815. * Creates a {BABYLON.AssetsProgressEvent}
  106816. * @param remainingCount defines the number of remaining tasks to process
  106817. * @param totalCount defines the total number of tasks
  106818. * @param task defines the task that was just processed
  106819. */
  106820. function AssetsProgressEvent(remainingCount, totalCount, task) {
  106821. this.remainingCount = remainingCount;
  106822. this.totalCount = totalCount;
  106823. this.task = task;
  106824. }
  106825. return AssetsProgressEvent;
  106826. }());
  106827. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  106828. /**
  106829. * Define a task used by {BABYLON.AssetsManager} to load meshes
  106830. */
  106831. var MeshAssetTask = /** @class */ (function (_super) {
  106832. __extends(MeshAssetTask, _super);
  106833. /**
  106834. * Creates a new {BABYLON.MeshAssetTask}
  106835. * @param name defines the name of the task
  106836. * @param meshesNames defines the list of mesh's names you want to load
  106837. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  106838. * @param sceneFilename defines the filename of the scene to load from
  106839. */
  106840. function MeshAssetTask(
  106841. /**
  106842. * Defines the name of the task
  106843. */
  106844. name,
  106845. /**
  106846. * Defines the list of mesh's names you want to load
  106847. */
  106848. meshesNames,
  106849. /**
  106850. * Defines the root url to use as a base to load your meshes and associated resources
  106851. */
  106852. rootUrl,
  106853. /**
  106854. * Defines the filename of the scene to load from
  106855. */
  106856. sceneFilename) {
  106857. var _this = _super.call(this, name) || this;
  106858. _this.name = name;
  106859. _this.meshesNames = meshesNames;
  106860. _this.rootUrl = rootUrl;
  106861. _this.sceneFilename = sceneFilename;
  106862. return _this;
  106863. }
  106864. /**
  106865. * Execute the current task
  106866. * @param scene defines the scene where you want your assets to be loaded
  106867. * @param onSuccess is a callback called when the task is successfully executed
  106868. * @param onError is a callback called if an error occurs
  106869. */
  106870. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106871. var _this = this;
  106872. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  106873. _this.loadedMeshes = meshes;
  106874. _this.loadedParticleSystems = particleSystems;
  106875. _this.loadedSkeletons = skeletons;
  106876. onSuccess();
  106877. }, null, function (scene, message, exception) {
  106878. onError(message, exception);
  106879. });
  106880. };
  106881. return MeshAssetTask;
  106882. }(AbstractAssetTask));
  106883. BABYLON.MeshAssetTask = MeshAssetTask;
  106884. /**
  106885. * Define a task used by {BABYLON.AssetsManager} to load text content
  106886. */
  106887. var TextFileAssetTask = /** @class */ (function (_super) {
  106888. __extends(TextFileAssetTask, _super);
  106889. /**
  106890. * Creates a new TextFileAssetTask object
  106891. * @param name defines the name of the task
  106892. * @param url defines the location of the file to load
  106893. */
  106894. function TextFileAssetTask(
  106895. /**
  106896. * Defines the name of the task
  106897. */
  106898. name,
  106899. /**
  106900. * Defines the location of the file to load
  106901. */
  106902. url) {
  106903. var _this = _super.call(this, name) || this;
  106904. _this.name = name;
  106905. _this.url = url;
  106906. return _this;
  106907. }
  106908. /**
  106909. * Execute the current task
  106910. * @param scene defines the scene where you want your assets to be loaded
  106911. * @param onSuccess is a callback called when the task is successfully executed
  106912. * @param onError is a callback called if an error occurs
  106913. */
  106914. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106915. var _this = this;
  106916. scene._loadFile(this.url, function (data) {
  106917. _this.text = data;
  106918. onSuccess();
  106919. }, undefined, false, false, function (request, exception) {
  106920. if (request) {
  106921. onError(request.status + " " + request.statusText, exception);
  106922. }
  106923. });
  106924. };
  106925. return TextFileAssetTask;
  106926. }(AbstractAssetTask));
  106927. BABYLON.TextFileAssetTask = TextFileAssetTask;
  106928. /**
  106929. * Define a task used by {BABYLON.AssetsManager} to load binary data
  106930. */
  106931. var BinaryFileAssetTask = /** @class */ (function (_super) {
  106932. __extends(BinaryFileAssetTask, _super);
  106933. /**
  106934. * Creates a new BinaryFileAssetTask object
  106935. * @param name defines the name of the new task
  106936. * @param url defines the location of the file to load
  106937. */
  106938. function BinaryFileAssetTask(
  106939. /**
  106940. * Defines the name of the task
  106941. */
  106942. name,
  106943. /**
  106944. * Defines the location of the file to load
  106945. */
  106946. url) {
  106947. var _this = _super.call(this, name) || this;
  106948. _this.name = name;
  106949. _this.url = url;
  106950. return _this;
  106951. }
  106952. /**
  106953. * Execute the current task
  106954. * @param scene defines the scene where you want your assets to be loaded
  106955. * @param onSuccess is a callback called when the task is successfully executed
  106956. * @param onError is a callback called if an error occurs
  106957. */
  106958. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106959. var _this = this;
  106960. scene._loadFile(this.url, function (data) {
  106961. _this.data = data;
  106962. onSuccess();
  106963. }, undefined, true, true, function (request, exception) {
  106964. if (request) {
  106965. onError(request.status + " " + request.statusText, exception);
  106966. }
  106967. });
  106968. };
  106969. return BinaryFileAssetTask;
  106970. }(AbstractAssetTask));
  106971. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  106972. /**
  106973. * Define a task used by {BABYLON.AssetsManager} to load images
  106974. */
  106975. var ImageAssetTask = /** @class */ (function (_super) {
  106976. __extends(ImageAssetTask, _super);
  106977. /**
  106978. * Creates a new ImageAssetTask
  106979. * @param name defines the name of the task
  106980. * @param url defines the location of the image to load
  106981. */
  106982. function ImageAssetTask(
  106983. /**
  106984. * Defines the name of the task
  106985. */
  106986. name,
  106987. /**
  106988. * Defines the location of the image to load
  106989. */
  106990. url) {
  106991. var _this = _super.call(this, name) || this;
  106992. _this.name = name;
  106993. _this.url = url;
  106994. return _this;
  106995. }
  106996. /**
  106997. * Execute the current task
  106998. * @param scene defines the scene where you want your assets to be loaded
  106999. * @param onSuccess is a callback called when the task is successfully executed
  107000. * @param onError is a callback called if an error occurs
  107001. */
  107002. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107003. var _this = this;
  107004. var img = new Image();
  107005. BABYLON.Tools.SetCorsBehavior(this.url, img);
  107006. img.onload = function () {
  107007. _this.image = img;
  107008. onSuccess();
  107009. };
  107010. img.onerror = function (err) {
  107011. onError("Error loading image", err);
  107012. };
  107013. img.src = this.url;
  107014. };
  107015. return ImageAssetTask;
  107016. }(AbstractAssetTask));
  107017. BABYLON.ImageAssetTask = ImageAssetTask;
  107018. /**
  107019. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  107020. */
  107021. var TextureAssetTask = /** @class */ (function (_super) {
  107022. __extends(TextureAssetTask, _super);
  107023. /**
  107024. * Creates a new TextureAssetTask object
  107025. * @param name defines the name of the task
  107026. * @param url defines the location of the file to load
  107027. * @param noMipmap defines if mipmap should not be generated (default is false)
  107028. * @param invertY defines if texture must be inverted on Y axis (default is false)
  107029. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107030. */
  107031. function TextureAssetTask(
  107032. /**
  107033. * Defines the name of the task
  107034. */
  107035. name,
  107036. /**
  107037. * Defines the location of the file to load
  107038. */
  107039. url,
  107040. /**
  107041. * Defines if mipmap should not be generated (default is false)
  107042. */
  107043. noMipmap,
  107044. /**
  107045. * Defines if texture must be inverted on Y axis (default is false)
  107046. */
  107047. invertY,
  107048. /**
  107049. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107050. */
  107051. samplingMode) {
  107052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107053. var _this = _super.call(this, name) || this;
  107054. _this.name = name;
  107055. _this.url = url;
  107056. _this.noMipmap = noMipmap;
  107057. _this.invertY = invertY;
  107058. _this.samplingMode = samplingMode;
  107059. return _this;
  107060. }
  107061. /**
  107062. * Execute the current task
  107063. * @param scene defines the scene where you want your assets to be loaded
  107064. * @param onSuccess is a callback called when the task is successfully executed
  107065. * @param onError is a callback called if an error occurs
  107066. */
  107067. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107068. var onload = function () {
  107069. onSuccess();
  107070. };
  107071. var onerror = function (message, exception) {
  107072. onError(message, exception);
  107073. };
  107074. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  107075. };
  107076. return TextureAssetTask;
  107077. }(AbstractAssetTask));
  107078. BABYLON.TextureAssetTask = TextureAssetTask;
  107079. /**
  107080. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  107081. */
  107082. var CubeTextureAssetTask = /** @class */ (function (_super) {
  107083. __extends(CubeTextureAssetTask, _super);
  107084. /**
  107085. * Creates a new CubeTextureAssetTask
  107086. * @param name defines the name of the task
  107087. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107088. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107089. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107090. * @param files defines the explicit list of files (undefined by default)
  107091. */
  107092. function CubeTextureAssetTask(
  107093. /**
  107094. * Defines the name of the task
  107095. */
  107096. name,
  107097. /**
  107098. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107099. */
  107100. url,
  107101. /**
  107102. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107103. */
  107104. extensions,
  107105. /**
  107106. * Defines if mipmaps should not be generated (default is false)
  107107. */
  107108. noMipmap,
  107109. /**
  107110. * Defines the explicit list of files (undefined by default)
  107111. */
  107112. files) {
  107113. var _this = _super.call(this, name) || this;
  107114. _this.name = name;
  107115. _this.url = url;
  107116. _this.extensions = extensions;
  107117. _this.noMipmap = noMipmap;
  107118. _this.files = files;
  107119. return _this;
  107120. }
  107121. /**
  107122. * Execute the current task
  107123. * @param scene defines the scene where you want your assets to be loaded
  107124. * @param onSuccess is a callback called when the task is successfully executed
  107125. * @param onError is a callback called if an error occurs
  107126. */
  107127. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107128. var onload = function () {
  107129. onSuccess();
  107130. };
  107131. var onerror = function (message, exception) {
  107132. onError(message, exception);
  107133. };
  107134. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  107135. };
  107136. return CubeTextureAssetTask;
  107137. }(AbstractAssetTask));
  107138. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  107139. /**
  107140. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  107141. */
  107142. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  107143. __extends(HDRCubeTextureAssetTask, _super);
  107144. /**
  107145. * Creates a new HDRCubeTextureAssetTask object
  107146. * @param name defines the name of the task
  107147. * @param url defines the location of the file to load
  107148. * @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.
  107149. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107150. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107151. * @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)
  107152. * @param reserved Internal use only
  107153. */
  107154. function HDRCubeTextureAssetTask(
  107155. /**
  107156. * Defines the name of the task
  107157. */
  107158. name,
  107159. /**
  107160. * Defines the location of the file to load
  107161. */
  107162. url,
  107163. /**
  107164. * Defines the desired size (the more it increases the longer the generation will be)
  107165. */
  107166. size,
  107167. /**
  107168. * Defines if mipmaps should not be generated (default is false)
  107169. */
  107170. noMipmap,
  107171. /**
  107172. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107173. */
  107174. generateHarmonics,
  107175. /**
  107176. * 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)
  107177. */
  107178. gammaSpace,
  107179. /**
  107180. * Internal Use Only
  107181. */
  107182. reserved) {
  107183. if (noMipmap === void 0) { noMipmap = false; }
  107184. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107185. if (gammaSpace === void 0) { gammaSpace = false; }
  107186. if (reserved === void 0) { reserved = false; }
  107187. var _this = _super.call(this, name) || this;
  107188. _this.name = name;
  107189. _this.url = url;
  107190. _this.size = size;
  107191. _this.noMipmap = noMipmap;
  107192. _this.generateHarmonics = generateHarmonics;
  107193. _this.gammaSpace = gammaSpace;
  107194. _this.reserved = reserved;
  107195. return _this;
  107196. }
  107197. /**
  107198. * Execute the current task
  107199. * @param scene defines the scene where you want your assets to be loaded
  107200. * @param onSuccess is a callback called when the task is successfully executed
  107201. * @param onError is a callback called if an error occurs
  107202. */
  107203. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107204. var onload = function () {
  107205. onSuccess();
  107206. };
  107207. var onerror = function (message, exception) {
  107208. onError(message, exception);
  107209. };
  107210. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  107211. };
  107212. return HDRCubeTextureAssetTask;
  107213. }(AbstractAssetTask));
  107214. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  107215. /**
  107216. * This class can be used to easily import assets into a scene
  107217. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  107218. */
  107219. var AssetsManager = /** @class */ (function () {
  107220. /**
  107221. * Creates a new AssetsManager
  107222. * @param scene defines the scene to work on
  107223. */
  107224. function AssetsManager(scene) {
  107225. this._isLoading = false;
  107226. this._tasks = new Array();
  107227. this._waitingTasksCount = 0;
  107228. this._totalTasksCount = 0;
  107229. /**
  107230. * Observable called when all tasks are processed
  107231. */
  107232. this.onTaskSuccessObservable = new BABYLON.Observable();
  107233. /**
  107234. * Observable called when a task had an error
  107235. */
  107236. this.onTaskErrorObservable = new BABYLON.Observable();
  107237. /**
  107238. * Observable called when a task is successful
  107239. */
  107240. this.onTasksDoneObservable = new BABYLON.Observable();
  107241. /**
  107242. * Observable called when a task is done (whatever the result is)
  107243. */
  107244. this.onProgressObservable = new BABYLON.Observable();
  107245. /**
  107246. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  107247. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  107248. */
  107249. this.useDefaultLoadingScreen = true;
  107250. this._scene = scene;
  107251. }
  107252. /**
  107253. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  107254. * @param taskName defines the name of the new task
  107255. * @param meshesNames defines the name of meshes to load
  107256. * @param rootUrl defines the root url to use to locate files
  107257. * @param sceneFilename defines the filename of the scene file
  107258. * @returns a new {BABYLON.MeshAssetTask} object
  107259. */
  107260. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  107261. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  107262. this._tasks.push(task);
  107263. return task;
  107264. };
  107265. /**
  107266. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  107267. * @param taskName defines the name of the new task
  107268. * @param url defines the url of the file to load
  107269. * @returns a new {BABYLON.TextFileAssetTask} object
  107270. */
  107271. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  107272. var task = new TextFileAssetTask(taskName, url);
  107273. this._tasks.push(task);
  107274. return task;
  107275. };
  107276. /**
  107277. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  107278. * @param taskName defines the name of the new task
  107279. * @param url defines the url of the file to load
  107280. * @returns a new {BABYLON.BinaryFileAssetTask} object
  107281. */
  107282. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  107283. var task = new BinaryFileAssetTask(taskName, url);
  107284. this._tasks.push(task);
  107285. return task;
  107286. };
  107287. /**
  107288. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  107289. * @param taskName defines the name of the new task
  107290. * @param url defines the url of the file to load
  107291. * @returns a new {BABYLON.ImageAssetTask} object
  107292. */
  107293. AssetsManager.prototype.addImageTask = function (taskName, url) {
  107294. var task = new ImageAssetTask(taskName, url);
  107295. this._tasks.push(task);
  107296. return task;
  107297. };
  107298. /**
  107299. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  107300. * @param taskName defines the name of the new task
  107301. * @param url defines the url of the file to load
  107302. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107303. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  107304. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  107305. * @returns a new {BABYLON.TextureAssetTask} object
  107306. */
  107307. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  107308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107309. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  107310. this._tasks.push(task);
  107311. return task;
  107312. };
  107313. /**
  107314. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  107315. * @param taskName defines the name of the new task
  107316. * @param url defines the url of the file to load
  107317. * @param extensions defines the extension to use to load the cube map (can be null)
  107318. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107319. * @param files defines the list of files to load (can be null)
  107320. * @returns a new {BABYLON.CubeTextureAssetTask} object
  107321. */
  107322. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  107323. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  107324. this._tasks.push(task);
  107325. return task;
  107326. };
  107327. /**
  107328. *
  107329. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  107330. * @param taskName defines the name of the new task
  107331. * @param url defines the url of the file to load
  107332. * @param size defines the size you want for the cubemap (can be null)
  107333. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107334. * @param generateHarmonics defines if you want to automatically generate (true by default)
  107335. * @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)
  107336. * @param reserved Internal use only
  107337. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  107338. */
  107339. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  107340. if (noMipmap === void 0) { noMipmap = false; }
  107341. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107342. if (gammaSpace === void 0) { gammaSpace = false; }
  107343. if (reserved === void 0) { reserved = false; }
  107344. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  107345. this._tasks.push(task);
  107346. return task;
  107347. };
  107348. /**
  107349. * Remove a task from the assets manager.
  107350. * @param task the task to remove
  107351. */
  107352. AssetsManager.prototype.removeTask = function (task) {
  107353. var index = this._tasks.indexOf(task);
  107354. if (index > -1) {
  107355. this._tasks.splice(index, 1);
  107356. }
  107357. };
  107358. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  107359. this._waitingTasksCount--;
  107360. try {
  107361. if (this.onProgress) {
  107362. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  107363. }
  107364. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  107365. }
  107366. catch (e) {
  107367. BABYLON.Tools.Error("Error running progress callbacks.");
  107368. console.log(e);
  107369. }
  107370. if (this._waitingTasksCount === 0) {
  107371. try {
  107372. if (this.onFinish) {
  107373. this.onFinish(this._tasks);
  107374. }
  107375. // Let's remove successfull tasks
  107376. var currentTasks = this._tasks.slice();
  107377. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  107378. var task = currentTasks_1[_i];
  107379. if (task.taskState === AssetTaskState.DONE) {
  107380. var index = this._tasks.indexOf(task);
  107381. if (index > -1) {
  107382. this._tasks.splice(index, 1);
  107383. }
  107384. }
  107385. }
  107386. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107387. }
  107388. catch (e) {
  107389. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  107390. console.log(e);
  107391. }
  107392. this._isLoading = false;
  107393. this._scene.getEngine().hideLoadingUI();
  107394. }
  107395. };
  107396. AssetsManager.prototype._runTask = function (task) {
  107397. var _this = this;
  107398. var done = function () {
  107399. try {
  107400. if (_this.onTaskSuccess) {
  107401. _this.onTaskSuccess(task);
  107402. }
  107403. _this.onTaskSuccessObservable.notifyObservers(task);
  107404. _this._decreaseWaitingTasksCount(task);
  107405. }
  107406. catch (e) {
  107407. error("Error executing task success callbacks", e);
  107408. }
  107409. };
  107410. var error = function (message, exception) {
  107411. task._setErrorObject(message, exception);
  107412. if (_this.onTaskError) {
  107413. _this.onTaskError(task);
  107414. }
  107415. _this.onTaskErrorObservable.notifyObservers(task);
  107416. _this._decreaseWaitingTasksCount(task);
  107417. };
  107418. task.run(this._scene, done, error);
  107419. };
  107420. /**
  107421. * Reset the {BABYLON.AssetsManager} and remove all tasks
  107422. * @return the current instance of the {BABYLON.AssetsManager}
  107423. */
  107424. AssetsManager.prototype.reset = function () {
  107425. this._isLoading = false;
  107426. this._tasks = new Array();
  107427. return this;
  107428. };
  107429. /**
  107430. * Start the loading process
  107431. * @return the current instance of the {BABYLON.AssetsManager}
  107432. */
  107433. AssetsManager.prototype.load = function () {
  107434. if (this._isLoading) {
  107435. return this;
  107436. }
  107437. this._isLoading = true;
  107438. this._waitingTasksCount = this._tasks.length;
  107439. this._totalTasksCount = this._tasks.length;
  107440. if (this._waitingTasksCount === 0) {
  107441. this._isLoading = false;
  107442. if (this.onFinish) {
  107443. this.onFinish(this._tasks);
  107444. }
  107445. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107446. return this;
  107447. }
  107448. if (this.useDefaultLoadingScreen) {
  107449. this._scene.getEngine().displayLoadingUI();
  107450. }
  107451. for (var index = 0; index < this._tasks.length; index++) {
  107452. var task = this._tasks[index];
  107453. if (task.taskState === AssetTaskState.INIT) {
  107454. this._runTask(task);
  107455. }
  107456. }
  107457. return this;
  107458. };
  107459. return AssetsManager;
  107460. }());
  107461. BABYLON.AssetsManager = AssetsManager;
  107462. })(BABYLON || (BABYLON = {}));
  107463. //# sourceMappingURL=babylon.assetsManager.js.map
  107464. var BABYLON;
  107465. (function (BABYLON) {
  107466. var serializedGeometries = [];
  107467. var serializeGeometry = function (geometry, serializationGeometries) {
  107468. if (serializedGeometries[geometry.id]) {
  107469. return;
  107470. }
  107471. if (geometry.doNotSerialize) {
  107472. return;
  107473. }
  107474. if (geometry instanceof BABYLON.BoxGeometry) {
  107475. serializationGeometries.boxes.push(geometry.serialize());
  107476. }
  107477. else if (geometry instanceof BABYLON.SphereGeometry) {
  107478. serializationGeometries.spheres.push(geometry.serialize());
  107479. }
  107480. else if (geometry instanceof BABYLON.CylinderGeometry) {
  107481. serializationGeometries.cylinders.push(geometry.serialize());
  107482. }
  107483. else if (geometry instanceof BABYLON.TorusGeometry) {
  107484. serializationGeometries.toruses.push(geometry.serialize());
  107485. }
  107486. else if (geometry instanceof BABYLON.GroundGeometry) {
  107487. serializationGeometries.grounds.push(geometry.serialize());
  107488. }
  107489. else if (geometry instanceof BABYLON.Plane) {
  107490. serializationGeometries.planes.push(geometry.serialize());
  107491. }
  107492. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  107493. serializationGeometries.torusKnots.push(geometry.serialize());
  107494. }
  107495. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  107496. throw new Error("Unknown primitive type");
  107497. }
  107498. else {
  107499. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  107500. }
  107501. serializedGeometries[geometry.id] = true;
  107502. };
  107503. var serializeMesh = function (mesh, serializationScene) {
  107504. var serializationObject = {};
  107505. // Geometry
  107506. var geometry = mesh._geometry;
  107507. if (geometry) {
  107508. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  107509. // 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
  107510. serializeGeometry(geometry, serializationScene.geometries);
  107511. }
  107512. }
  107513. // Custom
  107514. if (mesh.serialize) {
  107515. mesh.serialize(serializationObject);
  107516. }
  107517. return serializationObject;
  107518. };
  107519. var finalizeSingleMesh = function (mesh, serializationObject) {
  107520. //only works if the mesh is already loaded
  107521. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107522. //serialize material
  107523. if (mesh.material) {
  107524. if (mesh.material instanceof BABYLON.MultiMaterial) {
  107525. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  107526. serializationObject.materials = serializationObject.materials || [];
  107527. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107528. serializationObject.multiMaterials.push(mesh.material.serialize());
  107529. var _loop_1 = function (submaterial) {
  107530. if (submaterial) {
  107531. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  107532. serializationObject.materials.push(submaterial.serialize());
  107533. }
  107534. }
  107535. };
  107536. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  107537. var submaterial = _a[_i];
  107538. _loop_1(submaterial);
  107539. }
  107540. }
  107541. }
  107542. else {
  107543. serializationObject.materials = serializationObject.materials || [];
  107544. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107545. serializationObject.materials.push(mesh.material.serialize());
  107546. }
  107547. }
  107548. }
  107549. //serialize geometry
  107550. var geometry = mesh._geometry;
  107551. if (geometry) {
  107552. if (!serializationObject.geometries) {
  107553. serializationObject.geometries = {};
  107554. serializationObject.geometries.boxes = [];
  107555. serializationObject.geometries.spheres = [];
  107556. serializationObject.geometries.cylinders = [];
  107557. serializationObject.geometries.toruses = [];
  107558. serializationObject.geometries.grounds = [];
  107559. serializationObject.geometries.planes = [];
  107560. serializationObject.geometries.torusKnots = [];
  107561. serializationObject.geometries.vertexData = [];
  107562. }
  107563. serializeGeometry(geometry, serializationObject.geometries);
  107564. }
  107565. // Skeletons
  107566. if (mesh.skeleton) {
  107567. serializationObject.skeletons = serializationObject.skeletons || [];
  107568. serializationObject.skeletons.push(mesh.skeleton.serialize());
  107569. }
  107570. //serialize the actual mesh
  107571. serializationObject.meshes = serializationObject.meshes || [];
  107572. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107573. }
  107574. };
  107575. var SceneSerializer = /** @class */ (function () {
  107576. function SceneSerializer() {
  107577. }
  107578. SceneSerializer.ClearCache = function () {
  107579. serializedGeometries = [];
  107580. };
  107581. SceneSerializer.Serialize = function (scene) {
  107582. var serializationObject = {};
  107583. SceneSerializer.ClearCache();
  107584. // Scene
  107585. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  107586. serializationObject.autoClear = scene.autoClear;
  107587. serializationObject.clearColor = scene.clearColor.asArray();
  107588. serializationObject.ambientColor = scene.ambientColor.asArray();
  107589. serializationObject.gravity = scene.gravity.asArray();
  107590. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  107591. serializationObject.workerCollisions = scene.workerCollisions;
  107592. // Fog
  107593. if (scene.fogMode && scene.fogMode !== 0) {
  107594. serializationObject.fogMode = scene.fogMode;
  107595. serializationObject.fogColor = scene.fogColor.asArray();
  107596. serializationObject.fogStart = scene.fogStart;
  107597. serializationObject.fogEnd = scene.fogEnd;
  107598. serializationObject.fogDensity = scene.fogDensity;
  107599. }
  107600. //Physics
  107601. if (scene.isPhysicsEnabled()) {
  107602. var physicEngine = scene.getPhysicsEngine();
  107603. if (physicEngine) {
  107604. serializationObject.physicsEnabled = true;
  107605. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  107606. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  107607. }
  107608. }
  107609. // Metadata
  107610. if (scene.metadata) {
  107611. serializationObject.metadata = scene.metadata;
  107612. }
  107613. // Morph targets
  107614. serializationObject.morphTargetManagers = [];
  107615. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  107616. var abstractMesh = _a[_i];
  107617. var manager = abstractMesh.morphTargetManager;
  107618. if (manager) {
  107619. serializationObject.morphTargetManagers.push(manager.serialize());
  107620. }
  107621. }
  107622. // Lights
  107623. serializationObject.lights = [];
  107624. var index;
  107625. var light;
  107626. for (index = 0; index < scene.lights.length; index++) {
  107627. light = scene.lights[index];
  107628. if (!light.doNotSerialize) {
  107629. serializationObject.lights.push(light.serialize());
  107630. }
  107631. }
  107632. // Cameras
  107633. serializationObject.cameras = [];
  107634. for (index = 0; index < scene.cameras.length; index++) {
  107635. var camera = scene.cameras[index];
  107636. if (!camera.doNotSerialize) {
  107637. serializationObject.cameras.push(camera.serialize());
  107638. }
  107639. }
  107640. if (scene.activeCamera) {
  107641. serializationObject.activeCameraID = scene.activeCamera.id;
  107642. }
  107643. // Animations
  107644. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  107645. // Materials
  107646. serializationObject.materials = [];
  107647. serializationObject.multiMaterials = [];
  107648. var material;
  107649. for (index = 0; index < scene.materials.length; index++) {
  107650. material = scene.materials[index];
  107651. if (!material.doNotSerialize) {
  107652. serializationObject.materials.push(material.serialize());
  107653. }
  107654. }
  107655. // MultiMaterials
  107656. serializationObject.multiMaterials = [];
  107657. for (index = 0; index < scene.multiMaterials.length; index++) {
  107658. var multiMaterial = scene.multiMaterials[index];
  107659. serializationObject.multiMaterials.push(multiMaterial.serialize());
  107660. }
  107661. // Environment texture
  107662. if (scene.environmentTexture) {
  107663. serializationObject.environmentTexture = scene.environmentTexture.name;
  107664. }
  107665. // Skeletons
  107666. serializationObject.skeletons = [];
  107667. for (index = 0; index < scene.skeletons.length; index++) {
  107668. var skeleton = scene.skeletons[index];
  107669. if (!skeleton.doNotSerialize) {
  107670. serializationObject.skeletons.push(skeleton.serialize());
  107671. }
  107672. }
  107673. // Transform nodes
  107674. serializationObject.transformNodes = [];
  107675. for (index = 0; index < scene.transformNodes.length; index++) {
  107676. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  107677. }
  107678. // Geometries
  107679. serializationObject.geometries = {};
  107680. serializationObject.geometries.boxes = [];
  107681. serializationObject.geometries.spheres = [];
  107682. serializationObject.geometries.cylinders = [];
  107683. serializationObject.geometries.toruses = [];
  107684. serializationObject.geometries.grounds = [];
  107685. serializationObject.geometries.planes = [];
  107686. serializationObject.geometries.torusKnots = [];
  107687. serializationObject.geometries.vertexData = [];
  107688. serializedGeometries = [];
  107689. var geometries = scene.getGeometries();
  107690. for (index = 0; index < geometries.length; index++) {
  107691. var geometry = geometries[index];
  107692. if (geometry.isReady()) {
  107693. serializeGeometry(geometry, serializationObject.geometries);
  107694. }
  107695. }
  107696. // Meshes
  107697. serializationObject.meshes = [];
  107698. for (index = 0; index < scene.meshes.length; index++) {
  107699. var abstractMesh = scene.meshes[index];
  107700. if (abstractMesh instanceof BABYLON.Mesh) {
  107701. var mesh = abstractMesh;
  107702. if (!mesh.doNotSerialize) {
  107703. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107704. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107705. }
  107706. }
  107707. }
  107708. }
  107709. // Particles Systems
  107710. serializationObject.particleSystems = [];
  107711. for (index = 0; index < scene.particleSystems.length; index++) {
  107712. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  107713. }
  107714. // Action Manager
  107715. if (scene.actionManager) {
  107716. serializationObject.actions = scene.actionManager.serialize("scene");
  107717. }
  107718. // Components
  107719. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  107720. var component = _c[_b];
  107721. component.serialize(serializationObject);
  107722. }
  107723. return serializationObject;
  107724. };
  107725. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  107726. if (withParents === void 0) { withParents = false; }
  107727. if (withChildren === void 0) { withChildren = false; }
  107728. var serializationObject = {};
  107729. SceneSerializer.ClearCache();
  107730. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  107731. if (withParents || withChildren) {
  107732. //deliberate for loop! not for each, appended should be processed as well.
  107733. for (var i = 0; i < toSerialize.length; ++i) {
  107734. if (withChildren) {
  107735. toSerialize[i].getDescendants().forEach(function (node) {
  107736. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  107737. toSerialize.push(node);
  107738. }
  107739. });
  107740. }
  107741. //make sure the array doesn't contain the object already
  107742. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  107743. toSerialize.push(toSerialize[i].parent);
  107744. }
  107745. }
  107746. }
  107747. toSerialize.forEach(function (mesh) {
  107748. finalizeSingleMesh(mesh, serializationObject);
  107749. });
  107750. return serializationObject;
  107751. };
  107752. return SceneSerializer;
  107753. }());
  107754. BABYLON.SceneSerializer = SceneSerializer;
  107755. })(BABYLON || (BABYLON = {}));
  107756. //# sourceMappingURL=babylon.sceneSerializer.js.map
  107757. var BABYLON;
  107758. (function (BABYLON) {
  107759. /**
  107760. * Class used to generate realtime reflection / refraction cube textures
  107761. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  107762. */
  107763. var ReflectionProbe = /** @class */ (function () {
  107764. /**
  107765. * Creates a new reflection probe
  107766. * @param name defines the name of the probe
  107767. * @param size defines the texture resolution (for each face)
  107768. * @param scene defines the hosting scene
  107769. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  107770. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  107771. */
  107772. function ReflectionProbe(
  107773. /** defines the name of the probe */
  107774. name, size, scene, generateMipMaps, useFloat) {
  107775. if (generateMipMaps === void 0) { generateMipMaps = true; }
  107776. if (useFloat === void 0) { useFloat = false; }
  107777. var _this = this;
  107778. this.name = name;
  107779. this._viewMatrix = BABYLON.Matrix.Identity();
  107780. this._target = BABYLON.Vector3.Zero();
  107781. this._add = BABYLON.Vector3.Zero();
  107782. this._invertYAxis = false;
  107783. /** Gets or sets probe position (center of the cube map) */
  107784. this.position = BABYLON.Vector3.Zero();
  107785. this._scene = scene;
  107786. // Create the scene field if not exist.
  107787. if (!this._scene.reflectionProbes) {
  107788. this._scene.reflectionProbes = new Array();
  107789. }
  107790. this._scene.reflectionProbes.push(this);
  107791. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  107792. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  107793. switch (faceIndex) {
  107794. case 0:
  107795. _this._add.copyFromFloats(1, 0, 0);
  107796. break;
  107797. case 1:
  107798. _this._add.copyFromFloats(-1, 0, 0);
  107799. break;
  107800. case 2:
  107801. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  107802. break;
  107803. case 3:
  107804. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  107805. break;
  107806. case 4:
  107807. _this._add.copyFromFloats(0, 0, 1);
  107808. break;
  107809. case 5:
  107810. _this._add.copyFromFloats(0, 0, -1);
  107811. break;
  107812. }
  107813. if (_this._attachedMesh) {
  107814. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  107815. }
  107816. _this.position.addToRef(_this._add, _this._target);
  107817. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  107818. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  107819. scene._forcedViewPosition = _this.position;
  107820. });
  107821. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  107822. scene._forcedViewPosition = null;
  107823. scene.updateTransformMatrix(true);
  107824. });
  107825. if (scene.activeCamera) {
  107826. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  107827. }
  107828. }
  107829. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  107830. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  107831. get: function () {
  107832. return this._renderTargetTexture.samples;
  107833. },
  107834. set: function (value) {
  107835. this._renderTargetTexture.samples = value;
  107836. },
  107837. enumerable: true,
  107838. configurable: true
  107839. });
  107840. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  107841. /** Gets or sets the refresh rate to use (on every frame by default) */
  107842. get: function () {
  107843. return this._renderTargetTexture.refreshRate;
  107844. },
  107845. set: function (value) {
  107846. this._renderTargetTexture.refreshRate = value;
  107847. },
  107848. enumerable: true,
  107849. configurable: true
  107850. });
  107851. /**
  107852. * Gets the hosting scene
  107853. * @returns a Scene
  107854. */
  107855. ReflectionProbe.prototype.getScene = function () {
  107856. return this._scene;
  107857. };
  107858. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  107859. /** Gets the internal CubeTexture used to render to */
  107860. get: function () {
  107861. return this._renderTargetTexture;
  107862. },
  107863. enumerable: true,
  107864. configurable: true
  107865. });
  107866. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  107867. /** Gets the list of meshes to render */
  107868. get: function () {
  107869. return this._renderTargetTexture.renderList;
  107870. },
  107871. enumerable: true,
  107872. configurable: true
  107873. });
  107874. /**
  107875. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  107876. * @param mesh defines the mesh to attach to
  107877. */
  107878. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  107879. this._attachedMesh = mesh;
  107880. };
  107881. /**
  107882. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  107883. * @param renderingGroupId The rendering group id corresponding to its index
  107884. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  107885. */
  107886. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  107887. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  107888. };
  107889. /**
  107890. * Clean all associated resources
  107891. */
  107892. ReflectionProbe.prototype.dispose = function () {
  107893. var index = this._scene.reflectionProbes.indexOf(this);
  107894. if (index !== -1) {
  107895. // Remove from the scene if found
  107896. this._scene.reflectionProbes.splice(index, 1);
  107897. }
  107898. if (this._renderTargetTexture) {
  107899. this._renderTargetTexture.dispose();
  107900. this._renderTargetTexture = null;
  107901. }
  107902. };
  107903. return ReflectionProbe;
  107904. }());
  107905. BABYLON.ReflectionProbe = ReflectionProbe;
  107906. })(BABYLON || (BABYLON = {}));
  107907. //# sourceMappingURL=babylon.reflectionProbe.js.map
  107908. var BABYLON;
  107909. (function (BABYLON) {
  107910. /**
  107911. * Defines the layer scene component responsible to manage any layers
  107912. * in a given scene.
  107913. */
  107914. var LayerSceneComponent = /** @class */ (function () {
  107915. /**
  107916. * Creates a new instance of the component for the given scene
  107917. * @param scene Defines the scene to register the component in
  107918. */
  107919. function LayerSceneComponent(scene) {
  107920. /**
  107921. * The component name helpfull to identify the component in the list of scene components.
  107922. */
  107923. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  107924. this.scene = scene;
  107925. this._engine = scene.getEngine();
  107926. scene.layers = new Array();
  107927. }
  107928. /**
  107929. * Registers the component in a given scene
  107930. */
  107931. LayerSceneComponent.prototype.register = function () {
  107932. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  107933. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  107934. };
  107935. /**
  107936. * Rebuilds the elements related to this component in case of
  107937. * context lost for instance.
  107938. */
  107939. LayerSceneComponent.prototype.rebuild = function () {
  107940. var layers = this.scene.layers;
  107941. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107942. var layer = layers_1[_i];
  107943. layer._rebuild();
  107944. }
  107945. };
  107946. /**
  107947. * Disposes the component and the associated ressources.
  107948. */
  107949. LayerSceneComponent.prototype.dispose = function () {
  107950. var layers = this.scene.layers;
  107951. while (layers.length) {
  107952. layers[0].dispose();
  107953. }
  107954. };
  107955. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  107956. var layers = this.scene.layers;
  107957. if (layers.length) {
  107958. this._engine.setDepthBuffer(false);
  107959. var cameraLayerMask = camera.layerMask;
  107960. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107961. var layer = layers_2[_i];
  107962. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  107963. layer.render();
  107964. }
  107965. }
  107966. this._engine.setDepthBuffer(true);
  107967. }
  107968. };
  107969. LayerSceneComponent.prototype._drawBackground = function (camera) {
  107970. this._draw(camera, true);
  107971. };
  107972. LayerSceneComponent.prototype._drawForeground = function (camera) {
  107973. this._draw(camera, false);
  107974. };
  107975. return LayerSceneComponent;
  107976. }());
  107977. BABYLON.LayerSceneComponent = LayerSceneComponent;
  107978. })(BABYLON || (BABYLON = {}));
  107979. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  107980. var BABYLON;
  107981. (function (BABYLON) {
  107982. /**
  107983. * This represents a full screen 2d layer.
  107984. * This can be usefull to display a picture in the background of your scene for instance.
  107985. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107986. */
  107987. var Layer = /** @class */ (function () {
  107988. /**
  107989. * Instantiates a new layer.
  107990. * This represents a full screen 2d layer.
  107991. * This can be usefull to display a picture in the background of your scene for instance.
  107992. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107993. * @param name Define the name of the layer in the scene
  107994. * @param imgUrl Define the url of the texture to display in the layer
  107995. * @param scene Define the scene the layer belongs to
  107996. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  107997. * @param color Defines a color for the layer
  107998. */
  107999. function Layer(
  108000. /**
  108001. * Define the name of the layer.
  108002. */
  108003. name, imgUrl, scene, isBackground, color) {
  108004. this.name = name;
  108005. /**
  108006. * Define the scale of the layer in order to zoom in out of the texture.
  108007. */
  108008. this.scale = new BABYLON.Vector2(1, 1);
  108009. /**
  108010. * Define an offset for the layer in order to shift the texture.
  108011. */
  108012. this.offset = new BABYLON.Vector2(0, 0);
  108013. /**
  108014. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  108015. */
  108016. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  108017. /**
  108018. * Define a mask to restrict the layer to only some of the scene cameras.
  108019. */
  108020. this.layerMask = 0x0FFFFFFF;
  108021. this._vertexBuffers = {};
  108022. /**
  108023. * An event triggered when the layer is disposed.
  108024. */
  108025. this.onDisposeObservable = new BABYLON.Observable();
  108026. /**
  108027. * An event triggered before rendering the scene
  108028. */
  108029. this.onBeforeRenderObservable = new BABYLON.Observable();
  108030. /**
  108031. * An event triggered after rendering the scene
  108032. */
  108033. this.onAfterRenderObservable = new BABYLON.Observable();
  108034. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  108035. this.isBackground = isBackground === undefined ? true : isBackground;
  108036. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  108037. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  108038. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  108039. if (!layerComponent) {
  108040. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  108041. this._scene._addComponent(layerComponent);
  108042. }
  108043. this._scene.layers.push(this);
  108044. var engine = this._scene.getEngine();
  108045. // VBO
  108046. var vertices = [];
  108047. vertices.push(1, 1);
  108048. vertices.push(-1, 1);
  108049. vertices.push(-1, -1);
  108050. vertices.push(1, -1);
  108051. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108052. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108053. this._createIndexBuffer();
  108054. // Effects
  108055. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  108056. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  108057. }
  108058. Object.defineProperty(Layer.prototype, "onDispose", {
  108059. /**
  108060. * Back compatibility with callback before the onDisposeObservable existed.
  108061. * The set callback will be triggered when the layer has been disposed.
  108062. */
  108063. set: function (callback) {
  108064. if (this._onDisposeObserver) {
  108065. this.onDisposeObservable.remove(this._onDisposeObserver);
  108066. }
  108067. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  108068. },
  108069. enumerable: true,
  108070. configurable: true
  108071. });
  108072. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  108073. /**
  108074. * Back compatibility with callback before the onBeforeRenderObservable existed.
  108075. * The set callback will be triggered just before rendering the layer.
  108076. */
  108077. set: function (callback) {
  108078. if (this._onBeforeRenderObserver) {
  108079. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  108080. }
  108081. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  108082. },
  108083. enumerable: true,
  108084. configurable: true
  108085. });
  108086. Object.defineProperty(Layer.prototype, "onAfterRender", {
  108087. /**
  108088. * Back compatibility with callback before the onAfterRenderObservable existed.
  108089. * The set callback will be triggered just after rendering the layer.
  108090. */
  108091. set: function (callback) {
  108092. if (this._onAfterRenderObserver) {
  108093. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  108094. }
  108095. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  108096. },
  108097. enumerable: true,
  108098. configurable: true
  108099. });
  108100. Layer.prototype._createIndexBuffer = function () {
  108101. var engine = this._scene.getEngine();
  108102. // Indices
  108103. var indices = [];
  108104. indices.push(0);
  108105. indices.push(1);
  108106. indices.push(2);
  108107. indices.push(0);
  108108. indices.push(2);
  108109. indices.push(3);
  108110. this._indexBuffer = engine.createIndexBuffer(indices);
  108111. };
  108112. /** @hidden */
  108113. Layer.prototype._rebuild = function () {
  108114. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108115. if (vb) {
  108116. vb._rebuild();
  108117. }
  108118. this._createIndexBuffer();
  108119. };
  108120. /**
  108121. * Renders the layer in the scene.
  108122. */
  108123. Layer.prototype.render = function () {
  108124. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  108125. // Check
  108126. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  108127. return;
  108128. var engine = this._scene.getEngine();
  108129. this.onBeforeRenderObservable.notifyObservers(this);
  108130. // Render
  108131. engine.enableEffect(currentEffect);
  108132. engine.setState(false);
  108133. // Texture
  108134. currentEffect.setTexture("textureSampler", this.texture);
  108135. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  108136. // Color
  108137. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  108138. // Scale / offset
  108139. currentEffect.setVector2("offset", this.offset);
  108140. currentEffect.setVector2("scale", this.scale);
  108141. // VBOs
  108142. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  108143. // Draw order
  108144. if (!this.alphaTest) {
  108145. engine.setAlphaMode(this.alphaBlendingMode);
  108146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108147. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108148. }
  108149. else {
  108150. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108151. }
  108152. this.onAfterRenderObservable.notifyObservers(this);
  108153. };
  108154. /**
  108155. * Disposes and releases the associated ressources.
  108156. */
  108157. Layer.prototype.dispose = function () {
  108158. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108159. if (vertexBuffer) {
  108160. vertexBuffer.dispose();
  108161. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  108162. }
  108163. if (this._indexBuffer) {
  108164. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  108165. this._indexBuffer = null;
  108166. }
  108167. if (this.texture) {
  108168. this.texture.dispose();
  108169. this.texture = null;
  108170. }
  108171. // Remove from scene
  108172. var index = this._scene.layers.indexOf(this);
  108173. this._scene.layers.splice(index, 1);
  108174. // Callback
  108175. this.onDisposeObservable.notifyObservers(this);
  108176. this.onDisposeObservable.clear();
  108177. this.onAfterRenderObservable.clear();
  108178. this.onBeforeRenderObservable.clear();
  108179. };
  108180. return Layer;
  108181. }());
  108182. BABYLON.Layer = Layer;
  108183. })(BABYLON || (BABYLON = {}));
  108184. //# sourceMappingURL=babylon.layer.js.map
  108185. var BABYLON;
  108186. (function (BABYLON) {
  108187. var TextureTools = /** @class */ (function () {
  108188. function TextureTools() {
  108189. }
  108190. /**
  108191. * Uses the GPU to create a copy texture rescaled at a given size
  108192. * @param texture Texture to copy from
  108193. * @param width Desired width
  108194. * @param height Desired height
  108195. * @return Generated texture
  108196. */
  108197. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  108198. if (useBilinearMode === void 0) { useBilinearMode = true; }
  108199. var scene = texture.getScene();
  108200. var engine = scene.getEngine();
  108201. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  108202. rtt.wrapU = texture.wrapU;
  108203. rtt.wrapV = texture.wrapV;
  108204. rtt.uOffset = texture.uOffset;
  108205. rtt.vOffset = texture.vOffset;
  108206. rtt.uScale = texture.uScale;
  108207. rtt.vScale = texture.vScale;
  108208. rtt.uAng = texture.uAng;
  108209. rtt.vAng = texture.vAng;
  108210. rtt.wAng = texture.wAng;
  108211. rtt.coordinatesIndex = texture.coordinatesIndex;
  108212. rtt.level = texture.level;
  108213. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  108214. rtt._texture.isReady = false;
  108215. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108216. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108217. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108218. passPostProcess.getEffect().executeWhenCompiled(function () {
  108219. passPostProcess.onApply = function (effect) {
  108220. effect.setTexture("textureSampler", texture);
  108221. };
  108222. var internalTexture = rtt.getInternalTexture();
  108223. if (internalTexture) {
  108224. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  108225. engine.unBindFramebuffer(internalTexture);
  108226. rtt.disposeFramebufferObjects();
  108227. passPostProcess.dispose();
  108228. internalTexture.isReady = true;
  108229. }
  108230. });
  108231. return rtt;
  108232. };
  108233. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  108234. if (!scene._environmentBRDFTexture) {
  108235. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108236. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108237. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108238. scene._environmentBRDFTexture = texture;
  108239. }
  108240. return scene._environmentBRDFTexture;
  108241. };
  108242. 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=";
  108243. return TextureTools;
  108244. }());
  108245. BABYLON.TextureTools = TextureTools;
  108246. })(BABYLON || (BABYLON = {}));
  108247. //# sourceMappingURL=babylon.textureTools.js.map
  108248. var BABYLON;
  108249. (function (BABYLON) {
  108250. /**
  108251. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  108252. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  108253. */
  108254. var FramingBehavior = /** @class */ (function () {
  108255. function FramingBehavior() {
  108256. this._mode = FramingBehavior.FitFrustumSidesMode;
  108257. this._radiusScale = 1.0;
  108258. this._positionScale = 0.5;
  108259. this._defaultElevation = 0.3;
  108260. this._elevationReturnTime = 1500;
  108261. this._elevationReturnWaitTime = 1000;
  108262. this._zoomStopsAnimation = false;
  108263. this._framingTime = 1500;
  108264. /**
  108265. * Define if the behavior should automatically change the configured
  108266. * camera limits and sensibilities.
  108267. */
  108268. this.autoCorrectCameraLimitsAndSensibility = true;
  108269. this._isPointerDown = false;
  108270. this._lastInteractionTime = -Infinity;
  108271. // Framing control
  108272. this._animatables = new Array();
  108273. this._betaIsAnimating = false;
  108274. }
  108275. Object.defineProperty(FramingBehavior.prototype, "name", {
  108276. /**
  108277. * Gets the name of the behavior.
  108278. */
  108279. get: function () {
  108280. return "Framing";
  108281. },
  108282. enumerable: true,
  108283. configurable: true
  108284. });
  108285. Object.defineProperty(FramingBehavior.prototype, "mode", {
  108286. /**
  108287. * Gets current mode used by the behavior.
  108288. */
  108289. get: function () {
  108290. return this._mode;
  108291. },
  108292. /**
  108293. * Sets the current mode used by the behavior
  108294. */
  108295. set: function (mode) {
  108296. this._mode = mode;
  108297. },
  108298. enumerable: true,
  108299. configurable: true
  108300. });
  108301. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  108302. /**
  108303. * Gets the scale applied to the radius
  108304. */
  108305. get: function () {
  108306. return this._radiusScale;
  108307. },
  108308. /**
  108309. * Sets the scale applied to the radius (1 by default)
  108310. */
  108311. set: function (radius) {
  108312. this._radiusScale = radius;
  108313. },
  108314. enumerable: true,
  108315. configurable: true
  108316. });
  108317. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  108318. /**
  108319. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108320. */
  108321. get: function () {
  108322. return this._positionScale;
  108323. },
  108324. /**
  108325. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108326. */
  108327. set: function (scale) {
  108328. this._positionScale = scale;
  108329. },
  108330. enumerable: true,
  108331. configurable: true
  108332. });
  108333. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  108334. /**
  108335. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108336. * behaviour is triggered, in radians.
  108337. */
  108338. get: function () {
  108339. return this._defaultElevation;
  108340. },
  108341. /**
  108342. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108343. * behaviour is triggered, in radians.
  108344. */
  108345. set: function (elevation) {
  108346. this._defaultElevation = elevation;
  108347. },
  108348. enumerable: true,
  108349. configurable: true
  108350. });
  108351. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  108352. /**
  108353. * Gets the time (in milliseconds) taken to return to the default beta position.
  108354. * Negative value indicates camera should not return to default.
  108355. */
  108356. get: function () {
  108357. return this._elevationReturnTime;
  108358. },
  108359. /**
  108360. * Sets the time (in milliseconds) taken to return to the default beta position.
  108361. * Negative value indicates camera should not return to default.
  108362. */
  108363. set: function (speed) {
  108364. this._elevationReturnTime = speed;
  108365. },
  108366. enumerable: true,
  108367. configurable: true
  108368. });
  108369. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  108370. /**
  108371. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108372. */
  108373. get: function () {
  108374. return this._elevationReturnWaitTime;
  108375. },
  108376. /**
  108377. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108378. */
  108379. set: function (time) {
  108380. this._elevationReturnWaitTime = time;
  108381. },
  108382. enumerable: true,
  108383. configurable: true
  108384. });
  108385. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  108386. /**
  108387. * Gets the flag that indicates if user zooming should stop animation.
  108388. */
  108389. get: function () {
  108390. return this._zoomStopsAnimation;
  108391. },
  108392. /**
  108393. * Sets the flag that indicates if user zooming should stop animation.
  108394. */
  108395. set: function (flag) {
  108396. this._zoomStopsAnimation = flag;
  108397. },
  108398. enumerable: true,
  108399. configurable: true
  108400. });
  108401. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  108402. /**
  108403. * Gets the transition time when framing the mesh, in milliseconds
  108404. */
  108405. get: function () {
  108406. return this._framingTime;
  108407. },
  108408. /**
  108409. * Sets the transition time when framing the mesh, in milliseconds
  108410. */
  108411. set: function (time) {
  108412. this._framingTime = time;
  108413. },
  108414. enumerable: true,
  108415. configurable: true
  108416. });
  108417. /**
  108418. * Initializes the behavior.
  108419. */
  108420. FramingBehavior.prototype.init = function () {
  108421. // Do notihng
  108422. };
  108423. /**
  108424. * Attaches the behavior to its arc rotate camera.
  108425. * @param camera Defines the camera to attach the behavior to
  108426. */
  108427. FramingBehavior.prototype.attach = function (camera) {
  108428. var _this = this;
  108429. this._attachedCamera = camera;
  108430. var scene = this._attachedCamera.getScene();
  108431. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  108432. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  108433. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  108434. _this._isPointerDown = true;
  108435. return;
  108436. }
  108437. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  108438. _this._isPointerDown = false;
  108439. }
  108440. });
  108441. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108442. if (mesh) {
  108443. _this.zoomOnMesh(mesh);
  108444. }
  108445. });
  108446. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108447. // Stop the animation if there is user interaction and the animation should stop for this interaction
  108448. _this._applyUserInteraction();
  108449. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  108450. // back to the default position after a given timeout
  108451. _this._maintainCameraAboveGround();
  108452. });
  108453. };
  108454. /**
  108455. * Detaches the behavior from its current arc rotate camera.
  108456. */
  108457. FramingBehavior.prototype.detach = function () {
  108458. if (!this._attachedCamera) {
  108459. return;
  108460. }
  108461. var scene = this._attachedCamera.getScene();
  108462. if (this._onPrePointerObservableObserver) {
  108463. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  108464. }
  108465. if (this._onAfterCheckInputsObserver) {
  108466. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108467. }
  108468. if (this._onMeshTargetChangedObserver) {
  108469. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108470. }
  108471. this._attachedCamera = null;
  108472. };
  108473. /**
  108474. * Targets the given mesh and updates zoom level accordingly.
  108475. * @param mesh The mesh to target.
  108476. * @param radius Optional. If a cached radius position already exists, overrides default.
  108477. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108478. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108479. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108480. */
  108481. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108482. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108483. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108484. mesh.computeWorldMatrix(true);
  108485. var boundingBox = mesh.getBoundingInfo().boundingBox;
  108486. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  108487. };
  108488. /**
  108489. * Targets the given mesh with its children and updates zoom level accordingly.
  108490. * @param mesh The mesh to target.
  108491. * @param radius Optional. If a cached radius position already exists, overrides default.
  108492. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108493. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108494. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108495. */
  108496. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108497. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108498. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108499. mesh.computeWorldMatrix(true);
  108500. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  108501. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  108502. };
  108503. /**
  108504. * Targets the given meshes with their children and updates zoom level accordingly.
  108505. * @param meshes The mesh to target.
  108506. * @param radius Optional. If a cached radius position already exists, overrides default.
  108507. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108508. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108509. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108510. */
  108511. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  108512. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108513. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108514. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  108515. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  108516. for (var i = 0; i < meshes.length; i++) {
  108517. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  108518. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  108519. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  108520. }
  108521. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  108522. };
  108523. /**
  108524. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  108525. * @param minimumWorld Determines the smaller position of the bounding box extend
  108526. * @param maximumWorld Determines the bigger position of the bounding box extend
  108527. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108528. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108529. */
  108530. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  108531. var _this = this;
  108532. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108533. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108534. var zoomTarget;
  108535. if (!this._attachedCamera) {
  108536. return;
  108537. }
  108538. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  108539. var bottom = minimumWorld.y;
  108540. var top = maximumWorld.y;
  108541. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  108542. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  108543. if (focusOnOriginXZ) {
  108544. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  108545. }
  108546. else {
  108547. var centerWorld = minimumWorld.add(radiusWorld);
  108548. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  108549. }
  108550. if (!this._vectorTransition) {
  108551. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  108552. }
  108553. this._betaIsAnimating = true;
  108554. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  108555. if (animatable) {
  108556. this._animatables.push(animatable);
  108557. }
  108558. // sets the radius and lower radius bounds
  108559. // Small delta ensures camera is not always at lower zoom limit.
  108560. var radius = 0;
  108561. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  108562. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108563. if (this.autoCorrectCameraLimitsAndSensibility) {
  108564. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  108565. }
  108566. radius = position;
  108567. }
  108568. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108569. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108570. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  108571. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  108572. }
  108573. }
  108574. // Set sensibilities
  108575. if (this.autoCorrectCameraLimitsAndSensibility) {
  108576. var extend = maximumWorld.subtract(minimumWorld).length();
  108577. this._attachedCamera.panningSensibility = 5000 / extend;
  108578. this._attachedCamera.wheelPrecision = 100 / radius;
  108579. }
  108580. // transition to new radius
  108581. if (!this._radiusTransition) {
  108582. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108583. }
  108584. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  108585. _this.stopAllAnimations();
  108586. if (onAnimationEnd) {
  108587. onAnimationEnd();
  108588. }
  108589. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  108590. _this._attachedCamera.storeState();
  108591. }
  108592. });
  108593. if (animatable) {
  108594. this._animatables.push(animatable);
  108595. }
  108596. };
  108597. /**
  108598. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  108599. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  108600. * frustum width.
  108601. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  108602. * to fully enclose the mesh in the viewing frustum.
  108603. */
  108604. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  108605. var size = maximumWorld.subtract(minimumWorld);
  108606. var boxVectorGlobalDiagonal = size.length();
  108607. var frustumSlope = this._getFrustumSlope();
  108608. // Formula for setting distance
  108609. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  108610. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  108611. // Horizon distance
  108612. var radius = radiusWithoutFraming * this._radiusScale;
  108613. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  108614. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  108615. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  108616. var camera = this._attachedCamera;
  108617. if (!camera) {
  108618. return 0;
  108619. }
  108620. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108621. // Don't exceed the requested limit
  108622. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  108623. }
  108624. // Don't exceed the upper radius limit
  108625. if (camera.upperRadiusLimit) {
  108626. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  108627. }
  108628. return distance;
  108629. };
  108630. /**
  108631. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  108632. * is automatically returned to its default position (expected to be above ground plane).
  108633. */
  108634. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  108635. var _this = this;
  108636. if (this._elevationReturnTime < 0) {
  108637. return;
  108638. }
  108639. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  108640. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  108641. var limitBeta = Math.PI * 0.5;
  108642. // Bring the camera back up if below the ground plane
  108643. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  108644. this._betaIsAnimating = true;
  108645. //Transition to new position
  108646. this.stopAllAnimations();
  108647. if (!this._betaTransition) {
  108648. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108649. }
  108650. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  108651. _this._clearAnimationLocks();
  108652. _this.stopAllAnimations();
  108653. });
  108654. if (animatabe) {
  108655. this._animatables.push(animatabe);
  108656. }
  108657. }
  108658. };
  108659. /**
  108660. * Returns the frustum slope based on the canvas ratio and camera FOV
  108661. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  108662. */
  108663. FramingBehavior.prototype._getFrustumSlope = function () {
  108664. // Calculate the viewport ratio
  108665. // Aspect Ratio is Height/Width.
  108666. var camera = this._attachedCamera;
  108667. if (!camera) {
  108668. return BABYLON.Vector2.Zero();
  108669. }
  108670. var engine = camera.getScene().getEngine();
  108671. var aspectRatio = engine.getAspectRatio(camera);
  108672. // Camera FOV is the vertical field of view (top-bottom) in radians.
  108673. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  108674. var frustumSlopeY = Math.tan(camera.fov / 2);
  108675. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  108676. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  108677. // along the forward vector.
  108678. var frustumSlopeX = frustumSlopeY * aspectRatio;
  108679. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  108680. };
  108681. /**
  108682. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  108683. */
  108684. FramingBehavior.prototype._clearAnimationLocks = function () {
  108685. this._betaIsAnimating = false;
  108686. };
  108687. /**
  108688. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  108689. */
  108690. FramingBehavior.prototype._applyUserInteraction = function () {
  108691. if (this.isUserIsMoving) {
  108692. this._lastInteractionTime = BABYLON.Tools.Now;
  108693. this.stopAllAnimations();
  108694. this._clearAnimationLocks();
  108695. }
  108696. };
  108697. /**
  108698. * Stops and removes all animations that have been applied to the camera
  108699. */
  108700. FramingBehavior.prototype.stopAllAnimations = function () {
  108701. if (this._attachedCamera) {
  108702. this._attachedCamera.animations = [];
  108703. }
  108704. while (this._animatables.length) {
  108705. if (this._animatables[0]) {
  108706. this._animatables[0].onAnimationEnd = null;
  108707. this._animatables[0].stop();
  108708. }
  108709. this._animatables.shift();
  108710. }
  108711. };
  108712. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  108713. /**
  108714. * Gets a value indicating if the user is moving the camera
  108715. */
  108716. get: function () {
  108717. if (!this._attachedCamera) {
  108718. return false;
  108719. }
  108720. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108721. this._attachedCamera.inertialBetaOffset !== 0 ||
  108722. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108723. this._attachedCamera.inertialPanningX !== 0 ||
  108724. this._attachedCamera.inertialPanningY !== 0 ||
  108725. this._isPointerDown;
  108726. },
  108727. enumerable: true,
  108728. configurable: true
  108729. });
  108730. /**
  108731. * The easing function used by animations
  108732. */
  108733. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  108734. /**
  108735. * The easing mode used by animations
  108736. */
  108737. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  108738. // Statics
  108739. /**
  108740. * The camera can move all the way towards the mesh.
  108741. */
  108742. FramingBehavior.IgnoreBoundsSizeMode = 0;
  108743. /**
  108744. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  108745. */
  108746. FramingBehavior.FitFrustumSidesMode = 1;
  108747. return FramingBehavior;
  108748. }());
  108749. BABYLON.FramingBehavior = FramingBehavior;
  108750. })(BABYLON || (BABYLON = {}));
  108751. //# sourceMappingURL=babylon.framingBehavior.js.map
  108752. var BABYLON;
  108753. (function (BABYLON) {
  108754. /**
  108755. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  108756. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  108757. */
  108758. var BouncingBehavior = /** @class */ (function () {
  108759. function BouncingBehavior() {
  108760. /**
  108761. * The duration of the animation, in milliseconds
  108762. */
  108763. this.transitionDuration = 450;
  108764. /**
  108765. * Length of the distance animated by the transition when lower radius is reached
  108766. */
  108767. this.lowerRadiusTransitionRange = 2;
  108768. /**
  108769. * Length of the distance animated by the transition when upper radius is reached
  108770. */
  108771. this.upperRadiusTransitionRange = -2;
  108772. this._autoTransitionRange = false;
  108773. // Animations
  108774. this._radiusIsAnimating = false;
  108775. this._radiusBounceTransition = null;
  108776. this._animatables = new Array();
  108777. }
  108778. Object.defineProperty(BouncingBehavior.prototype, "name", {
  108779. /**
  108780. * Gets the name of the behavior.
  108781. */
  108782. get: function () {
  108783. return "Bouncing";
  108784. },
  108785. enumerable: true,
  108786. configurable: true
  108787. });
  108788. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  108789. /**
  108790. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108791. */
  108792. get: function () {
  108793. return this._autoTransitionRange;
  108794. },
  108795. /**
  108796. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108797. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  108798. */
  108799. set: function (value) {
  108800. var _this = this;
  108801. if (this._autoTransitionRange === value) {
  108802. return;
  108803. }
  108804. this._autoTransitionRange = value;
  108805. var camera = this._attachedCamera;
  108806. if (!camera) {
  108807. return;
  108808. }
  108809. if (value) {
  108810. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108811. if (!mesh) {
  108812. return;
  108813. }
  108814. mesh.computeWorldMatrix(true);
  108815. var diagonal = mesh.getBoundingInfo().diagonalLength;
  108816. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  108817. _this.upperRadiusTransitionRange = diagonal * 0.05;
  108818. });
  108819. }
  108820. else if (this._onMeshTargetChangedObserver) {
  108821. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108822. }
  108823. },
  108824. enumerable: true,
  108825. configurable: true
  108826. });
  108827. /**
  108828. * Initializes the behavior.
  108829. */
  108830. BouncingBehavior.prototype.init = function () {
  108831. // Do notihng
  108832. };
  108833. /**
  108834. * Attaches the behavior to its arc rotate camera.
  108835. * @param camera Defines the camera to attach the behavior to
  108836. */
  108837. BouncingBehavior.prototype.attach = function (camera) {
  108838. var _this = this;
  108839. this._attachedCamera = camera;
  108840. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108841. if (!_this._attachedCamera) {
  108842. return;
  108843. }
  108844. // Add the bounce animation to the lower radius limit
  108845. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  108846. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  108847. }
  108848. // Add the bounce animation to the upper radius limit
  108849. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  108850. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  108851. }
  108852. });
  108853. };
  108854. /**
  108855. * Detaches the behavior from its current arc rotate camera.
  108856. */
  108857. BouncingBehavior.prototype.detach = function () {
  108858. if (!this._attachedCamera) {
  108859. return;
  108860. }
  108861. if (this._onAfterCheckInputsObserver) {
  108862. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108863. }
  108864. if (this._onMeshTargetChangedObserver) {
  108865. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108866. }
  108867. this._attachedCamera = null;
  108868. };
  108869. /**
  108870. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  108871. * @param radiusLimit The limit to check against.
  108872. * @return Bool to indicate if at limit.
  108873. */
  108874. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  108875. if (!this._attachedCamera) {
  108876. return false;
  108877. }
  108878. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  108879. return true;
  108880. }
  108881. return false;
  108882. };
  108883. /**
  108884. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  108885. * @param radiusDelta The delta by which to animate to. Can be negative.
  108886. */
  108887. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  108888. var _this = this;
  108889. if (!this._attachedCamera) {
  108890. return;
  108891. }
  108892. if (!this._radiusBounceTransition) {
  108893. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  108894. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  108895. }
  108896. // Prevent zoom until bounce has completed
  108897. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  108898. this._attachedCamera.wheelPrecision = Infinity;
  108899. this._attachedCamera.inertialRadiusOffset = 0;
  108900. // Animate to the radius limit
  108901. this.stopAllAnimations();
  108902. this._radiusIsAnimating = true;
  108903. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  108904. if (animatable) {
  108905. this._animatables.push(animatable);
  108906. }
  108907. };
  108908. /**
  108909. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  108910. */
  108911. BouncingBehavior.prototype._clearAnimationLocks = function () {
  108912. this._radiusIsAnimating = false;
  108913. if (this._attachedCamera) {
  108914. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  108915. }
  108916. };
  108917. /**
  108918. * Stops and removes all animations that have been applied to the camera
  108919. */
  108920. BouncingBehavior.prototype.stopAllAnimations = function () {
  108921. if (this._attachedCamera) {
  108922. this._attachedCamera.animations = [];
  108923. }
  108924. while (this._animatables.length) {
  108925. this._animatables[0].onAnimationEnd = null;
  108926. this._animatables[0].stop();
  108927. this._animatables.shift();
  108928. }
  108929. };
  108930. /**
  108931. * The easing function used by animations
  108932. */
  108933. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  108934. /**
  108935. * The easing mode used by animations
  108936. */
  108937. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  108938. return BouncingBehavior;
  108939. }());
  108940. BABYLON.BouncingBehavior = BouncingBehavior;
  108941. })(BABYLON || (BABYLON = {}));
  108942. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  108943. var BABYLON;
  108944. (function (BABYLON) {
  108945. /**
  108946. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  108947. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  108948. */
  108949. var AutoRotationBehavior = /** @class */ (function () {
  108950. function AutoRotationBehavior() {
  108951. this._zoomStopsAnimation = false;
  108952. this._idleRotationSpeed = 0.05;
  108953. this._idleRotationWaitTime = 2000;
  108954. this._idleRotationSpinupTime = 2000;
  108955. this._isPointerDown = false;
  108956. this._lastFrameTime = null;
  108957. this._lastInteractionTime = -Infinity;
  108958. this._cameraRotationSpeed = 0;
  108959. this._lastFrameRadius = 0;
  108960. }
  108961. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  108962. /**
  108963. * Gets the name of the behavior.
  108964. */
  108965. get: function () {
  108966. return "AutoRotation";
  108967. },
  108968. enumerable: true,
  108969. configurable: true
  108970. });
  108971. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  108972. /**
  108973. * Gets the flag that indicates if user zooming should stop animation.
  108974. */
  108975. get: function () {
  108976. return this._zoomStopsAnimation;
  108977. },
  108978. /**
  108979. * Sets the flag that indicates if user zooming should stop animation.
  108980. */
  108981. set: function (flag) {
  108982. this._zoomStopsAnimation = flag;
  108983. },
  108984. enumerable: true,
  108985. configurable: true
  108986. });
  108987. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  108988. /**
  108989. * Gets the default speed at which the camera rotates around the model.
  108990. */
  108991. get: function () {
  108992. return this._idleRotationSpeed;
  108993. },
  108994. /**
  108995. * Sets the default speed at which the camera rotates around the model.
  108996. */
  108997. set: function (speed) {
  108998. this._idleRotationSpeed = speed;
  108999. },
  109000. enumerable: true,
  109001. configurable: true
  109002. });
  109003. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  109004. /**
  109005. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  109006. */
  109007. get: function () {
  109008. return this._idleRotationWaitTime;
  109009. },
  109010. /**
  109011. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  109012. */
  109013. set: function (time) {
  109014. this._idleRotationWaitTime = time;
  109015. },
  109016. enumerable: true,
  109017. configurable: true
  109018. });
  109019. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  109020. /**
  109021. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109022. */
  109023. get: function () {
  109024. return this._idleRotationSpinupTime;
  109025. },
  109026. /**
  109027. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109028. */
  109029. set: function (time) {
  109030. this._idleRotationSpinupTime = time;
  109031. },
  109032. enumerable: true,
  109033. configurable: true
  109034. });
  109035. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  109036. /**
  109037. * Gets a value indicating if the camera is currently rotating because of this behavior
  109038. */
  109039. get: function () {
  109040. return Math.abs(this._cameraRotationSpeed) > 0;
  109041. },
  109042. enumerable: true,
  109043. configurable: true
  109044. });
  109045. /**
  109046. * Initializes the behavior.
  109047. */
  109048. AutoRotationBehavior.prototype.init = function () {
  109049. // Do notihng
  109050. };
  109051. /**
  109052. * Attaches the behavior to its arc rotate camera.
  109053. * @param camera Defines the camera to attach the behavior to
  109054. */
  109055. AutoRotationBehavior.prototype.attach = function (camera) {
  109056. var _this = this;
  109057. this._attachedCamera = camera;
  109058. var scene = this._attachedCamera.getScene();
  109059. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109060. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109061. _this._isPointerDown = true;
  109062. return;
  109063. }
  109064. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109065. _this._isPointerDown = false;
  109066. }
  109067. });
  109068. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109069. var now = BABYLON.Tools.Now;
  109070. var dt = 0;
  109071. if (_this._lastFrameTime != null) {
  109072. dt = now - _this._lastFrameTime;
  109073. }
  109074. _this._lastFrameTime = now;
  109075. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109076. _this._applyUserInteraction();
  109077. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  109078. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  109079. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  109080. // Step camera rotation by rotation speed
  109081. if (_this._attachedCamera) {
  109082. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  109083. }
  109084. });
  109085. };
  109086. /**
  109087. * Detaches the behavior from its current arc rotate camera.
  109088. */
  109089. AutoRotationBehavior.prototype.detach = function () {
  109090. if (!this._attachedCamera) {
  109091. return;
  109092. }
  109093. var scene = this._attachedCamera.getScene();
  109094. if (this._onPrePointerObservableObserver) {
  109095. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109096. }
  109097. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109098. this._attachedCamera = null;
  109099. };
  109100. /**
  109101. * Returns true if user is scrolling.
  109102. * @return true if user is scrolling.
  109103. */
  109104. AutoRotationBehavior.prototype._userIsZooming = function () {
  109105. if (!this._attachedCamera) {
  109106. return false;
  109107. }
  109108. return this._attachedCamera.inertialRadiusOffset !== 0;
  109109. };
  109110. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  109111. if (!this._attachedCamera) {
  109112. return false;
  109113. }
  109114. var zoomHasHitLimit = false;
  109115. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  109116. zoomHasHitLimit = true;
  109117. }
  109118. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  109119. this._lastFrameRadius = this._attachedCamera.radius;
  109120. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  109121. };
  109122. /**
  109123. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109124. */
  109125. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  109126. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  109127. this._lastInteractionTime = BABYLON.Tools.Now;
  109128. }
  109129. };
  109130. // Tools
  109131. AutoRotationBehavior.prototype._userIsMoving = function () {
  109132. if (!this._attachedCamera) {
  109133. return false;
  109134. }
  109135. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109136. this._attachedCamera.inertialBetaOffset !== 0 ||
  109137. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109138. this._attachedCamera.inertialPanningX !== 0 ||
  109139. this._attachedCamera.inertialPanningY !== 0 ||
  109140. this._isPointerDown;
  109141. };
  109142. return AutoRotationBehavior;
  109143. }());
  109144. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  109145. })(BABYLON || (BABYLON = {}));
  109146. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  109147. var BABYLON;
  109148. (function (BABYLON) {
  109149. var NullEngineOptions = /** @class */ (function () {
  109150. function NullEngineOptions() {
  109151. this.renderWidth = 512;
  109152. this.renderHeight = 256;
  109153. this.textureSize = 512;
  109154. this.deterministicLockstep = false;
  109155. this.lockstepMaxSteps = 4;
  109156. }
  109157. return NullEngineOptions;
  109158. }());
  109159. BABYLON.NullEngineOptions = NullEngineOptions;
  109160. /**
  109161. * The null engine class provides support for headless version of babylon.js.
  109162. * This can be used in server side scenario or for testing purposes
  109163. */
  109164. var NullEngine = /** @class */ (function (_super) {
  109165. __extends(NullEngine, _super);
  109166. function NullEngine(options) {
  109167. if (options === void 0) { options = new NullEngineOptions(); }
  109168. var _this = _super.call(this, null) || this;
  109169. if (options.deterministicLockstep === undefined) {
  109170. options.deterministicLockstep = false;
  109171. }
  109172. if (options.lockstepMaxSteps === undefined) {
  109173. options.lockstepMaxSteps = 4;
  109174. }
  109175. _this._options = options;
  109176. // Init caps
  109177. // We consider we are on a webgl1 capable device
  109178. _this._caps = new BABYLON.EngineCapabilities();
  109179. _this._caps.maxTexturesImageUnits = 16;
  109180. _this._caps.maxVertexTextureImageUnits = 16;
  109181. _this._caps.maxTextureSize = 512;
  109182. _this._caps.maxCubemapTextureSize = 512;
  109183. _this._caps.maxRenderTextureSize = 512;
  109184. _this._caps.maxVertexAttribs = 16;
  109185. _this._caps.maxVaryingVectors = 16;
  109186. _this._caps.maxFragmentUniformVectors = 16;
  109187. _this._caps.maxVertexUniformVectors = 16;
  109188. // Extensions
  109189. _this._caps.standardDerivatives = false;
  109190. _this._caps.astc = null;
  109191. _this._caps.s3tc = null;
  109192. _this._caps.pvrtc = null;
  109193. _this._caps.etc1 = null;
  109194. _this._caps.etc2 = null;
  109195. _this._caps.textureAnisotropicFilterExtension = null;
  109196. _this._caps.maxAnisotropy = 0;
  109197. _this._caps.uintIndices = false;
  109198. _this._caps.fragmentDepthSupported = false;
  109199. _this._caps.highPrecisionShaderSupported = true;
  109200. _this._caps.colorBufferFloat = false;
  109201. _this._caps.textureFloat = false;
  109202. _this._caps.textureFloatLinearFiltering = false;
  109203. _this._caps.textureFloatRender = false;
  109204. _this._caps.textureHalfFloat = false;
  109205. _this._caps.textureHalfFloatLinearFiltering = false;
  109206. _this._caps.textureHalfFloatRender = false;
  109207. _this._caps.textureLOD = false;
  109208. _this._caps.drawBuffersExtension = false;
  109209. _this._caps.depthTextureExtension = false;
  109210. _this._caps.vertexArrayObject = false;
  109211. _this._caps.instancedArrays = false;
  109212. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  109213. // Wrappers
  109214. if (typeof URL === "undefined") {
  109215. URL = {
  109216. createObjectURL: function () { },
  109217. revokeObjectURL: function () { }
  109218. };
  109219. }
  109220. if (typeof Blob === "undefined") {
  109221. Blob = function () { };
  109222. }
  109223. return _this;
  109224. }
  109225. NullEngine.prototype.isDeterministicLockStep = function () {
  109226. return this._options.deterministicLockstep;
  109227. };
  109228. NullEngine.prototype.getLockstepMaxSteps = function () {
  109229. return this._options.lockstepMaxSteps;
  109230. };
  109231. NullEngine.prototype.getHardwareScalingLevel = function () {
  109232. return 1.0;
  109233. };
  109234. NullEngine.prototype.createVertexBuffer = function (vertices) {
  109235. return {
  109236. capacity: 0,
  109237. references: 1,
  109238. is32Bits: false
  109239. };
  109240. };
  109241. NullEngine.prototype.createIndexBuffer = function (indices) {
  109242. return {
  109243. capacity: 0,
  109244. references: 1,
  109245. is32Bits: false
  109246. };
  109247. };
  109248. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  109249. if (stencil === void 0) { stencil = false; }
  109250. };
  109251. NullEngine.prototype.getRenderWidth = function (useScreen) {
  109252. if (useScreen === void 0) { useScreen = false; }
  109253. if (!useScreen && this._currentRenderTarget) {
  109254. return this._currentRenderTarget.width;
  109255. }
  109256. return this._options.renderWidth;
  109257. };
  109258. NullEngine.prototype.getRenderHeight = function (useScreen) {
  109259. if (useScreen === void 0) { useScreen = false; }
  109260. if (!useScreen && this._currentRenderTarget) {
  109261. return this._currentRenderTarget.height;
  109262. }
  109263. return this._options.renderHeight;
  109264. };
  109265. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  109266. this._cachedViewport = viewport;
  109267. };
  109268. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  109269. return {
  109270. transformFeedback: null,
  109271. __SPECTOR_rebuildProgram: null
  109272. };
  109273. };
  109274. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  109275. return [];
  109276. };
  109277. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  109278. return [];
  109279. };
  109280. NullEngine.prototype.bindSamplers = function (effect) {
  109281. this._currentEffect = null;
  109282. };
  109283. NullEngine.prototype.enableEffect = function (effect) {
  109284. this._currentEffect = effect;
  109285. if (effect.onBind) {
  109286. effect.onBind(effect);
  109287. }
  109288. if (effect._onBindObservable) {
  109289. effect._onBindObservable.notifyObservers(effect);
  109290. }
  109291. };
  109292. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  109293. if (zOffset === void 0) { zOffset = 0; }
  109294. if (reverseSide === void 0) { reverseSide = false; }
  109295. };
  109296. NullEngine.prototype.setIntArray = function (uniform, array) {
  109297. };
  109298. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  109299. };
  109300. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  109301. };
  109302. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  109303. };
  109304. NullEngine.prototype.setFloatArray = function (uniform, array) {
  109305. };
  109306. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  109307. };
  109308. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  109309. };
  109310. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  109311. };
  109312. NullEngine.prototype.setArray = function (uniform, array) {
  109313. };
  109314. NullEngine.prototype.setArray2 = function (uniform, array) {
  109315. };
  109316. NullEngine.prototype.setArray3 = function (uniform, array) {
  109317. };
  109318. NullEngine.prototype.setArray4 = function (uniform, array) {
  109319. };
  109320. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  109321. };
  109322. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  109323. };
  109324. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  109325. };
  109326. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  109327. };
  109328. NullEngine.prototype.setFloat = function (uniform, value) {
  109329. };
  109330. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  109331. };
  109332. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  109333. };
  109334. NullEngine.prototype.setBool = function (uniform, bool) {
  109335. };
  109336. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  109337. };
  109338. NullEngine.prototype.setColor3 = function (uniform, color3) {
  109339. };
  109340. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  109341. };
  109342. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  109343. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  109344. if (this._alphaMode === mode) {
  109345. return;
  109346. }
  109347. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  109348. if (!noDepthWriteChange) {
  109349. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  109350. }
  109351. this._alphaMode = mode;
  109352. };
  109353. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  109354. };
  109355. NullEngine.prototype.wipeCaches = function (bruteForce) {
  109356. if (this.preventCacheWipeBetweenFrames) {
  109357. return;
  109358. }
  109359. this.resetTextureCache();
  109360. this._currentEffect = null;
  109361. if (bruteForce) {
  109362. this._currentProgram = null;
  109363. this._stencilState.reset();
  109364. this._depthCullingState.reset();
  109365. this._alphaState.reset();
  109366. }
  109367. this._cachedVertexBuffers = null;
  109368. this._cachedIndexBuffer = null;
  109369. this._cachedEffectForVertexBuffers = null;
  109370. };
  109371. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  109372. };
  109373. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  109374. };
  109375. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  109376. };
  109377. /** @hidden */
  109378. NullEngine.prototype._createTexture = function () {
  109379. return {};
  109380. };
  109381. /** @hidden */
  109382. NullEngine.prototype._releaseTexture = function (texture) {
  109383. };
  109384. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  109385. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109386. if (onLoad === void 0) { onLoad = null; }
  109387. if (onError === void 0) { onError = null; }
  109388. if (buffer === void 0) { buffer = null; }
  109389. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  109390. var url = String(urlArg);
  109391. texture.url = url;
  109392. texture.generateMipMaps = !noMipmap;
  109393. texture.samplingMode = samplingMode;
  109394. texture.invertY = invertY;
  109395. texture.baseWidth = this._options.textureSize;
  109396. texture.baseHeight = this._options.textureSize;
  109397. texture.width = this._options.textureSize;
  109398. texture.height = this._options.textureSize;
  109399. if (format) {
  109400. texture.format = format;
  109401. }
  109402. texture.isReady = true;
  109403. if (onLoad) {
  109404. onLoad();
  109405. }
  109406. this._internalTexturesCache.push(texture);
  109407. return texture;
  109408. };
  109409. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  109410. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  109411. if (options !== undefined && typeof options === "object") {
  109412. fullOptions.generateMipMaps = options.generateMipMaps;
  109413. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  109414. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  109415. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  109416. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  109417. }
  109418. else {
  109419. fullOptions.generateMipMaps = options;
  109420. fullOptions.generateDepthBuffer = true;
  109421. fullOptions.generateStencilBuffer = false;
  109422. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109423. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  109424. }
  109425. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  109426. var width = size.width || size;
  109427. var height = size.height || size;
  109428. texture._depthStencilBuffer = {};
  109429. texture._framebuffer = {};
  109430. texture.baseWidth = width;
  109431. texture.baseHeight = height;
  109432. texture.width = width;
  109433. texture.height = height;
  109434. texture.isReady = true;
  109435. texture.samples = 1;
  109436. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  109437. texture.samplingMode = fullOptions.samplingMode;
  109438. texture.type = fullOptions.type;
  109439. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  109440. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  109441. this._internalTexturesCache.push(texture);
  109442. return texture;
  109443. };
  109444. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  109445. texture.samplingMode = samplingMode;
  109446. };
  109447. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  109448. if (this._currentRenderTarget) {
  109449. this.unBindFramebuffer(this._currentRenderTarget);
  109450. }
  109451. this._currentRenderTarget = texture;
  109452. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  109453. if (this._cachedViewport && !forceFullscreenViewport) {
  109454. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  109455. }
  109456. };
  109457. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  109458. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  109459. this._currentRenderTarget = null;
  109460. if (onBeforeUnbind) {
  109461. if (texture._MSAAFramebuffer) {
  109462. this._currentFramebuffer = texture._framebuffer;
  109463. }
  109464. onBeforeUnbind();
  109465. }
  109466. this._currentFramebuffer = null;
  109467. };
  109468. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  109469. var vbo = {
  109470. capacity: 1,
  109471. references: 1,
  109472. is32Bits: false
  109473. };
  109474. return vbo;
  109475. };
  109476. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  109477. if (premulAlpha === void 0) { premulAlpha = false; }
  109478. };
  109479. /**
  109480. * @hidden
  109481. * Get the current error code of the webGL context
  109482. * @returns the error code
  109483. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  109484. */
  109485. NullEngine.prototype.getError = function () {
  109486. return 0;
  109487. };
  109488. /** @hidden */
  109489. NullEngine.prototype._getUnpackAlignement = function () {
  109490. return 1;
  109491. };
  109492. /** @hidden */
  109493. NullEngine.prototype._unpackFlipY = function (value) {
  109494. };
  109495. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  109496. if (offset === void 0) { offset = 0; }
  109497. };
  109498. /**
  109499. * Updates a dynamic vertex buffer.
  109500. * @param vertexBuffer the vertex buffer to update
  109501. * @param data the data used to update the vertex buffer
  109502. * @param byteOffset the byte offset of the data (optional)
  109503. * @param byteLength the byte length of the data (optional)
  109504. */
  109505. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  109506. };
  109507. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  109508. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  109509. this._boundTexturesCache[this._activeChannel] = texture;
  109510. return true;
  109511. }
  109512. return false;
  109513. };
  109514. /** @hidden */
  109515. NullEngine.prototype._bindTexture = function (channel, texture) {
  109516. if (channel < 0) {
  109517. return;
  109518. }
  109519. this._bindTextureDirectly(0, texture);
  109520. };
  109521. /** @hidden */
  109522. NullEngine.prototype._releaseBuffer = function (buffer) {
  109523. buffer.references--;
  109524. if (buffer.references === 0) {
  109525. return true;
  109526. }
  109527. return false;
  109528. };
  109529. NullEngine.prototype.releaseEffects = function () {
  109530. };
  109531. NullEngine.prototype.displayLoadingUI = function () {
  109532. };
  109533. NullEngine.prototype.hideLoadingUI = function () {
  109534. };
  109535. /** @hidden */
  109536. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  109537. if (faceIndex === void 0) { faceIndex = 0; }
  109538. if (lod === void 0) { lod = 0; }
  109539. };
  109540. /** @hidden */
  109541. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  109542. if (faceIndex === void 0) { faceIndex = 0; }
  109543. if (lod === void 0) { lod = 0; }
  109544. };
  109545. /** @hidden */
  109546. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  109547. if (faceIndex === void 0) { faceIndex = 0; }
  109548. if (lod === void 0) { lod = 0; }
  109549. };
  109550. /** @hidden */
  109551. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  109552. if (faceIndex === void 0) { faceIndex = 0; }
  109553. if (lod === void 0) { lod = 0; }
  109554. };
  109555. return NullEngine;
  109556. }(BABYLON.Engine));
  109557. BABYLON.NullEngine = NullEngine;
  109558. })(BABYLON || (BABYLON = {}));
  109559. //# sourceMappingURL=babylon.nullEngine.js.map
  109560. var BABYLON;
  109561. (function (BABYLON) {
  109562. /**
  109563. * This class can be used to get instrumentation data from a Babylon engine
  109564. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109565. */
  109566. var EngineInstrumentation = /** @class */ (function () {
  109567. /**
  109568. * Instantiates a new engine instrumentation.
  109569. * This class can be used to get instrumentation data from a Babylon engine
  109570. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109571. * @param engine Defines the engine to instrument
  109572. */
  109573. function EngineInstrumentation(
  109574. /**
  109575. * Define the instrumented engine.
  109576. */
  109577. engine) {
  109578. this.engine = engine;
  109579. this._captureGPUFrameTime = false;
  109580. this._gpuFrameTime = new BABYLON.PerfCounter();
  109581. this._captureShaderCompilationTime = false;
  109582. this._shaderCompilationTime = new BABYLON.PerfCounter();
  109583. // Observers
  109584. this._onBeginFrameObserver = null;
  109585. this._onEndFrameObserver = null;
  109586. this._onBeforeShaderCompilationObserver = null;
  109587. this._onAfterShaderCompilationObserver = null;
  109588. }
  109589. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  109590. // Properties
  109591. /**
  109592. * Gets the perf counter used for GPU frame time
  109593. */
  109594. get: function () {
  109595. return this._gpuFrameTime;
  109596. },
  109597. enumerable: true,
  109598. configurable: true
  109599. });
  109600. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  109601. /**
  109602. * Gets the GPU frame time capture status
  109603. */
  109604. get: function () {
  109605. return this._captureGPUFrameTime;
  109606. },
  109607. /**
  109608. * Enable or disable the GPU frame time capture
  109609. */
  109610. set: function (value) {
  109611. var _this = this;
  109612. if (value === this._captureGPUFrameTime) {
  109613. return;
  109614. }
  109615. this._captureGPUFrameTime = value;
  109616. if (value) {
  109617. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  109618. if (!_this._gpuFrameTimeToken) {
  109619. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  109620. }
  109621. });
  109622. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  109623. if (!_this._gpuFrameTimeToken) {
  109624. return;
  109625. }
  109626. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  109627. if (time > -1) {
  109628. _this._gpuFrameTimeToken = null;
  109629. _this._gpuFrameTime.fetchNewFrame();
  109630. _this._gpuFrameTime.addCount(time, true);
  109631. }
  109632. });
  109633. }
  109634. else {
  109635. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109636. this._onBeginFrameObserver = null;
  109637. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109638. this._onEndFrameObserver = null;
  109639. }
  109640. },
  109641. enumerable: true,
  109642. configurable: true
  109643. });
  109644. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  109645. /**
  109646. * Gets the perf counter used for shader compilation time
  109647. */
  109648. get: function () {
  109649. return this._shaderCompilationTime;
  109650. },
  109651. enumerable: true,
  109652. configurable: true
  109653. });
  109654. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  109655. /**
  109656. * Gets the shader compilation time capture status
  109657. */
  109658. get: function () {
  109659. return this._captureShaderCompilationTime;
  109660. },
  109661. /**
  109662. * Enable or disable the shader compilation time capture
  109663. */
  109664. set: function (value) {
  109665. var _this = this;
  109666. if (value === this._captureShaderCompilationTime) {
  109667. return;
  109668. }
  109669. this._captureShaderCompilationTime = value;
  109670. if (value) {
  109671. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  109672. _this._shaderCompilationTime.fetchNewFrame();
  109673. _this._shaderCompilationTime.beginMonitoring();
  109674. });
  109675. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  109676. _this._shaderCompilationTime.endMonitoring();
  109677. });
  109678. }
  109679. else {
  109680. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109681. this._onBeforeShaderCompilationObserver = null;
  109682. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109683. this._onAfterShaderCompilationObserver = null;
  109684. }
  109685. },
  109686. enumerable: true,
  109687. configurable: true
  109688. });
  109689. /**
  109690. * Dispose and release associated resources.
  109691. */
  109692. EngineInstrumentation.prototype.dispose = function () {
  109693. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109694. this._onBeginFrameObserver = null;
  109695. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109696. this._onEndFrameObserver = null;
  109697. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109698. this._onBeforeShaderCompilationObserver = null;
  109699. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109700. this._onAfterShaderCompilationObserver = null;
  109701. this.engine = null;
  109702. };
  109703. return EngineInstrumentation;
  109704. }());
  109705. BABYLON.EngineInstrumentation = EngineInstrumentation;
  109706. })(BABYLON || (BABYLON = {}));
  109707. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  109708. var BABYLON;
  109709. (function (BABYLON) {
  109710. /**
  109711. * This class can be used to get instrumentation data from a Babylon engine
  109712. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109713. */
  109714. var SceneInstrumentation = /** @class */ (function () {
  109715. /**
  109716. * Instantiates a new scene instrumentation.
  109717. * This class can be used to get instrumentation data from a Babylon engine
  109718. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109719. * @param scene Defines the scene to instrument
  109720. */
  109721. function SceneInstrumentation(
  109722. /**
  109723. * Defines the scene to instrument
  109724. */
  109725. scene) {
  109726. var _this = this;
  109727. this.scene = scene;
  109728. this._captureActiveMeshesEvaluationTime = false;
  109729. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  109730. this._captureRenderTargetsRenderTime = false;
  109731. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  109732. this._captureFrameTime = false;
  109733. this._frameTime = new BABYLON.PerfCounter();
  109734. this._captureRenderTime = false;
  109735. this._renderTime = new BABYLON.PerfCounter();
  109736. this._captureInterFrameTime = false;
  109737. this._interFrameTime = new BABYLON.PerfCounter();
  109738. this._captureParticlesRenderTime = false;
  109739. this._particlesRenderTime = new BABYLON.PerfCounter();
  109740. this._captureSpritesRenderTime = false;
  109741. this._spritesRenderTime = new BABYLON.PerfCounter();
  109742. this._capturePhysicsTime = false;
  109743. this._physicsTime = new BABYLON.PerfCounter();
  109744. this._captureAnimationsTime = false;
  109745. this._animationsTime = new BABYLON.PerfCounter();
  109746. this._captureCameraRenderTime = false;
  109747. this._cameraRenderTime = new BABYLON.PerfCounter();
  109748. // Observers
  109749. this._onBeforeActiveMeshesEvaluationObserver = null;
  109750. this._onAfterActiveMeshesEvaluationObserver = null;
  109751. this._onBeforeRenderTargetsRenderObserver = null;
  109752. this._onAfterRenderTargetsRenderObserver = null;
  109753. this._onAfterRenderObserver = null;
  109754. this._onBeforeDrawPhaseObserver = null;
  109755. this._onAfterDrawPhaseObserver = null;
  109756. this._onBeforeAnimationsObserver = null;
  109757. this._onBeforeParticlesRenderingObserver = null;
  109758. this._onAfterParticlesRenderingObserver = null;
  109759. this._onBeforeSpritesRenderingObserver = null;
  109760. this._onAfterSpritesRenderingObserver = null;
  109761. this._onBeforePhysicsObserver = null;
  109762. this._onAfterPhysicsObserver = null;
  109763. this._onAfterAnimationsObserver = null;
  109764. this._onBeforeCameraRenderObserver = null;
  109765. this._onAfterCameraRenderObserver = null;
  109766. // Before render
  109767. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  109768. if (_this._captureActiveMeshesEvaluationTime) {
  109769. _this._activeMeshesEvaluationTime.fetchNewFrame();
  109770. }
  109771. if (_this._captureRenderTargetsRenderTime) {
  109772. _this._renderTargetsRenderTime.fetchNewFrame();
  109773. }
  109774. if (_this._captureFrameTime) {
  109775. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  109776. _this._frameTime.beginMonitoring();
  109777. }
  109778. if (_this._captureInterFrameTime) {
  109779. _this._interFrameTime.endMonitoring();
  109780. }
  109781. if (_this._captureParticlesRenderTime) {
  109782. _this._particlesRenderTime.fetchNewFrame();
  109783. }
  109784. if (_this._captureSpritesRenderTime) {
  109785. _this._spritesRenderTime.fetchNewFrame();
  109786. }
  109787. if (_this._captureAnimationsTime) {
  109788. _this._animationsTime.beginMonitoring();
  109789. }
  109790. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  109791. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  109792. });
  109793. // After render
  109794. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  109795. if (_this._captureFrameTime) {
  109796. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  109797. _this._frameTime.endMonitoring();
  109798. }
  109799. if (_this._captureRenderTime) {
  109800. _this._renderTime.endMonitoring(false);
  109801. }
  109802. if (_this._captureInterFrameTime) {
  109803. _this._interFrameTime.beginMonitoring();
  109804. }
  109805. });
  109806. }
  109807. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  109808. // Properties
  109809. /**
  109810. * Gets the perf counter used for active meshes evaluation time
  109811. */
  109812. get: function () {
  109813. return this._activeMeshesEvaluationTime;
  109814. },
  109815. enumerable: true,
  109816. configurable: true
  109817. });
  109818. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  109819. /**
  109820. * Gets the active meshes evaluation time capture status
  109821. */
  109822. get: function () {
  109823. return this._captureActiveMeshesEvaluationTime;
  109824. },
  109825. /**
  109826. * Enable or disable the active meshes evaluation time capture
  109827. */
  109828. set: function (value) {
  109829. var _this = this;
  109830. if (value === this._captureActiveMeshesEvaluationTime) {
  109831. return;
  109832. }
  109833. this._captureActiveMeshesEvaluationTime = value;
  109834. if (value) {
  109835. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  109836. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  109837. _this._activeMeshesEvaluationTime.beginMonitoring();
  109838. });
  109839. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  109840. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  109841. _this._activeMeshesEvaluationTime.endMonitoring();
  109842. });
  109843. }
  109844. else {
  109845. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109846. this._onBeforeActiveMeshesEvaluationObserver = null;
  109847. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109848. this._onAfterActiveMeshesEvaluationObserver = null;
  109849. }
  109850. },
  109851. enumerable: true,
  109852. configurable: true
  109853. });
  109854. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  109855. /**
  109856. * Gets the perf counter used for render targets render time
  109857. */
  109858. get: function () {
  109859. return this._renderTargetsRenderTime;
  109860. },
  109861. enumerable: true,
  109862. configurable: true
  109863. });
  109864. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  109865. /**
  109866. * Gets the render targets render time capture status
  109867. */
  109868. get: function () {
  109869. return this._captureRenderTargetsRenderTime;
  109870. },
  109871. /**
  109872. * Enable or disable the render targets render time capture
  109873. */
  109874. set: function (value) {
  109875. var _this = this;
  109876. if (value === this._captureRenderTargetsRenderTime) {
  109877. return;
  109878. }
  109879. this._captureRenderTargetsRenderTime = value;
  109880. if (value) {
  109881. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  109882. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  109883. _this._renderTargetsRenderTime.beginMonitoring();
  109884. });
  109885. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  109886. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  109887. _this._renderTargetsRenderTime.endMonitoring(false);
  109888. });
  109889. }
  109890. else {
  109891. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109892. this._onBeforeRenderTargetsRenderObserver = null;
  109893. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109894. this._onAfterRenderTargetsRenderObserver = null;
  109895. }
  109896. },
  109897. enumerable: true,
  109898. configurable: true
  109899. });
  109900. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  109901. /**
  109902. * Gets the perf counter used for particles render time
  109903. */
  109904. get: function () {
  109905. return this._particlesRenderTime;
  109906. },
  109907. enumerable: true,
  109908. configurable: true
  109909. });
  109910. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  109911. /**
  109912. * Gets the particles render time capture status
  109913. */
  109914. get: function () {
  109915. return this._captureParticlesRenderTime;
  109916. },
  109917. /**
  109918. * Enable or disable the particles render time capture
  109919. */
  109920. set: function (value) {
  109921. var _this = this;
  109922. if (value === this._captureParticlesRenderTime) {
  109923. return;
  109924. }
  109925. this._captureParticlesRenderTime = value;
  109926. if (value) {
  109927. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  109928. BABYLON.Tools.StartPerformanceCounter("Particles");
  109929. _this._particlesRenderTime.beginMonitoring();
  109930. });
  109931. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  109932. BABYLON.Tools.EndPerformanceCounter("Particles");
  109933. _this._particlesRenderTime.endMonitoring(false);
  109934. });
  109935. }
  109936. else {
  109937. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109938. this._onBeforeParticlesRenderingObserver = null;
  109939. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109940. this._onAfterParticlesRenderingObserver = null;
  109941. }
  109942. },
  109943. enumerable: true,
  109944. configurable: true
  109945. });
  109946. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  109947. /**
  109948. * Gets the perf counter used for sprites render time
  109949. */
  109950. get: function () {
  109951. return this._spritesRenderTime;
  109952. },
  109953. enumerable: true,
  109954. configurable: true
  109955. });
  109956. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  109957. /**
  109958. * Gets the sprites render time capture status
  109959. */
  109960. get: function () {
  109961. return this._captureSpritesRenderTime;
  109962. },
  109963. /**
  109964. * Enable or disable the sprites render time capture
  109965. */
  109966. set: function (value) {
  109967. var _this = this;
  109968. if (value === this._captureSpritesRenderTime) {
  109969. return;
  109970. }
  109971. this._captureSpritesRenderTime = value;
  109972. if (!this.scene.spriteManagers) {
  109973. return;
  109974. }
  109975. if (value) {
  109976. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  109977. BABYLON.Tools.StartPerformanceCounter("Sprites");
  109978. _this._spritesRenderTime.beginMonitoring();
  109979. });
  109980. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  109981. BABYLON.Tools.EndPerformanceCounter("Sprites");
  109982. _this._spritesRenderTime.endMonitoring(false);
  109983. });
  109984. }
  109985. else {
  109986. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109987. this._onBeforeSpritesRenderingObserver = null;
  109988. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109989. this._onAfterSpritesRenderingObserver = null;
  109990. }
  109991. },
  109992. enumerable: true,
  109993. configurable: true
  109994. });
  109995. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  109996. /**
  109997. * Gets the perf counter used for physics time
  109998. */
  109999. get: function () {
  110000. return this._physicsTime;
  110001. },
  110002. enumerable: true,
  110003. configurable: true
  110004. });
  110005. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  110006. /**
  110007. * Gets the physics time capture status
  110008. */
  110009. get: function () {
  110010. return this._capturePhysicsTime;
  110011. },
  110012. /**
  110013. * Enable or disable the physics time capture
  110014. */
  110015. set: function (value) {
  110016. var _this = this;
  110017. if (value === this._capturePhysicsTime) {
  110018. return;
  110019. }
  110020. if (!this.scene.onBeforePhysicsObservable) {
  110021. return;
  110022. }
  110023. this._capturePhysicsTime = value;
  110024. if (value) {
  110025. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  110026. BABYLON.Tools.StartPerformanceCounter("Physics");
  110027. _this._physicsTime.beginMonitoring();
  110028. });
  110029. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  110030. BABYLON.Tools.EndPerformanceCounter("Physics");
  110031. _this._physicsTime.endMonitoring();
  110032. });
  110033. }
  110034. else {
  110035. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110036. this._onBeforePhysicsObserver = null;
  110037. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110038. this._onAfterPhysicsObserver = null;
  110039. }
  110040. },
  110041. enumerable: true,
  110042. configurable: true
  110043. });
  110044. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  110045. /**
  110046. * Gets the perf counter used for animations time
  110047. */
  110048. get: function () {
  110049. return this._animationsTime;
  110050. },
  110051. enumerable: true,
  110052. configurable: true
  110053. });
  110054. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  110055. /**
  110056. * Gets the animations time capture status
  110057. */
  110058. get: function () {
  110059. return this._captureAnimationsTime;
  110060. },
  110061. /**
  110062. * Enable or disable the animations time capture
  110063. */
  110064. set: function (value) {
  110065. var _this = this;
  110066. if (value === this._captureAnimationsTime) {
  110067. return;
  110068. }
  110069. this._captureAnimationsTime = value;
  110070. if (value) {
  110071. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  110072. _this._animationsTime.endMonitoring();
  110073. });
  110074. }
  110075. else {
  110076. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110077. this._onAfterAnimationsObserver = null;
  110078. }
  110079. },
  110080. enumerable: true,
  110081. configurable: true
  110082. });
  110083. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  110084. /**
  110085. * Gets the perf counter used for frame time capture
  110086. */
  110087. get: function () {
  110088. return this._frameTime;
  110089. },
  110090. enumerable: true,
  110091. configurable: true
  110092. });
  110093. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  110094. /**
  110095. * Gets the frame time capture status
  110096. */
  110097. get: function () {
  110098. return this._captureFrameTime;
  110099. },
  110100. /**
  110101. * Enable or disable the frame time capture
  110102. */
  110103. set: function (value) {
  110104. this._captureFrameTime = value;
  110105. },
  110106. enumerable: true,
  110107. configurable: true
  110108. });
  110109. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  110110. /**
  110111. * Gets the perf counter used for inter-frames time capture
  110112. */
  110113. get: function () {
  110114. return this._interFrameTime;
  110115. },
  110116. enumerable: true,
  110117. configurable: true
  110118. });
  110119. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  110120. /**
  110121. * Gets the inter-frames time capture status
  110122. */
  110123. get: function () {
  110124. return this._captureInterFrameTime;
  110125. },
  110126. /**
  110127. * Enable or disable the inter-frames time capture
  110128. */
  110129. set: function (value) {
  110130. this._captureInterFrameTime = value;
  110131. },
  110132. enumerable: true,
  110133. configurable: true
  110134. });
  110135. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  110136. /**
  110137. * Gets the perf counter used for render time capture
  110138. */
  110139. get: function () {
  110140. return this._renderTime;
  110141. },
  110142. enumerable: true,
  110143. configurable: true
  110144. });
  110145. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  110146. /**
  110147. * Gets the render time capture status
  110148. */
  110149. get: function () {
  110150. return this._captureRenderTime;
  110151. },
  110152. /**
  110153. * Enable or disable the render time capture
  110154. */
  110155. set: function (value) {
  110156. var _this = this;
  110157. if (value === this._captureRenderTime) {
  110158. return;
  110159. }
  110160. this._captureRenderTime = value;
  110161. if (value) {
  110162. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  110163. _this._renderTime.beginMonitoring();
  110164. BABYLON.Tools.StartPerformanceCounter("Main render");
  110165. });
  110166. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  110167. _this._renderTime.endMonitoring(false);
  110168. BABYLON.Tools.EndPerformanceCounter("Main render");
  110169. });
  110170. }
  110171. else {
  110172. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110173. this._onBeforeDrawPhaseObserver = null;
  110174. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110175. this._onAfterDrawPhaseObserver = null;
  110176. }
  110177. },
  110178. enumerable: true,
  110179. configurable: true
  110180. });
  110181. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  110182. /**
  110183. * Gets the perf counter used for camera render time capture
  110184. */
  110185. get: function () {
  110186. return this._cameraRenderTime;
  110187. },
  110188. enumerable: true,
  110189. configurable: true
  110190. });
  110191. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  110192. /**
  110193. * Gets the camera render time capture status
  110194. */
  110195. get: function () {
  110196. return this._captureCameraRenderTime;
  110197. },
  110198. /**
  110199. * Enable or disable the camera render time capture
  110200. */
  110201. set: function (value) {
  110202. var _this = this;
  110203. if (value === this._captureCameraRenderTime) {
  110204. return;
  110205. }
  110206. this._captureCameraRenderTime = value;
  110207. if (value) {
  110208. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  110209. _this._cameraRenderTime.beginMonitoring();
  110210. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  110211. });
  110212. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  110213. _this._cameraRenderTime.endMonitoring(false);
  110214. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  110215. });
  110216. }
  110217. else {
  110218. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110219. this._onBeforeCameraRenderObserver = null;
  110220. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110221. this._onAfterCameraRenderObserver = null;
  110222. }
  110223. },
  110224. enumerable: true,
  110225. configurable: true
  110226. });
  110227. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  110228. /**
  110229. * Gets the perf counter used for draw calls
  110230. */
  110231. get: function () {
  110232. return this.scene.getEngine()._drawCalls;
  110233. },
  110234. enumerable: true,
  110235. configurable: true
  110236. });
  110237. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  110238. /**
  110239. * Gets the perf counter used for texture collisions
  110240. */
  110241. get: function () {
  110242. return this.scene.getEngine()._textureCollisions;
  110243. },
  110244. enumerable: true,
  110245. configurable: true
  110246. });
  110247. /**
  110248. * Dispose and release associated resources.
  110249. */
  110250. SceneInstrumentation.prototype.dispose = function () {
  110251. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110252. this._onAfterRenderObserver = null;
  110253. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110254. this._onBeforeActiveMeshesEvaluationObserver = null;
  110255. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110256. this._onAfterActiveMeshesEvaluationObserver = null;
  110257. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110258. this._onBeforeRenderTargetsRenderObserver = null;
  110259. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110260. this._onAfterRenderTargetsRenderObserver = null;
  110261. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  110262. this._onBeforeAnimationsObserver = null;
  110263. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110264. this._onBeforeParticlesRenderingObserver = null;
  110265. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110266. this._onAfterParticlesRenderingObserver = null;
  110267. if (this._onBeforeSpritesRenderingObserver) {
  110268. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110269. this._onBeforeSpritesRenderingObserver = null;
  110270. }
  110271. if (this._onAfterSpritesRenderingObserver) {
  110272. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110273. this._onAfterSpritesRenderingObserver = null;
  110274. }
  110275. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110276. this._onBeforeDrawPhaseObserver = null;
  110277. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110278. this._onAfterDrawPhaseObserver = null;
  110279. if (this._onBeforePhysicsObserver) {
  110280. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110281. this._onBeforePhysicsObserver = null;
  110282. }
  110283. if (this._onAfterPhysicsObserver) {
  110284. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110285. this._onAfterPhysicsObserver = null;
  110286. }
  110287. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110288. this._onAfterAnimationsObserver = null;
  110289. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110290. this._onBeforeCameraRenderObserver = null;
  110291. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110292. this._onAfterCameraRenderObserver = null;
  110293. this.scene = null;
  110294. };
  110295. return SceneInstrumentation;
  110296. }());
  110297. BABYLON.SceneInstrumentation = SceneInstrumentation;
  110298. })(BABYLON || (BABYLON = {}));
  110299. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  110300. var BABYLON;
  110301. (function (BABYLON) {
  110302. /**
  110303. * @hidden
  110304. **/
  110305. var _TimeToken = /** @class */ (function () {
  110306. function _TimeToken() {
  110307. this._timeElapsedQueryEnded = false;
  110308. }
  110309. return _TimeToken;
  110310. }());
  110311. BABYLON._TimeToken = _TimeToken;
  110312. })(BABYLON || (BABYLON = {}));
  110313. //# sourceMappingURL=babylon.timeToken.js.map
  110314. var BABYLON;
  110315. (function (BABYLON) {
  110316. /**
  110317. * Background material defines definition.
  110318. * @hidden Mainly internal Use
  110319. */
  110320. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  110321. __extends(BackgroundMaterialDefines, _super);
  110322. /**
  110323. * Constructor of the defines.
  110324. */
  110325. function BackgroundMaterialDefines() {
  110326. var _this = _super.call(this) || this;
  110327. /**
  110328. * True if the diffuse texture is in use.
  110329. */
  110330. _this.DIFFUSE = false;
  110331. /**
  110332. * The direct UV channel to use.
  110333. */
  110334. _this.DIFFUSEDIRECTUV = 0;
  110335. /**
  110336. * True if the diffuse texture is in gamma space.
  110337. */
  110338. _this.GAMMADIFFUSE = false;
  110339. /**
  110340. * True if the diffuse texture has opacity in the alpha channel.
  110341. */
  110342. _this.DIFFUSEHASALPHA = false;
  110343. /**
  110344. * True if you want the material to fade to transparent at grazing angle.
  110345. */
  110346. _this.OPACITYFRESNEL = false;
  110347. /**
  110348. * True if an extra blur needs to be added in the reflection.
  110349. */
  110350. _this.REFLECTIONBLUR = false;
  110351. /**
  110352. * True if you want the material to fade to reflection at grazing angle.
  110353. */
  110354. _this.REFLECTIONFRESNEL = false;
  110355. /**
  110356. * True if you want the material to falloff as far as you move away from the scene center.
  110357. */
  110358. _this.REFLECTIONFALLOFF = false;
  110359. /**
  110360. * False if the current Webgl implementation does not support the texture lod extension.
  110361. */
  110362. _this.TEXTURELODSUPPORT = false;
  110363. /**
  110364. * True to ensure the data are premultiplied.
  110365. */
  110366. _this.PREMULTIPLYALPHA = false;
  110367. /**
  110368. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  110369. */
  110370. _this.USERGBCOLOR = false;
  110371. /**
  110372. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  110373. * stays aligned with the desired configuration.
  110374. */
  110375. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  110376. /**
  110377. * True to add noise in order to reduce the banding effect.
  110378. */
  110379. _this.NOISE = false;
  110380. /**
  110381. * is the reflection texture in BGR color scheme?
  110382. * Mainly used to solve a bug in ios10 video tag
  110383. */
  110384. _this.REFLECTIONBGR = false;
  110385. _this.IMAGEPROCESSING = false;
  110386. _this.VIGNETTE = false;
  110387. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  110388. _this.VIGNETTEBLENDMODEOPAQUE = false;
  110389. _this.TONEMAPPING = false;
  110390. _this.TONEMAPPING_ACES = false;
  110391. _this.CONTRAST = false;
  110392. _this.COLORCURVES = false;
  110393. _this.COLORGRADING = false;
  110394. _this.COLORGRADING3D = false;
  110395. _this.SAMPLER3DGREENDEPTH = false;
  110396. _this.SAMPLER3DBGRMAP = false;
  110397. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  110398. _this.EXPOSURE = false;
  110399. // Reflection.
  110400. _this.REFLECTION = false;
  110401. _this.REFLECTIONMAP_3D = false;
  110402. _this.REFLECTIONMAP_SPHERICAL = false;
  110403. _this.REFLECTIONMAP_PLANAR = false;
  110404. _this.REFLECTIONMAP_CUBIC = false;
  110405. _this.REFLECTIONMAP_PROJECTION = false;
  110406. _this.REFLECTIONMAP_SKYBOX = false;
  110407. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110408. _this.REFLECTIONMAP_EXPLICIT = false;
  110409. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110410. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110411. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110412. _this.INVERTCUBICMAP = false;
  110413. _this.REFLECTIONMAP_OPPOSITEZ = false;
  110414. _this.LODINREFLECTIONALPHA = false;
  110415. _this.GAMMAREFLECTION = false;
  110416. _this.RGBDREFLECTION = false;
  110417. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  110418. // Default BJS.
  110419. _this.MAINUV1 = false;
  110420. _this.MAINUV2 = false;
  110421. _this.UV1 = false;
  110422. _this.UV2 = false;
  110423. _this.CLIPPLANE = false;
  110424. _this.CLIPPLANE2 = false;
  110425. _this.CLIPPLANE3 = false;
  110426. _this.CLIPPLANE4 = false;
  110427. _this.POINTSIZE = false;
  110428. _this.FOG = false;
  110429. _this.NORMAL = false;
  110430. _this.NUM_BONE_INFLUENCERS = 0;
  110431. _this.BonesPerMesh = 0;
  110432. _this.INSTANCES = false;
  110433. _this.SHADOWFLOAT = false;
  110434. _this.rebuild();
  110435. return _this;
  110436. }
  110437. return BackgroundMaterialDefines;
  110438. }(BABYLON.MaterialDefines));
  110439. /**
  110440. * Background material used to create an efficient environement around your scene.
  110441. */
  110442. var BackgroundMaterial = /** @class */ (function (_super) {
  110443. __extends(BackgroundMaterial, _super);
  110444. /**
  110445. * Instantiates a Background Material in the given scene
  110446. * @param name The friendly name of the material
  110447. * @param scene The scene to add the material to
  110448. */
  110449. function BackgroundMaterial(name, scene) {
  110450. var _this = _super.call(this, name, scene) || this;
  110451. /**
  110452. * Key light Color (multiply against the environement texture)
  110453. */
  110454. _this.primaryColor = BABYLON.Color3.White();
  110455. _this._primaryColorShadowLevel = 0;
  110456. _this._primaryColorHighlightLevel = 0;
  110457. /**
  110458. * Reflection Texture used in the material.
  110459. * Should be author in a specific way for the best result (refer to the documentation).
  110460. */
  110461. _this.reflectionTexture = null;
  110462. /**
  110463. * Reflection Texture level of blur.
  110464. *
  110465. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  110466. * texture twice.
  110467. */
  110468. _this.reflectionBlur = 0;
  110469. /**
  110470. * Diffuse Texture used in the material.
  110471. * Should be author in a specific way for the best result (refer to the documentation).
  110472. */
  110473. _this.diffuseTexture = null;
  110474. _this._shadowLights = null;
  110475. /**
  110476. * Specify the list of lights casting shadow on the material.
  110477. * All scene shadow lights will be included if null.
  110478. */
  110479. _this.shadowLights = null;
  110480. /**
  110481. * Helps adjusting the shadow to a softer level if required.
  110482. * 0 means black shadows and 1 means no shadows.
  110483. */
  110484. _this.shadowLevel = 0;
  110485. /**
  110486. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  110487. * It is usually zero but might be interesting to modify according to your setup.
  110488. */
  110489. _this.sceneCenter = BABYLON.Vector3.Zero();
  110490. /**
  110491. * This helps specifying that the material is falling off to the sky box at grazing angle.
  110492. * This helps ensuring a nice transition when the camera goes under the ground.
  110493. */
  110494. _this.opacityFresnel = true;
  110495. /**
  110496. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  110497. * This helps adding a mirror texture on the ground.
  110498. */
  110499. _this.reflectionFresnel = false;
  110500. /**
  110501. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  110502. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  110503. */
  110504. _this.reflectionFalloffDistance = 0.0;
  110505. /**
  110506. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  110507. */
  110508. _this.reflectionAmount = 1.0;
  110509. /**
  110510. * This specifies the weight of the reflection at grazing angle.
  110511. */
  110512. _this.reflectionReflectance0 = 0.05;
  110513. /**
  110514. * This specifies the weight of the reflection at a perpendicular point of view.
  110515. */
  110516. _this.reflectionReflectance90 = 0.5;
  110517. /**
  110518. * Helps to directly use the maps channels instead of their level.
  110519. */
  110520. _this.useRGBColor = true;
  110521. /**
  110522. * This helps reducing the banding effect that could occur on the background.
  110523. */
  110524. _this.enableNoise = false;
  110525. _this._fovMultiplier = 1.0;
  110526. /**
  110527. * Enable the FOV adjustment feature controlled by fovMultiplier.
  110528. */
  110529. _this.useEquirectangularFOV = false;
  110530. _this._maxSimultaneousLights = 4;
  110531. /**
  110532. * Number of Simultaneous lights allowed on the material.
  110533. */
  110534. _this.maxSimultaneousLights = 4;
  110535. /**
  110536. * Keep track of the image processing observer to allow dispose and replace.
  110537. */
  110538. _this._imageProcessingObserver = null;
  110539. /**
  110540. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  110541. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  110542. */
  110543. _this.switchToBGR = false;
  110544. // Temp values kept as cache in the material.
  110545. _this._renderTargets = new BABYLON.SmartArray(16);
  110546. _this._reflectionControls = BABYLON.Vector4.Zero();
  110547. _this._white = BABYLON.Color3.White();
  110548. _this._primaryShadowColor = BABYLON.Color3.Black();
  110549. _this._primaryHighlightColor = BABYLON.Color3.Black();
  110550. // Setup the default processing configuration to the scene.
  110551. _this._attachImageProcessingConfiguration(null);
  110552. _this.getRenderTargetTextures = function () {
  110553. _this._renderTargets.reset();
  110554. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  110555. _this._renderTargets.push(_this._diffuseTexture);
  110556. }
  110557. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  110558. _this._renderTargets.push(_this._reflectionTexture);
  110559. }
  110560. return _this._renderTargets;
  110561. };
  110562. return _this;
  110563. }
  110564. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  110565. /**
  110566. * Experimental Internal Use Only.
  110567. *
  110568. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  110569. * This acts as a helper to set the primary color to a more "human friendly" value.
  110570. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  110571. * output color as close as possible from the chosen value.
  110572. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  110573. * part of lighting setup.)
  110574. */
  110575. get: function () {
  110576. return this.__perceptualColor;
  110577. },
  110578. set: function (value) {
  110579. this.__perceptualColor = value;
  110580. this._computePrimaryColorFromPerceptualColor();
  110581. this._markAllSubMeshesAsLightsDirty();
  110582. },
  110583. enumerable: true,
  110584. configurable: true
  110585. });
  110586. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  110587. /**
  110588. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  110589. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  110590. */
  110591. get: function () {
  110592. return this._primaryColorShadowLevel;
  110593. },
  110594. set: function (value) {
  110595. this._primaryColorShadowLevel = value;
  110596. this._computePrimaryColors();
  110597. this._markAllSubMeshesAsLightsDirty();
  110598. },
  110599. enumerable: true,
  110600. configurable: true
  110601. });
  110602. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  110603. /**
  110604. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  110605. * The primary color is used at the level chosen to define what the white area would look.
  110606. */
  110607. get: function () {
  110608. return this._primaryColorHighlightLevel;
  110609. },
  110610. set: function (value) {
  110611. this._primaryColorHighlightLevel = value;
  110612. this._computePrimaryColors();
  110613. this._markAllSubMeshesAsLightsDirty();
  110614. },
  110615. enumerable: true,
  110616. configurable: true
  110617. });
  110618. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  110619. /**
  110620. * Sets the reflection reflectance fresnel values according to the default standard
  110621. * empirically know to work well :-)
  110622. */
  110623. set: function (value) {
  110624. var reflectionWeight = value;
  110625. if (reflectionWeight < 0.5) {
  110626. reflectionWeight = reflectionWeight * 2.0;
  110627. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  110628. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  110629. }
  110630. else {
  110631. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  110632. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  110633. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  110634. }
  110635. },
  110636. enumerable: true,
  110637. configurable: true
  110638. });
  110639. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  110640. /**
  110641. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  110642. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  110643. * Recommended to be keep at 1.0 except for special cases.
  110644. */
  110645. get: function () {
  110646. return this._fovMultiplier;
  110647. },
  110648. set: function (value) {
  110649. if (isNaN(value)) {
  110650. value = 1.0;
  110651. }
  110652. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  110653. },
  110654. enumerable: true,
  110655. configurable: true
  110656. });
  110657. /**
  110658. * Attaches a new image processing configuration to the PBR Material.
  110659. * @param configuration (if null the scene configuration will be use)
  110660. */
  110661. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  110662. var _this = this;
  110663. if (configuration === this._imageProcessingConfiguration) {
  110664. return;
  110665. }
  110666. // Detaches observer.
  110667. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110668. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110669. }
  110670. // Pick the scene configuration if needed.
  110671. if (!configuration) {
  110672. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  110673. }
  110674. else {
  110675. this._imageProcessingConfiguration = configuration;
  110676. }
  110677. // Attaches observer.
  110678. if (this._imageProcessingConfiguration) {
  110679. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  110680. _this._computePrimaryColorFromPerceptualColor();
  110681. _this._markAllSubMeshesAsImageProcessingDirty();
  110682. });
  110683. }
  110684. };
  110685. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  110686. /**
  110687. * Gets the image processing configuration used either in this material.
  110688. */
  110689. get: function () {
  110690. return this._imageProcessingConfiguration;
  110691. },
  110692. /**
  110693. * Sets the Default image processing configuration used either in the this material.
  110694. *
  110695. * If sets to null, the scene one is in use.
  110696. */
  110697. set: function (value) {
  110698. this._attachImageProcessingConfiguration(value);
  110699. // Ensure the effect will be rebuilt.
  110700. this._markAllSubMeshesAsTexturesDirty();
  110701. },
  110702. enumerable: true,
  110703. configurable: true
  110704. });
  110705. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  110706. /**
  110707. * Gets wether the color curves effect is enabled.
  110708. */
  110709. get: function () {
  110710. return this.imageProcessingConfiguration.colorCurvesEnabled;
  110711. },
  110712. /**
  110713. * Sets wether the color curves effect is enabled.
  110714. */
  110715. set: function (value) {
  110716. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  110717. },
  110718. enumerable: true,
  110719. configurable: true
  110720. });
  110721. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  110722. /**
  110723. * Gets wether the color grading effect is enabled.
  110724. */
  110725. get: function () {
  110726. return this.imageProcessingConfiguration.colorGradingEnabled;
  110727. },
  110728. /**
  110729. * Gets wether the color grading effect is enabled.
  110730. */
  110731. set: function (value) {
  110732. this.imageProcessingConfiguration.colorGradingEnabled = value;
  110733. },
  110734. enumerable: true,
  110735. configurable: true
  110736. });
  110737. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  110738. /**
  110739. * Gets wether tonemapping is enabled or not.
  110740. */
  110741. get: function () {
  110742. return this._imageProcessingConfiguration.toneMappingEnabled;
  110743. },
  110744. /**
  110745. * Sets wether tonemapping is enabled or not
  110746. */
  110747. set: function (value) {
  110748. this._imageProcessingConfiguration.toneMappingEnabled = value;
  110749. },
  110750. enumerable: true,
  110751. configurable: true
  110752. });
  110753. ;
  110754. ;
  110755. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  110756. /**
  110757. * The camera exposure used on this material.
  110758. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110759. * This corresponds to a photographic exposure.
  110760. */
  110761. get: function () {
  110762. return this._imageProcessingConfiguration.exposure;
  110763. },
  110764. /**
  110765. * The camera exposure used on this material.
  110766. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110767. * This corresponds to a photographic exposure.
  110768. */
  110769. set: function (value) {
  110770. this._imageProcessingConfiguration.exposure = value;
  110771. },
  110772. enumerable: true,
  110773. configurable: true
  110774. });
  110775. ;
  110776. ;
  110777. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  110778. /**
  110779. * Gets The camera contrast used on this material.
  110780. */
  110781. get: function () {
  110782. return this._imageProcessingConfiguration.contrast;
  110783. },
  110784. /**
  110785. * Sets The camera contrast used on this material.
  110786. */
  110787. set: function (value) {
  110788. this._imageProcessingConfiguration.contrast = value;
  110789. },
  110790. enumerable: true,
  110791. configurable: true
  110792. });
  110793. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  110794. /**
  110795. * Gets the Color Grading 2D Lookup Texture.
  110796. */
  110797. get: function () {
  110798. return this._imageProcessingConfiguration.colorGradingTexture;
  110799. },
  110800. /**
  110801. * Sets the Color Grading 2D Lookup Texture.
  110802. */
  110803. set: function (value) {
  110804. this.imageProcessingConfiguration.colorGradingTexture = value;
  110805. },
  110806. enumerable: true,
  110807. configurable: true
  110808. });
  110809. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  110810. /**
  110811. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110812. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110813. * 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;
  110814. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110815. */
  110816. get: function () {
  110817. return this.imageProcessingConfiguration.colorCurves;
  110818. },
  110819. /**
  110820. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110821. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110822. * 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;
  110823. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110824. */
  110825. set: function (value) {
  110826. this.imageProcessingConfiguration.colorCurves = value;
  110827. },
  110828. enumerable: true,
  110829. configurable: true
  110830. });
  110831. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  110832. /**
  110833. * Gets a boolean indicating that current material needs to register RTT
  110834. */
  110835. get: function () {
  110836. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110837. return true;
  110838. }
  110839. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110840. return true;
  110841. }
  110842. return false;
  110843. },
  110844. enumerable: true,
  110845. configurable: true
  110846. });
  110847. /**
  110848. * The entire material has been created in order to prevent overdraw.
  110849. * @returns false
  110850. */
  110851. BackgroundMaterial.prototype.needAlphaTesting = function () {
  110852. return true;
  110853. };
  110854. /**
  110855. * The entire material has been created in order to prevent overdraw.
  110856. * @returns true if blending is enable
  110857. */
  110858. BackgroundMaterial.prototype.needAlphaBlending = function () {
  110859. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  110860. };
  110861. /**
  110862. * Checks wether the material is ready to be rendered for a given mesh.
  110863. * @param mesh The mesh to render
  110864. * @param subMesh The submesh to check against
  110865. * @param useInstances Specify wether or not the material is used with instances
  110866. * @returns true if all the dependencies are ready (Textures, Effects...)
  110867. */
  110868. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  110869. var _this = this;
  110870. if (useInstances === void 0) { useInstances = false; }
  110871. if (subMesh.effect && this.isFrozen) {
  110872. if (this._wasPreviouslyReady) {
  110873. return true;
  110874. }
  110875. }
  110876. if (!subMesh._materialDefines) {
  110877. subMesh._materialDefines = new BackgroundMaterialDefines();
  110878. }
  110879. var scene = this.getScene();
  110880. var defines = subMesh._materialDefines;
  110881. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  110882. if (defines._renderId === scene.getRenderId()) {
  110883. return true;
  110884. }
  110885. }
  110886. var engine = scene.getEngine();
  110887. // Lights
  110888. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  110889. defines._needNormals = true;
  110890. // Textures
  110891. if (defines._areTexturesDirty) {
  110892. defines._needUVs = false;
  110893. if (scene.texturesEnabled) {
  110894. if (scene.getEngine().getCaps().textureLOD) {
  110895. defines.TEXTURELODSUPPORT = true;
  110896. }
  110897. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110898. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  110899. return false;
  110900. }
  110901. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  110902. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  110903. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  110904. defines.OPACITYFRESNEL = this._opacityFresnel;
  110905. }
  110906. else {
  110907. defines.DIFFUSE = false;
  110908. defines.DIFFUSEHASALPHA = false;
  110909. defines.GAMMADIFFUSE = false;
  110910. defines.OPACITYFRESNEL = false;
  110911. }
  110912. var reflectionTexture = this._reflectionTexture;
  110913. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110914. if (!reflectionTexture.isReadyOrNotBlocking()) {
  110915. return false;
  110916. }
  110917. defines.REFLECTION = true;
  110918. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  110919. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  110920. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  110921. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  110922. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  110923. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  110924. defines.REFLECTIONBGR = this.switchToBGR;
  110925. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  110926. defines.INVERTCUBICMAP = true;
  110927. }
  110928. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  110929. switch (reflectionTexture.coordinatesMode) {
  110930. case BABYLON.Texture.EXPLICIT_MODE:
  110931. defines.REFLECTIONMAP_EXPLICIT = true;
  110932. break;
  110933. case BABYLON.Texture.PLANAR_MODE:
  110934. defines.REFLECTIONMAP_PLANAR = true;
  110935. break;
  110936. case BABYLON.Texture.PROJECTION_MODE:
  110937. defines.REFLECTIONMAP_PROJECTION = true;
  110938. break;
  110939. case BABYLON.Texture.SKYBOX_MODE:
  110940. defines.REFLECTIONMAP_SKYBOX = true;
  110941. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  110942. break;
  110943. case BABYLON.Texture.SPHERICAL_MODE:
  110944. defines.REFLECTIONMAP_SPHERICAL = true;
  110945. break;
  110946. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  110947. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  110948. break;
  110949. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  110950. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  110951. break;
  110952. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  110953. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  110954. break;
  110955. case BABYLON.Texture.CUBIC_MODE:
  110956. case BABYLON.Texture.INVCUBIC_MODE:
  110957. default:
  110958. defines.REFLECTIONMAP_CUBIC = true;
  110959. break;
  110960. }
  110961. if (this.reflectionFresnel) {
  110962. defines.REFLECTIONFRESNEL = true;
  110963. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  110964. this._reflectionControls.x = this.reflectionAmount;
  110965. this._reflectionControls.y = this.reflectionReflectance0;
  110966. this._reflectionControls.z = this.reflectionReflectance90;
  110967. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  110968. }
  110969. else {
  110970. defines.REFLECTIONFRESNEL = false;
  110971. defines.REFLECTIONFALLOFF = false;
  110972. }
  110973. }
  110974. else {
  110975. defines.REFLECTION = false;
  110976. defines.REFLECTIONFRESNEL = false;
  110977. defines.REFLECTIONFALLOFF = false;
  110978. defines.REFLECTIONBLUR = false;
  110979. defines.REFLECTIONMAP_3D = false;
  110980. defines.REFLECTIONMAP_SPHERICAL = false;
  110981. defines.REFLECTIONMAP_PLANAR = false;
  110982. defines.REFLECTIONMAP_CUBIC = false;
  110983. defines.REFLECTIONMAP_PROJECTION = false;
  110984. defines.REFLECTIONMAP_SKYBOX = false;
  110985. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110986. defines.REFLECTIONMAP_EXPLICIT = false;
  110987. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110988. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110989. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110990. defines.INVERTCUBICMAP = false;
  110991. defines.REFLECTIONMAP_OPPOSITEZ = false;
  110992. defines.LODINREFLECTIONALPHA = false;
  110993. defines.GAMMAREFLECTION = false;
  110994. defines.RGBDREFLECTION = false;
  110995. }
  110996. }
  110997. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  110998. defines.USERGBCOLOR = this._useRGBColor;
  110999. defines.NOISE = this._enableNoise;
  111000. }
  111001. if (defines._areLightsDirty) {
  111002. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  111003. }
  111004. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  111005. if (!this._imageProcessingConfiguration.isReady()) {
  111006. return false;
  111007. }
  111008. this._imageProcessingConfiguration.prepareDefines(defines);
  111009. }
  111010. // Misc.
  111011. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  111012. // Values that need to be evaluated on every frame
  111013. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  111014. // Attribs
  111015. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  111016. if (mesh) {
  111017. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  111018. mesh.createNormals(true);
  111019. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  111020. }
  111021. }
  111022. }
  111023. // Get correct effect
  111024. if (defines.isDirty) {
  111025. defines.markAsProcessed();
  111026. scene.resetCachedMaterial();
  111027. // Fallbacks
  111028. var fallbacks = new BABYLON.EffectFallbacks();
  111029. if (defines.FOG) {
  111030. fallbacks.addFallback(0, "FOG");
  111031. }
  111032. if (defines.POINTSIZE) {
  111033. fallbacks.addFallback(1, "POINTSIZE");
  111034. }
  111035. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  111036. if (defines.NUM_BONE_INFLUENCERS > 0) {
  111037. fallbacks.addCPUSkinningFallback(0, mesh);
  111038. }
  111039. //Attributes
  111040. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111041. if (defines.NORMAL) {
  111042. attribs.push(BABYLON.VertexBuffer.NormalKind);
  111043. }
  111044. if (defines.UV1) {
  111045. attribs.push(BABYLON.VertexBuffer.UVKind);
  111046. }
  111047. if (defines.UV2) {
  111048. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111049. }
  111050. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  111051. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  111052. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  111053. "vFogInfos", "vFogColor", "pointSize",
  111054. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  111055. "vPrimaryColor", "vPrimaryColorShadow",
  111056. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  111057. "shadowLevel", "alpha",
  111058. "vBackgroundCenter", "vReflectionControl",
  111059. "vDiffuseInfos", "diffuseMatrix",
  111060. ];
  111061. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  111062. var uniformBuffers = ["Material", "Scene"];
  111063. if (BABYLON.ImageProcessingConfiguration) {
  111064. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  111065. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  111066. }
  111067. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  111068. uniformsNames: uniforms,
  111069. uniformBuffersNames: uniformBuffers,
  111070. samplers: samplers,
  111071. defines: defines,
  111072. maxSimultaneousLights: this._maxSimultaneousLights
  111073. });
  111074. var onCompiled = function (effect) {
  111075. if (_this.onCompiled) {
  111076. _this.onCompiled(effect);
  111077. }
  111078. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  111079. };
  111080. var join = defines.toString();
  111081. subMesh.setEffect(scene.getEngine().createEffect("background", {
  111082. attributes: attribs,
  111083. uniformsNames: uniforms,
  111084. uniformBuffersNames: uniformBuffers,
  111085. samplers: samplers,
  111086. defines: join,
  111087. fallbacks: fallbacks,
  111088. onCompiled: onCompiled,
  111089. onError: this.onError,
  111090. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  111091. }, engine), defines);
  111092. this.buildUniformLayout();
  111093. }
  111094. if (!subMesh.effect || !subMesh.effect.isReady()) {
  111095. return false;
  111096. }
  111097. defines._renderId = scene.getRenderId();
  111098. this._wasPreviouslyReady = true;
  111099. return true;
  111100. };
  111101. /**
  111102. * Compute the primary color according to the chosen perceptual color.
  111103. */
  111104. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  111105. if (!this.__perceptualColor) {
  111106. return;
  111107. }
  111108. this._primaryColor.copyFrom(this.__perceptualColor);
  111109. // Revert gamma space.
  111110. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  111111. // Revert image processing configuration.
  111112. if (this._imageProcessingConfiguration) {
  111113. // Revert Exposure.
  111114. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  111115. }
  111116. this._computePrimaryColors();
  111117. };
  111118. /**
  111119. * Compute the highlights and shadow colors according to their chosen levels.
  111120. */
  111121. BackgroundMaterial.prototype._computePrimaryColors = function () {
  111122. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  111123. return;
  111124. }
  111125. // Find the highlight color based on the configuration.
  111126. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  111127. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  111128. // Find the shadow color based on the configuration.
  111129. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  111130. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  111131. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  111132. };
  111133. /**
  111134. * Build the uniform buffer used in the material.
  111135. */
  111136. BackgroundMaterial.prototype.buildUniformLayout = function () {
  111137. // Order is important !
  111138. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  111139. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  111140. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  111141. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  111142. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  111143. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  111144. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  111145. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  111146. this._uniformBuffer.addUniform("pointSize", 1);
  111147. this._uniformBuffer.addUniform("shadowLevel", 1);
  111148. this._uniformBuffer.addUniform("alpha", 1);
  111149. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  111150. this._uniformBuffer.addUniform("vReflectionControl", 4);
  111151. this._uniformBuffer.create();
  111152. };
  111153. /**
  111154. * Unbind the material.
  111155. */
  111156. BackgroundMaterial.prototype.unbind = function () {
  111157. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111158. this._uniformBuffer.setTexture("diffuseSampler", null);
  111159. }
  111160. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111161. this._uniformBuffer.setTexture("reflectionSampler", null);
  111162. }
  111163. _super.prototype.unbind.call(this);
  111164. };
  111165. /**
  111166. * Bind only the world matrix to the material.
  111167. * @param world The world matrix to bind.
  111168. */
  111169. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  111170. this._activeEffect.setMatrix("world", world);
  111171. };
  111172. /**
  111173. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  111174. * @param world The world matrix to bind.
  111175. * @param subMesh The submesh to bind for.
  111176. */
  111177. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  111178. var scene = this.getScene();
  111179. var defines = subMesh._materialDefines;
  111180. if (!defines) {
  111181. return;
  111182. }
  111183. var effect = subMesh.effect;
  111184. if (!effect) {
  111185. return;
  111186. }
  111187. this._activeEffect = effect;
  111188. // Matrices
  111189. this.bindOnlyWorldMatrix(world);
  111190. // Bones
  111191. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  111192. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  111193. if (mustRebind) {
  111194. this._uniformBuffer.bindToEffect(effect, "Material");
  111195. this.bindViewProjection(effect);
  111196. var reflectionTexture = this._reflectionTexture;
  111197. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  111198. // Texture uniforms
  111199. if (scene.texturesEnabled) {
  111200. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111201. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  111202. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  111203. }
  111204. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111205. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  111206. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  111207. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  111208. }
  111209. }
  111210. if (this.shadowLevel > 0) {
  111211. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  111212. }
  111213. this._uniformBuffer.updateFloat("alpha", this.alpha);
  111214. // Point size
  111215. if (this.pointsCloud) {
  111216. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  111217. }
  111218. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  111219. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  111220. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  111221. }
  111222. else {
  111223. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  111224. }
  111225. }
  111226. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  111227. // Textures
  111228. if (scene.texturesEnabled) {
  111229. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111230. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  111231. }
  111232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111233. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  111234. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111235. }
  111236. else if (!defines.REFLECTIONBLUR) {
  111237. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111238. }
  111239. else {
  111240. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  111241. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  111242. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  111243. }
  111244. if (defines.REFLECTIONFRESNEL) {
  111245. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  111246. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  111247. }
  111248. }
  111249. }
  111250. // Clip plane
  111251. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  111252. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  111253. }
  111254. if (mustRebind || !this.isFrozen) {
  111255. if (scene.lightsEnabled) {
  111256. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  111257. }
  111258. // View
  111259. this.bindView(effect);
  111260. // Fog
  111261. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  111262. // image processing
  111263. if (this._imageProcessingConfiguration) {
  111264. this._imageProcessingConfiguration.bind(this._activeEffect);
  111265. }
  111266. }
  111267. this._uniformBuffer.update();
  111268. this._afterBind(mesh, this._activeEffect);
  111269. };
  111270. /**
  111271. * Dispose the material.
  111272. * @param forceDisposeEffect Force disposal of the associated effect.
  111273. * @param forceDisposeTextures Force disposal of the associated textures.
  111274. */
  111275. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  111276. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  111277. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  111278. if (forceDisposeTextures) {
  111279. if (this.diffuseTexture) {
  111280. this.diffuseTexture.dispose();
  111281. }
  111282. if (this.reflectionTexture) {
  111283. this.reflectionTexture.dispose();
  111284. }
  111285. }
  111286. this._renderTargets.dispose();
  111287. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111288. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111289. }
  111290. _super.prototype.dispose.call(this, forceDisposeEffect);
  111291. };
  111292. /**
  111293. * Clones the material.
  111294. * @param name The cloned name.
  111295. * @returns The cloned material.
  111296. */
  111297. BackgroundMaterial.prototype.clone = function (name) {
  111298. var _this = this;
  111299. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  111300. };
  111301. /**
  111302. * Serializes the current material to its JSON representation.
  111303. * @returns The JSON representation.
  111304. */
  111305. BackgroundMaterial.prototype.serialize = function () {
  111306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111307. serializationObject.customType = "BABYLON.BackgroundMaterial";
  111308. return serializationObject;
  111309. };
  111310. /**
  111311. * Gets the class name of the material
  111312. * @returns "BackgroundMaterial"
  111313. */
  111314. BackgroundMaterial.prototype.getClassName = function () {
  111315. return "BackgroundMaterial";
  111316. };
  111317. /**
  111318. * Parse a JSON input to create back a background material.
  111319. * @param source The JSON data to parse
  111320. * @param scene The scene to create the parsed material in
  111321. * @param rootUrl The root url of the assets the material depends upon
  111322. * @returns the instantiated BackgroundMaterial.
  111323. */
  111324. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  111325. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  111326. };
  111327. /**
  111328. * Standard reflectance value at parallel view angle.
  111329. */
  111330. BackgroundMaterial.StandardReflectance0 = 0.05;
  111331. /**
  111332. * Standard reflectance value at grazing angle.
  111333. */
  111334. BackgroundMaterial.StandardReflectance90 = 0.5;
  111335. __decorate([
  111336. BABYLON.serializeAsColor3()
  111337. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  111338. __decorate([
  111339. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111340. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  111341. __decorate([
  111342. BABYLON.serializeAsColor3()
  111343. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  111344. __decorate([
  111345. BABYLON.serialize()
  111346. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  111347. __decorate([
  111348. BABYLON.serialize()
  111349. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  111350. __decorate([
  111351. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111352. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  111353. __decorate([
  111354. BABYLON.serializeAsTexture()
  111355. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  111356. __decorate([
  111357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111358. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  111359. __decorate([
  111360. BABYLON.serialize()
  111361. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  111362. __decorate([
  111363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111364. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  111365. __decorate([
  111366. BABYLON.serializeAsTexture()
  111367. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  111368. __decorate([
  111369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111370. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  111371. __decorate([
  111372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111373. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  111374. __decorate([
  111375. BABYLON.serialize()
  111376. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  111377. __decorate([
  111378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111379. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  111380. __decorate([
  111381. BABYLON.serializeAsVector3()
  111382. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  111383. __decorate([
  111384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111385. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  111386. __decorate([
  111387. BABYLON.serialize()
  111388. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  111389. __decorate([
  111390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111391. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  111392. __decorate([
  111393. BABYLON.serialize()
  111394. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  111395. __decorate([
  111396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111397. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  111398. __decorate([
  111399. BABYLON.serialize()
  111400. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  111401. __decorate([
  111402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111403. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  111404. __decorate([
  111405. BABYLON.serialize()
  111406. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  111407. __decorate([
  111408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111409. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  111410. __decorate([
  111411. BABYLON.serialize()
  111412. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  111413. __decorate([
  111414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111415. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  111416. __decorate([
  111417. BABYLON.serialize()
  111418. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  111419. __decorate([
  111420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111421. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  111422. __decorate([
  111423. BABYLON.serialize()
  111424. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  111425. __decorate([
  111426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111427. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  111428. __decorate([
  111429. BABYLON.serialize()
  111430. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  111431. __decorate([
  111432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111433. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  111434. __decorate([
  111435. BABYLON.serialize()
  111436. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  111437. __decorate([
  111438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111439. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  111440. __decorate([
  111441. BABYLON.serializeAsImageProcessingConfiguration()
  111442. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  111443. return BackgroundMaterial;
  111444. }(BABYLON.PushMaterial));
  111445. BABYLON.BackgroundMaterial = BackgroundMaterial;
  111446. })(BABYLON || (BABYLON = {}));
  111447. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  111448. var __assign = (this && this.__assign) || function () {
  111449. __assign = Object.assign || function(t) {
  111450. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111451. s = arguments[i];
  111452. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111453. t[p] = s[p];
  111454. }
  111455. return t;
  111456. };
  111457. return __assign.apply(this, arguments);
  111458. };
  111459. var BABYLON;
  111460. (function (BABYLON) {
  111461. /**
  111462. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  111463. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  111464. * It also helps with the default setup of your imageProcessing configuration.
  111465. */
  111466. var EnvironmentHelper = /** @class */ (function () {
  111467. /**
  111468. * constructor
  111469. * @param options
  111470. * @param scene The scene to add the material to
  111471. */
  111472. function EnvironmentHelper(options, scene) {
  111473. var _this = this;
  111474. this._errorHandler = function (message, exception) {
  111475. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  111476. };
  111477. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  111478. this._scene = scene;
  111479. this.onErrorObservable = new BABYLON.Observable();
  111480. this._setupBackground();
  111481. this._setupImageProcessing();
  111482. }
  111483. /**
  111484. * Creates the default options for the helper.
  111485. */
  111486. EnvironmentHelper._getDefaultOptions = function () {
  111487. return {
  111488. createGround: true,
  111489. groundSize: 15,
  111490. groundTexture: this._groundTextureCDNUrl,
  111491. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111492. groundOpacity: 0.9,
  111493. enableGroundShadow: true,
  111494. groundShadowLevel: 0.5,
  111495. enableGroundMirror: false,
  111496. groundMirrorSizeRatio: 0.3,
  111497. groundMirrorBlurKernel: 64,
  111498. groundMirrorAmount: 1,
  111499. groundMirrorFresnelWeight: 1,
  111500. groundMirrorFallOffDistance: 0,
  111501. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  111502. groundYBias: 0.00001,
  111503. createSkybox: true,
  111504. skyboxSize: 20,
  111505. skyboxTexture: this._skyboxTextureCDNUrl,
  111506. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111507. backgroundYRotation: 0,
  111508. sizeAuto: true,
  111509. rootPosition: BABYLON.Vector3.Zero(),
  111510. setupImageProcessing: true,
  111511. environmentTexture: this._environmentTextureCDNUrl,
  111512. cameraExposure: 0.8,
  111513. cameraContrast: 1.2,
  111514. toneMappingEnabled: true,
  111515. };
  111516. };
  111517. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  111518. /**
  111519. * Gets the root mesh created by the helper.
  111520. */
  111521. get: function () {
  111522. return this._rootMesh;
  111523. },
  111524. enumerable: true,
  111525. configurable: true
  111526. });
  111527. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  111528. /**
  111529. * Gets the skybox created by the helper.
  111530. */
  111531. get: function () {
  111532. return this._skybox;
  111533. },
  111534. enumerable: true,
  111535. configurable: true
  111536. });
  111537. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  111538. /**
  111539. * Gets the skybox texture created by the helper.
  111540. */
  111541. get: function () {
  111542. return this._skyboxTexture;
  111543. },
  111544. enumerable: true,
  111545. configurable: true
  111546. });
  111547. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  111548. /**
  111549. * Gets the skybox material created by the helper.
  111550. */
  111551. get: function () {
  111552. return this._skyboxMaterial;
  111553. },
  111554. enumerable: true,
  111555. configurable: true
  111556. });
  111557. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  111558. /**
  111559. * Gets the ground mesh created by the helper.
  111560. */
  111561. get: function () {
  111562. return this._ground;
  111563. },
  111564. enumerable: true,
  111565. configurable: true
  111566. });
  111567. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  111568. /**
  111569. * Gets the ground texture created by the helper.
  111570. */
  111571. get: function () {
  111572. return this._groundTexture;
  111573. },
  111574. enumerable: true,
  111575. configurable: true
  111576. });
  111577. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  111578. /**
  111579. * Gets the ground mirror created by the helper.
  111580. */
  111581. get: function () {
  111582. return this._groundMirror;
  111583. },
  111584. enumerable: true,
  111585. configurable: true
  111586. });
  111587. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  111588. /**
  111589. * Gets the ground mirror render list to helps pushing the meshes
  111590. * you wish in the ground reflection.
  111591. */
  111592. get: function () {
  111593. if (this._groundMirror) {
  111594. return this._groundMirror.renderList;
  111595. }
  111596. return null;
  111597. },
  111598. enumerable: true,
  111599. configurable: true
  111600. });
  111601. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  111602. /**
  111603. * Gets the ground material created by the helper.
  111604. */
  111605. get: function () {
  111606. return this._groundMaterial;
  111607. },
  111608. enumerable: true,
  111609. configurable: true
  111610. });
  111611. /**
  111612. * Updates the background according to the new options
  111613. * @param options
  111614. */
  111615. EnvironmentHelper.prototype.updateOptions = function (options) {
  111616. var newOptions = __assign({}, this._options, options);
  111617. if (this._ground && !newOptions.createGround) {
  111618. this._ground.dispose();
  111619. this._ground = null;
  111620. }
  111621. if (this._groundMaterial && !newOptions.createGround) {
  111622. this._groundMaterial.dispose();
  111623. this._groundMaterial = null;
  111624. }
  111625. if (this._groundTexture) {
  111626. if (this._options.groundTexture != newOptions.groundTexture) {
  111627. this._groundTexture.dispose();
  111628. this._groundTexture = null;
  111629. }
  111630. }
  111631. if (this._skybox && !newOptions.createSkybox) {
  111632. this._skybox.dispose();
  111633. this._skybox = null;
  111634. }
  111635. if (this._skyboxMaterial && !newOptions.createSkybox) {
  111636. this._skyboxMaterial.dispose();
  111637. this._skyboxMaterial = null;
  111638. }
  111639. if (this._skyboxTexture) {
  111640. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  111641. this._skyboxTexture.dispose();
  111642. this._skyboxTexture = null;
  111643. }
  111644. }
  111645. if (this._groundMirror && !newOptions.enableGroundMirror) {
  111646. this._groundMirror.dispose();
  111647. this._groundMirror = null;
  111648. }
  111649. if (this._scene.environmentTexture) {
  111650. if (this._options.environmentTexture != newOptions.environmentTexture) {
  111651. this._scene.environmentTexture.dispose();
  111652. }
  111653. }
  111654. this._options = newOptions;
  111655. this._setupBackground();
  111656. this._setupImageProcessing();
  111657. };
  111658. /**
  111659. * Sets the primary color of all the available elements.
  111660. * @param color the main color to affect to the ground and the background
  111661. */
  111662. EnvironmentHelper.prototype.setMainColor = function (color) {
  111663. if (this.groundMaterial) {
  111664. this.groundMaterial.primaryColor = color;
  111665. }
  111666. if (this.skyboxMaterial) {
  111667. this.skyboxMaterial.primaryColor = color;
  111668. }
  111669. if (this.groundMirror) {
  111670. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  111671. }
  111672. };
  111673. /**
  111674. * Setup the image processing according to the specified options.
  111675. */
  111676. EnvironmentHelper.prototype._setupImageProcessing = function () {
  111677. if (this._options.setupImageProcessing) {
  111678. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  111679. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  111680. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  111681. this._setupEnvironmentTexture();
  111682. }
  111683. };
  111684. /**
  111685. * Setup the environment texture according to the specified options.
  111686. */
  111687. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  111688. if (this._scene.environmentTexture) {
  111689. return;
  111690. }
  111691. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  111692. this._scene.environmentTexture = this._options.environmentTexture;
  111693. return;
  111694. }
  111695. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  111696. this._scene.environmentTexture = environmentTexture;
  111697. };
  111698. /**
  111699. * Setup the background according to the specified options.
  111700. */
  111701. EnvironmentHelper.prototype._setupBackground = function () {
  111702. if (!this._rootMesh) {
  111703. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  111704. }
  111705. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  111706. var sceneSize = this._getSceneSize();
  111707. if (this._options.createGround) {
  111708. this._setupGround(sceneSize);
  111709. this._setupGroundMaterial();
  111710. this._setupGroundDiffuseTexture();
  111711. if (this._options.enableGroundMirror) {
  111712. this._setupGroundMirrorTexture(sceneSize);
  111713. }
  111714. this._setupMirrorInGroundMaterial();
  111715. }
  111716. if (this._options.createSkybox) {
  111717. this._setupSkybox(sceneSize);
  111718. this._setupSkyboxMaterial();
  111719. this._setupSkyboxReflectionTexture();
  111720. }
  111721. this._rootMesh.position.x = sceneSize.rootPosition.x;
  111722. this._rootMesh.position.z = sceneSize.rootPosition.z;
  111723. this._rootMesh.position.y = sceneSize.rootPosition.y;
  111724. };
  111725. /**
  111726. * Get the scene sizes according to the setup.
  111727. */
  111728. EnvironmentHelper.prototype._getSceneSize = function () {
  111729. var _this = this;
  111730. var groundSize = this._options.groundSize;
  111731. var skyboxSize = this._options.skyboxSize;
  111732. var rootPosition = this._options.rootPosition;
  111733. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  111734. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111735. }
  111736. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  111737. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  111738. });
  111739. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111740. if (this._options.sizeAuto) {
  111741. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  111742. this._scene.activeCamera.upperRadiusLimit) {
  111743. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  111744. skyboxSize = groundSize;
  111745. }
  111746. var sceneDiagonalLenght = sceneDiagonal.length();
  111747. if (sceneDiagonalLenght > groundSize) {
  111748. groundSize = sceneDiagonalLenght * 2;
  111749. skyboxSize = groundSize;
  111750. }
  111751. // 10 % bigger.
  111752. groundSize *= 1.1;
  111753. skyboxSize *= 1.5;
  111754. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  111755. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  111756. }
  111757. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111758. };
  111759. /**
  111760. * Setup the ground according to the specified options.
  111761. */
  111762. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  111763. var _this = this;
  111764. if (!this._ground || this._ground.isDisposed()) {
  111765. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  111766. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  111767. this._ground.parent = this._rootMesh;
  111768. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  111769. }
  111770. this._ground.receiveShadows = this._options.enableGroundShadow;
  111771. };
  111772. /**
  111773. * Setup the ground material according to the specified options.
  111774. */
  111775. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  111776. if (!this._groundMaterial) {
  111777. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  111778. }
  111779. this._groundMaterial.alpha = this._options.groundOpacity;
  111780. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111781. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  111782. this._groundMaterial.primaryColor = this._options.groundColor;
  111783. this._groundMaterial.useRGBColor = false;
  111784. this._groundMaterial.enableNoise = true;
  111785. if (this._ground) {
  111786. this._ground.material = this._groundMaterial;
  111787. }
  111788. };
  111789. /**
  111790. * Setup the ground diffuse texture according to the specified options.
  111791. */
  111792. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  111793. if (!this._groundMaterial) {
  111794. return;
  111795. }
  111796. if (this._groundTexture) {
  111797. return;
  111798. }
  111799. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  111800. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  111801. return;
  111802. }
  111803. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111804. diffuseTexture.gammaSpace = false;
  111805. diffuseTexture.hasAlpha = true;
  111806. this._groundMaterial.diffuseTexture = diffuseTexture;
  111807. };
  111808. /**
  111809. * Setup the ground mirror texture according to the specified options.
  111810. */
  111811. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  111812. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111813. if (!this._groundMirror) {
  111814. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  111815. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  111816. this._groundMirror.anisotropicFilteringLevel = 1;
  111817. this._groundMirror.wrapU = wrapping;
  111818. this._groundMirror.wrapV = wrapping;
  111819. this._groundMirror.gammaSpace = false;
  111820. if (this._groundMirror.renderList) {
  111821. for (var i = 0; i < this._scene.meshes.length; i++) {
  111822. var mesh = this._scene.meshes[i];
  111823. if (mesh !== this._ground &&
  111824. mesh !== this._skybox &&
  111825. mesh !== this._rootMesh) {
  111826. this._groundMirror.renderList.push(mesh);
  111827. }
  111828. }
  111829. }
  111830. }
  111831. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  111832. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  111833. };
  111834. /**
  111835. * Setup the ground to receive the mirror texture.
  111836. */
  111837. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  111838. if (this._groundMaterial) {
  111839. this._groundMaterial.reflectionTexture = this._groundMirror;
  111840. this._groundMaterial.reflectionFresnel = true;
  111841. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  111842. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  111843. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  111844. }
  111845. };
  111846. /**
  111847. * Setup the skybox according to the specified options.
  111848. */
  111849. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  111850. var _this = this;
  111851. if (!this._skybox || this._skybox.isDisposed()) {
  111852. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  111853. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  111854. }
  111855. this._skybox.parent = this._rootMesh;
  111856. };
  111857. /**
  111858. * Setup the skybox material according to the specified options.
  111859. */
  111860. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  111861. if (!this._skybox) {
  111862. return;
  111863. }
  111864. if (!this._skyboxMaterial) {
  111865. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  111866. }
  111867. this._skyboxMaterial.useRGBColor = false;
  111868. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  111869. this._skyboxMaterial.enableNoise = true;
  111870. this._skybox.material = this._skyboxMaterial;
  111871. };
  111872. /**
  111873. * Setup the skybox reflection texture according to the specified options.
  111874. */
  111875. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  111876. if (!this._skyboxMaterial) {
  111877. return;
  111878. }
  111879. if (this._skyboxTexture) {
  111880. return;
  111881. }
  111882. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  111883. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  111884. return;
  111885. }
  111886. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111887. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111888. this._skyboxTexture.gammaSpace = false;
  111889. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  111890. };
  111891. /**
  111892. * Dispose all the elements created by the Helper.
  111893. */
  111894. EnvironmentHelper.prototype.dispose = function () {
  111895. if (this._groundMaterial) {
  111896. this._groundMaterial.dispose(true, true);
  111897. }
  111898. if (this._skyboxMaterial) {
  111899. this._skyboxMaterial.dispose(true, true);
  111900. }
  111901. this._rootMesh.dispose(false);
  111902. };
  111903. /**
  111904. * Default ground texture URL.
  111905. */
  111906. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  111907. /**
  111908. * Default skybox texture URL.
  111909. */
  111910. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  111911. /**
  111912. * Default environment texture URL.
  111913. */
  111914. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  111915. return EnvironmentHelper;
  111916. }());
  111917. BABYLON.EnvironmentHelper = EnvironmentHelper;
  111918. })(BABYLON || (BABYLON = {}));
  111919. //# sourceMappingURL=babylon.environmentHelper.js.map
  111920. var BABYLON;
  111921. (function (BABYLON) {
  111922. /** Internal class used to store shapes for emitters */
  111923. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  111924. function ParticleSystemSetEmitterCreationOptions() {
  111925. }
  111926. return ParticleSystemSetEmitterCreationOptions;
  111927. }());
  111928. /**
  111929. * Represents a set of particle systems working together to create a specific effect
  111930. */
  111931. var ParticleSystemSet = /** @class */ (function () {
  111932. function ParticleSystemSet() {
  111933. /**
  111934. * Gets the particle system list
  111935. */
  111936. this.systems = new Array();
  111937. }
  111938. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  111939. /**
  111940. * Gets the emitter node used with this set
  111941. */
  111942. get: function () {
  111943. return this._emitterNode;
  111944. },
  111945. enumerable: true,
  111946. configurable: true
  111947. });
  111948. /**
  111949. * Creates a new emitter mesh as a sphere
  111950. * @param options defines the options used to create the sphere
  111951. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  111952. * @param scene defines the hosting scene
  111953. */
  111954. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  111955. if (this._emitterNode) {
  111956. this._emitterNode.dispose();
  111957. }
  111958. this._emitterCreationOptions = {
  111959. kind: "Sphere",
  111960. options: options,
  111961. renderingGroupId: renderingGroupId
  111962. };
  111963. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  111964. emitterMesh.renderingGroupId = renderingGroupId;
  111965. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  111966. material.emissiveColor = options.color;
  111967. emitterMesh.material = material;
  111968. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111969. var system = _a[_i];
  111970. system.emitter = emitterMesh;
  111971. }
  111972. this._emitterNode = emitterMesh;
  111973. };
  111974. /**
  111975. * Starts all particle systems of the set
  111976. * @param emitter defines an optional mesh to use as emitter for the particle systems
  111977. */
  111978. ParticleSystemSet.prototype.start = function (emitter) {
  111979. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111980. var system = _a[_i];
  111981. if (emitter) {
  111982. system.emitter = emitter;
  111983. }
  111984. system.start();
  111985. }
  111986. };
  111987. /**
  111988. * Release all associated resources
  111989. */
  111990. ParticleSystemSet.prototype.dispose = function () {
  111991. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111992. var system = _a[_i];
  111993. system.dispose();
  111994. }
  111995. this.systems = [];
  111996. if (this._emitterNode) {
  111997. this._emitterNode.dispose();
  111998. this._emitterNode = null;
  111999. }
  112000. };
  112001. /**
  112002. * Serialize the set into a JSON compatible object
  112003. * @returns a JSON compatible representation of the set
  112004. */
  112005. ParticleSystemSet.prototype.serialize = function () {
  112006. var result = {};
  112007. result.systems = [];
  112008. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112009. var system = _a[_i];
  112010. result.systems.push(system.serialize());
  112011. }
  112012. if (this._emitterNode) {
  112013. result.emitter = this._emitterCreationOptions;
  112014. }
  112015. return result;
  112016. };
  112017. /**
  112018. * Parse a new ParticleSystemSet from a serialized source
  112019. * @param data defines a JSON compatible representation of the set
  112020. * @param scene defines the hosting scene
  112021. * @param gpu defines if we want GPU particles or CPU particles
  112022. * @returns a new ParticleSystemSet
  112023. */
  112024. ParticleSystemSet.Parse = function (data, scene, gpu) {
  112025. if (gpu === void 0) { gpu = false; }
  112026. var result = new ParticleSystemSet();
  112027. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  112028. scene = scene || BABYLON.Engine.LastCreatedScene;
  112029. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  112030. var system = _a[_i];
  112031. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  112032. }
  112033. if (data.emitter) {
  112034. var options = data.emitter.options;
  112035. switch (data.emitter.kind) {
  112036. case "Sphere":
  112037. result.setEmitterAsSphere({
  112038. diameter: options.diameter,
  112039. segments: options.segments,
  112040. color: BABYLON.Color3.FromArray(options.color)
  112041. }, data.emitter.renderingGroupId, scene);
  112042. break;
  112043. }
  112044. }
  112045. return result;
  112046. };
  112047. return ParticleSystemSet;
  112048. }());
  112049. BABYLON.ParticleSystemSet = ParticleSystemSet;
  112050. })(BABYLON || (BABYLON = {}));
  112051. //# sourceMappingURL=babylon.particleSystemSet.js.map
  112052. var BABYLON;
  112053. (function (BABYLON) {
  112054. /**
  112055. * This class is made for on one-liner static method to help creating particle system set.
  112056. */
  112057. var ParticleHelper = /** @class */ (function () {
  112058. function ParticleHelper() {
  112059. }
  112060. /**
  112061. * Create a default particle system that you can tweak
  112062. * @param emitter defines the emitter to use
  112063. * @param capacity defines the system capacity (default is 500 particles)
  112064. * @param scene defines the hosting scene
  112065. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  112066. * @returns the new Particle system
  112067. */
  112068. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  112069. if (capacity === void 0) { capacity = 500; }
  112070. if (useGPU === void 0) { useGPU = false; }
  112071. var system;
  112072. if (useGPU) {
  112073. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  112074. }
  112075. else {
  112076. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  112077. }
  112078. system.emitter = emitter;
  112079. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  112080. system.createConeEmitter(0.1, Math.PI / 4);
  112081. // Particle color
  112082. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112083. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112084. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  112085. // Particle Size
  112086. system.minSize = 0.1;
  112087. system.maxSize = 0.1;
  112088. // Emission speed
  112089. system.minEmitPower = 2;
  112090. system.maxEmitPower = 2;
  112091. // Update speed
  112092. system.updateSpeed = 1 / 60;
  112093. system.emitRate = 30;
  112094. return system;
  112095. };
  112096. /**
  112097. * This is the main static method (one-liner) of this helper to create different particle systems
  112098. * @param type This string represents the type to the particle system to create
  112099. * @param scene The scene where the particle system should live
  112100. * @param gpu If the system will use gpu
  112101. * @returns the ParticleSystemSet created
  112102. */
  112103. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  112104. if (gpu === void 0) { gpu = false; }
  112105. if (!scene) {
  112106. scene = BABYLON.Engine.LastCreatedScene;
  112107. ;
  112108. }
  112109. var token = {};
  112110. scene._addPendingData(token);
  112111. return new Promise(function (resolve, reject) {
  112112. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  112113. scene._removePendingData(token);
  112114. return reject("Particle system with GPU is not supported.");
  112115. }
  112116. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  112117. scene._removePendingData(token);
  112118. var newData = JSON.parse(data.toString());
  112119. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  112120. }, undefined, undefined, undefined, function (req, exception) {
  112121. scene._removePendingData(token);
  112122. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  112123. });
  112124. });
  112125. };
  112126. /**
  112127. * Static function used to export a particle system to a ParticleSystemSet variable.
  112128. * Please note that the emitter shape is not exported
  112129. * @param system defines the particle systems to export
  112130. */
  112131. ParticleHelper.ExportSet = function (systems) {
  112132. var set = new BABYLON.ParticleSystemSet();
  112133. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  112134. var system = systems_1[_i];
  112135. set.systems.push(system);
  112136. }
  112137. return set;
  112138. };
  112139. /**
  112140. * Gets or sets base Assets URL
  112141. */
  112142. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  112143. return ParticleHelper;
  112144. }());
  112145. BABYLON.ParticleHelper = ParticleHelper;
  112146. })(BABYLON || (BABYLON = {}));
  112147. //# sourceMappingURL=babylon.particleHelper.js.map
  112148. var BABYLON;
  112149. (function (BABYLON) {
  112150. /**
  112151. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  112152. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  112153. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  112154. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112155. */
  112156. var VideoDome = /** @class */ (function (_super) {
  112157. __extends(VideoDome, _super);
  112158. /**
  112159. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  112160. * @param name Element's name, child elements will append suffixes for their own names.
  112161. * @param urlsOrVideo defines the url(s) or the video element to use
  112162. * @param options An object containing optional or exposed sub element properties
  112163. */
  112164. function VideoDome(name, urlsOrVideo, options, scene) {
  112165. var _this = _super.call(this, name, scene) || this;
  112166. _this._useDirectMapping = false;
  112167. // set defaults and manage values
  112168. name = name || "videoDome";
  112169. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112170. options.clickToPlay = Boolean(options.clickToPlay);
  112171. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  112172. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  112173. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112174. if (options.useDirectMapping === undefined) {
  112175. _this._useDirectMapping = true;
  112176. }
  112177. else {
  112178. _this._useDirectMapping = options.useDirectMapping;
  112179. }
  112180. _this._setReady(false);
  112181. // create
  112182. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  112183. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112184. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  112185. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112186. texture.onLoadObservable.addOnce(function () {
  112187. _this._setReady(true);
  112188. });
  112189. // configure material
  112190. material.useEquirectangularFOV = true;
  112191. material.fovMultiplier = 1.0;
  112192. material.opacityFresnel = false;
  112193. if (_this._useDirectMapping) {
  112194. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112195. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112196. material.diffuseTexture = texture;
  112197. }
  112198. else {
  112199. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112200. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112201. material.reflectionTexture = texture;
  112202. }
  112203. // configure mesh
  112204. _this._mesh.material = material;
  112205. _this._mesh.parent = _this;
  112206. // optional configuration
  112207. if (options.clickToPlay) {
  112208. scene.onPointerUp = function () {
  112209. _this._videoTexture.video.play();
  112210. };
  112211. }
  112212. return _this;
  112213. }
  112214. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  112215. /**
  112216. * Gets the video texture being displayed on the sphere
  112217. */
  112218. get: function () {
  112219. return this._videoTexture;
  112220. },
  112221. enumerable: true,
  112222. configurable: true
  112223. });
  112224. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  112225. /**
  112226. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112227. * Also see the options.resolution property.
  112228. */
  112229. get: function () {
  112230. return this._material.fovMultiplier;
  112231. },
  112232. set: function (value) {
  112233. this._material.fovMultiplier = value;
  112234. },
  112235. enumerable: true,
  112236. configurable: true
  112237. });
  112238. /**
  112239. * Releases resources associated with this node.
  112240. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112241. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112242. */
  112243. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112244. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112245. this._videoTexture.dispose();
  112246. this._mesh.dispose();
  112247. this._material.dispose();
  112248. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112249. };
  112250. return VideoDome;
  112251. }(BABYLON.TransformNode));
  112252. BABYLON.VideoDome = VideoDome;
  112253. })(BABYLON || (BABYLON = {}));
  112254. //# sourceMappingURL=babylon.videoDome.js.map
  112255. var BABYLON;
  112256. (function (BABYLON) {
  112257. /**
  112258. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  112259. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  112260. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  112261. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112262. */
  112263. var PhotoDome = /** @class */ (function (_super) {
  112264. __extends(PhotoDome, _super);
  112265. /**
  112266. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  112267. * @param name Element's name, child elements will append suffixes for their own names.
  112268. * @param urlsOfPhoto defines the url of the photo to display
  112269. * @param options defines an object containing optional or exposed sub element properties
  112270. * @param onError defines a callback called when an error occured while loading the texture
  112271. */
  112272. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  112273. if (onError === void 0) { onError = null; }
  112274. var _this = _super.call(this, name, scene) || this;
  112275. _this._useDirectMapping = false;
  112276. /**
  112277. * Observable raised when an error occured while loading the 360 image
  112278. */
  112279. _this.onLoadErrorObservable = new BABYLON.Observable();
  112280. // set defaults and manage values
  112281. name = name || "photoDome";
  112282. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112283. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112284. if (options.useDirectMapping === undefined) {
  112285. _this._useDirectMapping = true;
  112286. }
  112287. else {
  112288. _this._useDirectMapping = options.useDirectMapping;
  112289. }
  112290. _this._setReady(false);
  112291. // create
  112292. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112293. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112294. // configure material
  112295. material.opacityFresnel = false;
  112296. material.useEquirectangularFOV = true;
  112297. material.fovMultiplier = 1.0;
  112298. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  112299. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  112300. if (onError) {
  112301. onError(message, exception);
  112302. }
  112303. });
  112304. _this.photoTexture.onLoadObservable.addOnce(function () {
  112305. _this._setReady(true);
  112306. });
  112307. // configure mesh
  112308. _this._mesh.material = material;
  112309. _this._mesh.parent = _this;
  112310. return _this;
  112311. }
  112312. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  112313. /**
  112314. * Gets or sets the texture being displayed on the sphere
  112315. */
  112316. get: function () {
  112317. return this._photoTexture;
  112318. },
  112319. set: function (value) {
  112320. if (this._photoTexture === value) {
  112321. return;
  112322. }
  112323. this._photoTexture = value;
  112324. if (this._useDirectMapping) {
  112325. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112326. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112327. this._material.diffuseTexture = this._photoTexture;
  112328. }
  112329. else {
  112330. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112331. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112332. this._material.reflectionTexture = this._photoTexture;
  112333. }
  112334. },
  112335. enumerable: true,
  112336. configurable: true
  112337. });
  112338. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  112339. /**
  112340. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112341. * Also see the options.resolution property.
  112342. */
  112343. get: function () {
  112344. return this._material.fovMultiplier;
  112345. },
  112346. set: function (value) {
  112347. this._material.fovMultiplier = value;
  112348. },
  112349. enumerable: true,
  112350. configurable: true
  112351. });
  112352. /**
  112353. * Releases resources associated with this node.
  112354. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112355. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112356. */
  112357. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112358. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112359. this._photoTexture.dispose();
  112360. this._mesh.dispose();
  112361. this._material.dispose();
  112362. this.onLoadErrorObservable.clear();
  112363. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112364. };
  112365. return PhotoDome;
  112366. }(BABYLON.TransformNode));
  112367. BABYLON.PhotoDome = PhotoDome;
  112368. })(BABYLON || (BABYLON = {}));
  112369. //# sourceMappingURL=babylon.photoDome.js.map
  112370. var BABYLON;
  112371. (function (BABYLON) {
  112372. BABYLON.Engine.prototype.createQuery = function () {
  112373. return this._gl.createQuery();
  112374. };
  112375. BABYLON.Engine.prototype.deleteQuery = function (query) {
  112376. this._gl.deleteQuery(query);
  112377. return this;
  112378. };
  112379. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  112380. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  112381. };
  112382. BABYLON.Engine.prototype.getQueryResult = function (query) {
  112383. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  112384. };
  112385. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  112386. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112387. this._gl.beginQuery(glAlgorithm, query);
  112388. return this;
  112389. };
  112390. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  112391. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112392. this._gl.endQuery(glAlgorithm);
  112393. return this;
  112394. };
  112395. BABYLON.Engine.prototype._createTimeQuery = function () {
  112396. var timerQuery = this.getCaps().timerQuery;
  112397. if (timerQuery.createQueryEXT) {
  112398. return timerQuery.createQueryEXT();
  112399. }
  112400. return this.createQuery();
  112401. };
  112402. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  112403. var timerQuery = this.getCaps().timerQuery;
  112404. if (timerQuery.deleteQueryEXT) {
  112405. timerQuery.deleteQueryEXT(query);
  112406. return;
  112407. }
  112408. this.deleteQuery(query);
  112409. };
  112410. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  112411. var timerQuery = this.getCaps().timerQuery;
  112412. if (timerQuery.getQueryObjectEXT) {
  112413. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  112414. }
  112415. return this.getQueryResult(query);
  112416. };
  112417. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  112418. var timerQuery = this.getCaps().timerQuery;
  112419. if (timerQuery.getQueryObjectEXT) {
  112420. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  112421. }
  112422. return this.isQueryResultAvailable(query);
  112423. };
  112424. BABYLON.Engine.prototype.startTimeQuery = function () {
  112425. var caps = this.getCaps();
  112426. var timerQuery = caps.timerQuery;
  112427. if (!timerQuery) {
  112428. return null;
  112429. }
  112430. var token = new BABYLON._TimeToken();
  112431. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112432. if (caps.canUseTimestampForTimerQuery) {
  112433. token._startTimeQuery = this._createTimeQuery();
  112434. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  112435. }
  112436. else {
  112437. if (this._currentNonTimestampToken) {
  112438. return this._currentNonTimestampToken;
  112439. }
  112440. token._timeElapsedQuery = this._createTimeQuery();
  112441. if (timerQuery.beginQueryEXT) {
  112442. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112443. }
  112444. else {
  112445. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112446. }
  112447. this._currentNonTimestampToken = token;
  112448. }
  112449. return token;
  112450. };
  112451. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  112452. var caps = this.getCaps();
  112453. var timerQuery = caps.timerQuery;
  112454. if (!timerQuery || !token) {
  112455. return -1;
  112456. }
  112457. if (caps.canUseTimestampForTimerQuery) {
  112458. if (!token._startTimeQuery) {
  112459. return -1;
  112460. }
  112461. if (!token._endTimeQuery) {
  112462. token._endTimeQuery = this._createTimeQuery();
  112463. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  112464. }
  112465. }
  112466. else if (!token._timeElapsedQueryEnded) {
  112467. if (!token._timeElapsedQuery) {
  112468. return -1;
  112469. }
  112470. if (timerQuery.endQueryEXT) {
  112471. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  112472. }
  112473. else {
  112474. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  112475. }
  112476. token._timeElapsedQueryEnded = true;
  112477. }
  112478. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112479. var available = false;
  112480. if (token._endTimeQuery) {
  112481. available = this._getTimeQueryAvailability(token._endTimeQuery);
  112482. }
  112483. else if (token._timeElapsedQuery) {
  112484. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  112485. }
  112486. if (available && !disjoint) {
  112487. var result = 0;
  112488. if (caps.canUseTimestampForTimerQuery) {
  112489. if (!token._startTimeQuery || !token._endTimeQuery) {
  112490. return -1;
  112491. }
  112492. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  112493. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  112494. result = timeEnd - timeStart;
  112495. this._deleteTimeQuery(token._startTimeQuery);
  112496. this._deleteTimeQuery(token._endTimeQuery);
  112497. token._startTimeQuery = null;
  112498. token._endTimeQuery = null;
  112499. }
  112500. else {
  112501. if (!token._timeElapsedQuery) {
  112502. return -1;
  112503. }
  112504. result = this._getTimeQueryResult(token._timeElapsedQuery);
  112505. this._deleteTimeQuery(token._timeElapsedQuery);
  112506. token._timeElapsedQuery = null;
  112507. token._timeElapsedQueryEnded = false;
  112508. this._currentNonTimestampToken = null;
  112509. }
  112510. return result;
  112511. }
  112512. return -1;
  112513. };
  112514. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  112515. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  112516. };
  112517. // We also need to update AbstractMesh as there is a portion of the code there
  112518. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  112519. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  112520. this._isOccluded = false;
  112521. return;
  112522. }
  112523. var engine = this.getEngine();
  112524. if (engine.webGLVersion < 2) {
  112525. this._isOccluded = false;
  112526. return;
  112527. }
  112528. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  112529. this._isOccluded = false;
  112530. return;
  112531. }
  112532. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  112533. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  112534. if (isOcclusionQueryAvailable) {
  112535. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  112536. this._isOcclusionQueryInProgress = false;
  112537. this._occlusionInternalRetryCounter = 0;
  112538. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  112539. }
  112540. else {
  112541. this._occlusionInternalRetryCounter++;
  112542. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  112543. this._isOcclusionQueryInProgress = false;
  112544. this._occlusionInternalRetryCounter = 0;
  112545. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  112546. // if strict continue the last state of the object.
  112547. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  112548. }
  112549. else {
  112550. return;
  112551. }
  112552. }
  112553. }
  112554. var scene = this.getScene();
  112555. if (scene.getBoundingBoxRenderer) {
  112556. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  112557. if (!this._occlusionQuery) {
  112558. this._occlusionQuery = engine.createQuery();
  112559. }
  112560. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  112561. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  112562. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  112563. this._isOcclusionQueryInProgress = true;
  112564. }
  112565. };
  112566. })(BABYLON || (BABYLON = {}));
  112567. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  112568. var BABYLON;
  112569. (function (BABYLON) {
  112570. /**
  112571. * Class used to generate noise procedural textures
  112572. */
  112573. var NoiseProceduralTexture = /** @class */ (function (_super) {
  112574. __extends(NoiseProceduralTexture, _super);
  112575. /**
  112576. * Creates a new NoiseProceduralTexture
  112577. * @param name defines the name fo the texture
  112578. * @param size defines the size of the texture (default is 256)
  112579. * @param scene defines the hosting scene
  112580. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  112581. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  112582. */
  112583. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  112584. if (size === void 0) { size = 256; }
  112585. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  112586. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  112587. _this._time = 0;
  112588. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  112589. _this.brightness = 0.2;
  112590. /** Defines the number of octaves to process */
  112591. _this.octaves = 3;
  112592. /** Defines the level of persistence (0.8 by default) */
  112593. _this.persistence = 0.8;
  112594. /** Gets or sets animation speed factor (default is 1) */
  112595. _this.animationSpeedFactor = 1;
  112596. _this._updateShaderUniforms();
  112597. return _this;
  112598. }
  112599. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  112600. var scene = this.getScene();
  112601. if (!scene) {
  112602. return;
  112603. }
  112604. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  112605. this.setFloat("brightness", this.brightness);
  112606. this.setFloat("persistence", this.persistence);
  112607. this.setFloat("timeScale", this._time);
  112608. };
  112609. NoiseProceduralTexture.prototype._getDefines = function () {
  112610. return "#define OCTAVES " + (this.octaves | 0);
  112611. };
  112612. /** Generate the current state of the procedural texture */
  112613. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  112614. this._updateShaderUniforms();
  112615. _super.prototype.render.call(this, useCameraPostProcess);
  112616. };
  112617. /**
  112618. * Serializes this noise procedural texture
  112619. * @returns a serialized noise procedural texture object
  112620. */
  112621. NoiseProceduralTexture.prototype.serialize = function () {
  112622. var serializationObject = {};
  112623. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  112624. serializationObject.brightness = this.brightness;
  112625. serializationObject.octaves = this.octaves;
  112626. serializationObject.persistence = this.persistence;
  112627. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  112628. serializationObject.size = this.getSize().width;
  112629. serializationObject.generateMipMaps = this._generateMipMaps;
  112630. return serializationObject;
  112631. };
  112632. /**
  112633. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  112634. * @param parsedTexture defines parsed texture data
  112635. * @param scene defines the current scene
  112636. * @param rootUrl defines the root URL containing noise procedural texture information
  112637. * @returns a parsed NoiseProceduralTexture
  112638. */
  112639. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  112640. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  112641. texture.brightness = parsedTexture.brightness;
  112642. texture.octaves = parsedTexture.octaves;
  112643. texture.persistence = parsedTexture.persistence;
  112644. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  112645. return texture;
  112646. };
  112647. return NoiseProceduralTexture;
  112648. }(BABYLON.ProceduralTexture));
  112649. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  112650. })(BABYLON || (BABYLON = {}));
  112651. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  112652. var __assign = (this && this.__assign) || function () {
  112653. __assign = Object.assign || function(t) {
  112654. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112655. s = arguments[i];
  112656. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112657. t[p] = s[p];
  112658. }
  112659. return t;
  112660. };
  112661. return __assign.apply(this, arguments);
  112662. };
  112663. var BABYLON;
  112664. (function (BABYLON) {
  112665. /**
  112666. * This can helps recording videos from BabylonJS.
  112667. * This is based on the available WebRTC functionalities of the browser.
  112668. *
  112669. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  112670. */
  112671. var VideoRecorder = /** @class */ (function () {
  112672. /**
  112673. * Create a new VideoCapture object which can help converting what you see in Babylon to
  112674. * a video file.
  112675. * @param engine Defines the BabylonJS Engine you wish to record
  112676. * @param options Defines options that can be used to customized the capture
  112677. */
  112678. function VideoRecorder(engine, options) {
  112679. if (options === void 0) { options = null; }
  112680. if (!VideoRecorder.IsSupported(engine)) {
  112681. throw "Your browser does not support recording so far.";
  112682. }
  112683. var canvas = engine.getRenderingCanvas();
  112684. if (!canvas) {
  112685. throw "The babylon engine must have a canvas to be recorded";
  112686. }
  112687. this._canvas = canvas;
  112688. this._canvas.isRecording = false;
  112689. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  112690. var stream = this._canvas.captureStream(this._options.fps);
  112691. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  112692. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  112693. this._mediaRecorder.onerror = this._handleError.bind(this);
  112694. this._mediaRecorder.onstop = this._handleStop.bind(this);
  112695. }
  112696. /**
  112697. * Returns wehther or not the VideoRecorder is available in your browser.
  112698. * @param engine Defines the Babylon Engine to check the support for
  112699. * @returns true if supported otherwise false
  112700. */
  112701. VideoRecorder.IsSupported = function (engine) {
  112702. var canvas = engine.getRenderingCanvas();
  112703. return (!!canvas && typeof canvas.captureStream === "function");
  112704. };
  112705. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  112706. /**
  112707. * True wether a recording is already in progress.
  112708. */
  112709. get: function () {
  112710. return !!this._canvas && this._canvas.isRecording;
  112711. },
  112712. enumerable: true,
  112713. configurable: true
  112714. });
  112715. /**
  112716. * Stops the current recording before the default capture timeout passed in the startRecording
  112717. * functions.
  112718. */
  112719. VideoRecorder.prototype.stopRecording = function () {
  112720. if (!this._canvas || !this._mediaRecorder) {
  112721. return;
  112722. }
  112723. if (!this.isRecording) {
  112724. return;
  112725. }
  112726. this._canvas.isRecording = false;
  112727. this._mediaRecorder.stop();
  112728. };
  112729. /**
  112730. * Starts recording the canvas for a max duration specified in parameters.
  112731. * @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.
  112732. * @param maxDuration Defines the maximum recording time in seconds.
  112733. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  112734. * @return a promise callback at the end of the recording with the video data in Blob.
  112735. */
  112736. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  112737. var _this = this;
  112738. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  112739. if (maxDuration === void 0) { maxDuration = 7; }
  112740. if (!this._canvas || !this._mediaRecorder) {
  112741. throw "Recorder has already been disposed";
  112742. }
  112743. if (this.isRecording) {
  112744. throw "Recording already in progress";
  112745. }
  112746. if (maxDuration > 0) {
  112747. setTimeout(function () {
  112748. _this.stopRecording();
  112749. }, maxDuration * 1000);
  112750. }
  112751. this._fileName = fileName;
  112752. this._recordedChunks = [];
  112753. this._resolve = null;
  112754. this._reject = null;
  112755. this._canvas.isRecording = true;
  112756. this._mediaRecorder.start(this._options.recordChunckSize);
  112757. return new Promise(function (resolve, reject) {
  112758. _this._resolve = resolve;
  112759. _this._reject = reject;
  112760. });
  112761. };
  112762. /**
  112763. * Releases internal resources used during the recording.
  112764. */
  112765. VideoRecorder.prototype.dispose = function () {
  112766. this._canvas = null;
  112767. this._mediaRecorder = null;
  112768. this._recordedChunks = [];
  112769. this._fileName = null;
  112770. this._resolve = null;
  112771. this._reject = null;
  112772. };
  112773. VideoRecorder.prototype._handleDataAvailable = function (event) {
  112774. if (event.data.size > 0) {
  112775. this._recordedChunks.push(event.data);
  112776. }
  112777. };
  112778. VideoRecorder.prototype._handleError = function (event) {
  112779. this.stopRecording();
  112780. if (this._reject) {
  112781. this._reject(event.error);
  112782. }
  112783. else {
  112784. throw new event.error;
  112785. }
  112786. };
  112787. VideoRecorder.prototype._handleStop = function () {
  112788. this.stopRecording();
  112789. var superBuffer = new Blob(this._recordedChunks);
  112790. if (this._resolve) {
  112791. this._resolve(superBuffer);
  112792. }
  112793. window.URL.createObjectURL(superBuffer);
  112794. if (this._fileName) {
  112795. BABYLON.Tools.Download(superBuffer, this._fileName);
  112796. }
  112797. };
  112798. VideoRecorder._defaultOptions = {
  112799. mimeType: "video/webm",
  112800. fps: 25,
  112801. recordChunckSize: 3000
  112802. };
  112803. return VideoRecorder;
  112804. }());
  112805. BABYLON.VideoRecorder = VideoRecorder;
  112806. })(BABYLON || (BABYLON = {}));
  112807. //# sourceMappingURL=babylon.videoRecorder.js.map
  112808. var BABYLON;
  112809. (function (BABYLON) {
  112810. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  112811. if (replace === void 0) { replace = false; }
  112812. // Dispose existing light in replace mode.
  112813. if (replace) {
  112814. if (this.lights) {
  112815. for (var i = 0; i < this.lights.length; i++) {
  112816. this.lights[i].dispose();
  112817. }
  112818. }
  112819. }
  112820. // Light
  112821. if (this.lights.length === 0) {
  112822. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  112823. }
  112824. };
  112825. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  112826. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112827. if (replace === void 0) { replace = false; }
  112828. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112829. // Dispose existing camera in replace mode.
  112830. if (replace) {
  112831. if (this.activeCamera) {
  112832. this.activeCamera.dispose();
  112833. this.activeCamera = null;
  112834. }
  112835. }
  112836. // Camera
  112837. if (!this.activeCamera) {
  112838. var worldExtends = this.getWorldExtends();
  112839. var worldSize = worldExtends.max.subtract(worldExtends.min);
  112840. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  112841. var camera;
  112842. var radius = worldSize.length() * 1.5;
  112843. // empty scene scenario!
  112844. if (!isFinite(radius)) {
  112845. radius = 1;
  112846. worldCenter.copyFromFloats(0, 0, 0);
  112847. }
  112848. if (createArcRotateCamera) {
  112849. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  112850. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  112851. arcRotateCamera.wheelPrecision = 100 / radius;
  112852. camera = arcRotateCamera;
  112853. }
  112854. else {
  112855. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  112856. freeCamera.setTarget(worldCenter);
  112857. camera = freeCamera;
  112858. }
  112859. camera.minZ = radius * 0.01;
  112860. camera.maxZ = radius * 1000;
  112861. camera.speed = radius * 0.2;
  112862. this.activeCamera = camera;
  112863. var canvas = this.getEngine().getRenderingCanvas();
  112864. if (attachCameraControls && canvas) {
  112865. camera.attachControl(canvas);
  112866. }
  112867. }
  112868. };
  112869. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  112870. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112871. if (replace === void 0) { replace = false; }
  112872. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112873. this.createDefaultLight(replace);
  112874. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  112875. };
  112876. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  112877. if (pbr === void 0) { pbr = false; }
  112878. if (scale === void 0) { scale = 1000; }
  112879. if (blur === void 0) { blur = 0; }
  112880. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  112881. if (!environmentTexture) {
  112882. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  112883. return null;
  112884. }
  112885. if (setGlobalEnvTexture) {
  112886. if (environmentTexture) {
  112887. this.environmentTexture = environmentTexture;
  112888. }
  112889. }
  112890. // Skybox
  112891. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  112892. if (pbr) {
  112893. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  112894. hdrSkyboxMaterial.backFaceCulling = false;
  112895. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  112896. if (hdrSkyboxMaterial.reflectionTexture) {
  112897. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112898. }
  112899. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  112900. hdrSkyboxMaterial.disableLighting = true;
  112901. hdrSkyboxMaterial.twoSidedLighting = true;
  112902. hdrSkybox.infiniteDistance = true;
  112903. hdrSkybox.material = hdrSkyboxMaterial;
  112904. }
  112905. else {
  112906. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  112907. skyboxMaterial.backFaceCulling = false;
  112908. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  112909. if (skyboxMaterial.reflectionTexture) {
  112910. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112911. }
  112912. skyboxMaterial.disableLighting = true;
  112913. hdrSkybox.infiniteDistance = true;
  112914. hdrSkybox.material = skyboxMaterial;
  112915. }
  112916. return hdrSkybox;
  112917. };
  112918. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  112919. if (BABYLON.EnvironmentHelper) {
  112920. return new BABYLON.EnvironmentHelper(options, this);
  112921. }
  112922. return null;
  112923. };
  112924. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  112925. if (webVROptions === void 0) { webVROptions = {}; }
  112926. return new BABYLON.VRExperienceHelper(this, webVROptions);
  112927. };
  112928. })(BABYLON || (BABYLON = {}));
  112929. //# sourceMappingURL=babylon.sceneHelpers.js.map
  112930. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  112931. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  112932. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  112933. globalObject["BABYLON"] = BABYLON;
  112934. //backwards compatibility
  112935. if(typeof earcut !== 'undefined') {
  112936. globalObject["Earcut"] = {
  112937. earcut: earcut
  112938. };
  112939. }
  112940. return BABYLON;
  112941. });